text:
Q: Google Sign In with Firebase fails I am trying to implement an Google Auth method using Firebase, but the sign in fails. The Logcat doesn't show me any red text when it fails. I got my SHA 1 set up but it still doesn't work. I use Kotlin.
LoginActivity.kt
package com.example.madistrezsieu

import android.content.Intent
import android.os.Bundle

import android.widget.Toast.LENGTH_SHORT
import android.widget.Toast.makeText
import androidx.appcompat.app.AppCompatActivity
import com.example.madistrezsieu.MainActivity
import com.example.madistrezsieu.R
import com.example.madistrezsieu.view.User
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.GoogleApiClient
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : AppCompatActivity() {
    private var firebaseAuth: FirebaseAuth? = null
    private var authStateListener: FirebaseAuth.AuthStateListener? = null
    private var googleApiClient: GoogleApiClient? = null
    private var rootRef: FirebaseFirestore? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        rootRef = FirebaseFirestore.getInstance()

        google_sign_in_button.setOnClickListener { signIn() }

        firebaseAuth = FirebaseAuth.getInstance()
        authStateListener = FirebaseAuth.AuthStateListener { auth ->
            val firebaseUser = auth.currentUser
            if (firebaseUser != null) {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        }

        val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()

        googleApiClient = GoogleApiClient.Builder(applicationContext)
            .enableAutoManage(this) { makeText(this, "You got a GoogleApiClient Error!", LENGTH_SHORT).show() }
            .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
            .build()
    }

    private fun signIn() {
        val signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient)
        startActivityForResult(signInIntent, RC_SIGN_IN)
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == RC_SIGN_IN) {
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            try {
                val googleSignInAccount = task.getResult(ApiException::class.java)
                if (googleSignInAccount != null) {
                    firebaseSignInWithGoogle(googleSignInAccount)
                }
            } catch (e: ApiException) {
                makeText(this, "Google sign in failed!", LENGTH_SHORT).show()
            }
        }
    }

    private fun firebaseSignInWithGoogle(googleSignInAccount: GoogleSignInAccount) {
        val authCredential = GoogleAuthProvider.getCredential(googleSignInAccount.idToken, null)
        firebaseAuth!!.signInWithCredential(authCredential).addOnCompleteListener(this) {
            val firebaseUser = firebaseAuth!!.currentUser
            if (firebaseUser != null) {
                createUserIfNotExists(firebaseUser)
            }
        }
    }

    private fun createUserIfNotExists(firebaseUser: FirebaseUser) {
        val uid = firebaseUser.uid
        val userName = firebaseUser.displayName
        val user = User(uid, userName!!)

        val uidRef = rootRef!!.collection("users").document(uid)
        uidRef.get().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val document = task.result
                if (!document!!.exists()) {
                    uidRef.set(user)
                }
            }
        }
    }

    public override fun onStart() {
        super.onStart()
        firebaseAuth!!.addAuthStateListener(authStateListener!!)
    }

    public override fun onStop() {
        super.onStop()
        if (firebaseAuth != null) {
            firebaseAuth!!.removeAuthStateListener(authStateListener!!)
        }
    }

    companion object {
        //private val TAG = "LoginActivity"
        private const val RC_SIGN_IN = 123
    }
}

I don't know what the problem could be, should I make another Android Studio project and copy paste the code, and then add another app in the Firebase Project?
LOGCAT
06-12 15:08:23.264 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{c73e49c u0 com.google.android.gms/com.google.android.gms.auth.api.signin.ui.SignInActivity}
06-12 15:08:23.334 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{c73e49c u0 com.google.android.gms/com.google.android.gms.auth.api.signin.ui.SignInActivity}
06-12 15:08:23.374 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{15692e6 u0 com.example.madistrezsieu/com.google.android.gms.auth.api.signin.internal.SignInHubActivity}
06-12 15:08:23.544 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{1ccc6a0 u0 com.google.android.gms/com.google.android.gms.signin.activity.SignInActivity}
06-12 15:08:25.174 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{de116d2 u0 com.google.android.gms/com.google.android.gms.common.api.GoogleApiActivity}
06-12 15:08:26.354 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{1187be7 u0 com.google.android.gms/com.google.android.gms.common.account.OriginalAccountChipAccountPickerActivity}
06-12 15:08:28.044 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{6a14a0b u0 com.google.android.gms/com.google.android.gms.common.account.AccountChipAccountPickerActivity}
06-12 15:08:28.074 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{1ccc6a0 u0 com.google.android.gms/com.google.android.gms.signin.activity.SignInActivity}
06-12 15:08:28.744 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{de116d2 u0 com.google.android.gms/com.google.android.gms.common.api.GoogleApiActivity}
06-12 15:08:28.764 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{c73e49c u0 com.google.android.gms/com.google.android.gms.auth.api.signin.ui.SignInActivity}
06-12 15:08:28.824 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{15692e6 u0 com.example.madistrezsieu/com.google.android.gms.auth.api.signin.internal.SignInHubActivity}
06-12 15:08:28.834 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{d14245b u0 com.example.madistrezsieu/com.example.madistrezsieu.LoginActivity}
06-12 15:08:28.834 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x0 which=0x1 pkg=Window{d14245b u0 com.example.madistrezsieu/com.example.madistrezsieu.LoginActivity}
06-12 15:08:28.894 2897-2897/com.example.madistrezsieu D/WHATTHEFUCK: EROARE
06-12 15:08:33.884 1383-2275/? D/AlarmManager: sending alarm PendingIntent{bcc15b6: PendingIntentRecord{49e31a2 com.whatsapp broadcastIntent}}, i=com.whatsapp.MessageHandler.CLIENT_PINGER_ACTION, t=2, cnt=1, w=2614648, Int=240000
06-12 15:08:46.924 1383-3180/? D/StatusBarManagerService: disable:userId=0 what=0x3200000 which=0x1 pkg=com.android.systemui
06-12 15:08:46.954 1383-1428/? D/StatusBarManagerService: disable:userId=0 what=0x400000 which=0x1 pkg=Window{72431d1 u0 StatusBar}
06-12 15:08:48.854 2930-3536/? I/ContextualWidget: handleMessage, what=1028 mode=GettingOut maxcount=8

A: Just check while setting up the project in firebase , have you added the support email in public setting ?  . As i have faced the same issue few days back , and the only thing which was missing is Support email id in my firebase console .


text:
Q: Не работает docker сейчас я пытаюсь начать работу с docker, но есть некоторые проблемы. Установил его, но он не запускается (выводится ошибка Docker Desktop is shutting down.)
При попытке использования docker В VS code Так же выводится ошибка
(error during connect: This error may indicate that t
he docker daemon is not running.: Post "http://%2F%2
F.%2Fpipe%2Fdocker_engine/v1.24/images/create?fromIm
age=container&tag=latest": open //./pipe/docker_engi
ne: The system cannot find the file specified. )
Пересмотрел множество гайдов, но ничего не помогает. Если кто-то сталкивался с такой проблемой или знает решения, буду благодарен, если вы сможете помочь.
Виртуализацию включил (процессор AMD)
Скачивал через официальный сайт docker (https://www.docker.com/get-started)

redpajama_set_name: RedPajamaStackExchange


text:
Q: SYMFONY ORM Как запретить инверсные значения В чём собственно вопрос - есть такая таблица:
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
*/
private $id;

/**
* @ORM\Column(type="string", length=100)
*/
private $name;
/**
* @ORM\Column(type="string", length=100)
*/
private $slug;
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="id")
* @ORM\JoinColumn(name="parent", referencedColumnName="id", unique=false)
*/
private $parent;

public function __toString() {
    return (String) $this->getParent();
}

/**
* @ORM\ManyToMany(targetEntity="Post", mappedBy="category", cascade={"persist"})
*/
private $posts;

public function __construct() {
    $this->posts = new \Doctrine\Common\Collections\ArrayCollection();
}

Есть ли какой-то уже готовый способ в ORM или в SYMFONY чтобы при добавлении данных в таблицу нельзя было сделать так:

Или же нужно самому перед добавлением данных делать проверку?
Буду очень благодарен за ответы! Спасибо.

A: На уровне маппинга или схемы БД это не запретить. Проверяйте отношения между сущностями на этапе валидации.


text:
Q: Metamodel does not generate field annotated with @Type In a model class I have
@Type(type="balh.JsonConvertType")
@Column(name="tags")
private List<Tag> tags;

The database table contains the column tags which is a varchar column. But when i generate metamodel using JPA then this filed is not generated. How can i make feilds annotate with @Type to be generated into metamodel


text:
Q: how to inject webapp resource using relative path in spring I have a bean which im trying to pass a relative path at web application startup.  It works for an absolute path (running tomcat within eclipse) such as (C:/dev/workspace/project/src/main/webapp/WEB-INF/resource/)
However when  I try to pass it a relative path such as WEB-INF/my_resource/ it says cannot find the location C:/dev/eclipse/WEB-INF/my_resource/ probably because tomcat is running within eclipse.  How can I make this path relative so that it will be always picked up from whatever webcontainer is running it no matter the location of the webapp?
Ive read in place to use the servletconfig.getRelativePath(/) but neither know how to obtain the servlet config from within my bean or even if this is the right thing to do in Spring... Please help
The source code for my bean class and bean configuration xml can be found below
public class SuggestionIndexSearcher extends IndexSearcher {

private String indexSearcherType;

public SuggestionIndexSearcher(String type, String path){
    super(path);
    this.indexSearcherType = type;
}
...
}

The bean is defined in teh beans xml as...
    <bean id="KMSearcherBean" class="com.hp.it.km.search.web.suggestion.SuggestionIndexSearcher">
      <constructor-arg index="0" value="KMSearcher" />
      <constructor-arg index="1" value="WEB-INF/resource/keyword" />
</bean>

A: If your change your bean to take org.springframework.core.io.Resource (javadoc) instead of String, then Spring will automagically coerce your path into the appropriate type of Resource. When running inside a servlet container, Spring will generally pick ServletContextResource, in which the path becomes relative to the webapp root (so WEB-INF/my_resource/ should work as you expect).
How your code chooses to handle Resource depends what you want to do with it, obviously.
No change is required in your XML config, just keep passing the path string as before. See the Spring manual for a wider description of resources.

A: Change the argument type from String to Resource - spring will then do the conversion and give you the resource object which you can process.  You should be using an XMLWebApplicationContext (which is the default if the context is being created by the ContextLoaderListener or DispatcherServlet).
Take a look at this page for more details.


text:
Q: MKMapView doesn't display tiles on highest zoom - appears to be related to iOS 6.1.4 I'm working on an app that is heavily GPS-based.  Everything worked fantastically, specifically meaning my app's display of map tiles worked great, seemingly until I updated my iPhone5 (test device) to iOS 6.1.4.  Yes, I know that 6.1.4 supposedly only touched audio profiles, but this failure to load map tiles certainly coincided with my phone's OS upgrade.
Ever since I updated, not a single application on my phone (any that presumably use MKMapView), except Apple's Maps app, will load any tiles when I attempt to zoom in to the max level.  The tiles change to the gray grids with the Ø symbol.
FYI - when debugging my app, mapViewDidFailLoadingMap:withError: never fires, so the phone doesn't think it has a problem.  It's almost as if they are the tiles Apple is sending to the phone.
Anyway, I tested this on another iPhone5, which had the same problems (and was also updated to 6.1.4), and an iPhone4 and iPad 2 Retina, which did NOT show the symptoms.
Obviously, for my app, I could restrict the max zoom level to get around this, but I'm more concerned about an issue that may not be resolved until another OS update, while restricting the user's/app's capabilities in order to mask the bug.
Has anyone else seen this happen on their own devices, or heard about this happening? I'd think that if this was actually related to 6.1.4, people would be freaking out all over the web, but my web searches turn up nothing.
Other thoughts?
Thanks!


text:
Q: Field labels crispy forms Django I want to use the same model for two forms and change the labels of field how can i change the label?
this is my one form:
class jobpostForm(forms.ModelForm):

    class Meta:

        model = jobpost
        fields = ('job_type','title','company_name','location','country','description','start_date','end_date','how_to_apply')

    widgets = {

        'job_type':RadioSelect(),
        'location':TextInput(attrs={'size':'70','cols': 10, 'rows': 20}),
        'description': TinyMCE(attrs={'cols':'100', 'row': '80'}),
            'start_date':AdminDateWidget(attrs={'readonly':'readonly'}),
            'end_date':AdminDateWidget(attrs={'readonly':'readonly'}),
            'how_to_apply':RadioSelect(),

    }

    def __init__(self, *args, **kwargs):
        super(jobpostForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'horizontal-form'
        self.helper.form_id = 'id-jobpostform'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'

        self.helper.form_action = '/portal/next/post/'

        self.helper.add_input(Submit(_('submit_addcontent'), 'Preview'))

        super(jobpostForm, self).__init__(*args, **kwargs)

like i want to change 'location' to 'Job Location'..how can i do this?

A: There is an easier way to do this. See my example below:
    class CreateAPIKey(forms.ModelForm):

    class Meta:
        model = APIKey
        fields = ["client_id"]
        labels = {
            "client_id": "Nome da Key",
        }
        help_texts = {
            "client_id": _(
                "Um identificador exclusivo de formato livre da chave. 50 caracteres no máximo"
            ),
        }
        widgets = {
            "client_id": forms.TextInput(
                attrs={
                    "id": "key_id",
                    "required": True,
                    "placeholder": "Entre um nome único para a chave",
                    "label": "dasdasdsdasd",
                }
            ),
        }

Then, then rendering the form on the template:
<form class="" method="POST" action="#">
{% csrf_token %}
  <div class="col-md-4 col-sm-12 form-group" data-children-count="1">

    {% for field in form %}
       {{ field|as_crispy_field }}
    {% endfor %}

  </div>
</form>

RESULT:

A: This problem is not really specific for Django Crispy Forms.
One option is to set the label in the init() method of your JobPostForm.
def __init__(self, *args, **kwargs):
    super(JobPostForm, self).__init__(*args, **kwargs)
    self.fields['location'].label = "Job Location"

A good read when dealing with these kind of questions is Overloading Django Form Fields.

A: In my case calling the __init__ on my forms.py file worked
CODE FORMAT:
def __init__(self, *args, **kwargs):

    super(ChangeFormNameHere, self).__init__(*args, **kwargs)

    self.fields['model_filed_default_name'].label = "Your_new_label_name"


text:
Q: Combine Like Terms and Coefficient of One I realize this is a simple question but I am having trouble understanding/remembering some specific rules relating to combining like terms:
why does:
3xy + 2xy = 5xy rather than 3xy + 2xy = 5x2y ?
since y has a coefficient of 1 shouldn't it be
3x1y + 2x1y = 5x2y
Thank you for cleaning up this confusion

A: The constant coefficients in the terms $3xy$ and $2xy$ apply to the entire term, not just to the $x$ because they happen to be next to it: remember that $3xy$ means $3\cdot x\cdot y$.
If in doubt, plug in actual numbers for $x$ and $y$. Suppose we let $x=y=1$. Then $3xy+2xy=3\cdot1\cdot1+2\cdot1\cdot1=3+2=5$, but using your proposed solution, you would end up with $5x2y=5\cdot1\cdot2\cdot1=10$ instead.

A: The distributive law states that $(a + b)c = ac + bc$.
If we set $a = 3$, $b = 2$, and $c = xy$, then $5xy = (3 + 2)xy = 3xy + 2xy$.

A: You can define $z=xy,$ then $3xy+2xy=3z+2z=5z=5xy$ follows the distributive law.  Without defining $z$ you could say $3xy+2xy=(3+2)xy=5xy$ or $3xy+2xy=(3x+2x)y=5xy$

A: Recall that multiplication is associative, so an expression like $2xy$ could be expressed as either $(2x)y$ or $2(xy)$.
So
$$3xy+2xy = (3x)y+(2x)y = 3(xy) + 2(xy) = (3+2)(xy) = 5(xy) = (5x)y = 5xy$$


text:
Q: Show that a group of order 12 cannot have nine elements of order 2. This is what I have so far. Assume the contrary, then by Sylow's Third Theorem, the number of Sylow 3-subgroups is either 1 or 3. If it were 1 then there are only 7 elements of order 2. Thus there are 3 Sylow 2-subgroups. I am trying to wrap this up but I am getting confused. Is it the case that each Sylow 2-subgroup has the identity and 7 elements of order 2?

A: Such a group would have two elements of order $3$. Let $h$ be one of them.
The centraliser of $h$ must have order $6$ or $12$. In any case this centraliser
contains an element of order $2$ whose product with $h$ has order $6$; that's impossible.


text:
Q: How do I prove that a martingale has a constant expected value? I can´t prove that a martingale has constant expected value.
$$
\mathbf{E}[M_t]=\mathbf{E}[M_0]
$$
Thanks people.

A: It holds for any sigma-algebra $\mathcal{F}$ that
$$\mathbb{E}[ \mathbb{E}(X \mid \mathcal{F}) ] = \mathbb{E}(X).$$
Note that this does not require that $\mathcal{F}$ and $X$ are independent. Since a martingale satisfies
$$\mathbb{E}(M_{n+1} \mid \mathcal{F}_n) = M_n,$$
we get
$$\mathbb{E}(M_{n+1}) = \mathbb{E}[\mathbb{E}(M_{n+1} \mid \mathcal{F}_n)] = \mathbb{E}(M_n)$$ for all $n \in \mathbb{N}$. Hence, $\mathbb{E}(M_n) = \mathbb{E}(M_0)$.


text:
Q: HTML image is not displayed My picture is not displayed. I've tried several browsers and different image formats. Unfortunately it doesn't always show up for me.
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Title</title>

A: You need to open your body tag
and the image needs a src attribute, not scr https://www.w3schools.com/tags/att_img_src.asp
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Title</title>

A: Change scr to src in the img tag.
Also put it properly inside a body tag.
Something like this
<!DOCTYPE html>

     <meta charset="utf-8" />
     <title>Title</title>


text:
Q: Find p values so that improper integrals converge Assume that p > 0, find the all the values of p so that the following 2 improper integrals converge :-
$$\int_0^2 \frac{1}{\sqrt[3]{x^{p}-1}} dx $$
$$\int_2^\infty \frac{1}{\sqrt[3]{x^{p}-1}} dx $$
I tried solving them and I got stuck. The first integral must be split into 2 improper integrals between 2 intervals, the first one is between 0 and 1 not  and the second one is between 1 and 2 because the integrand is not continuous in 1. I tried substituting variables but nothing worked. Thanks for any help.

A: HINT
Note that for $x\to 1$
$$x^{p}=(1+(x-1))^p\sim1+p(x-1)\implies \sqrt[3]{x^{p}-1}\sim \sqrt[3] p \sqrt[3]{x-1}$$
then
$$\frac{1}{\sqrt[3]{x^{p}-1}} \sim \frac1{\sqrt[3] p \sqrt[3]{x-1}}$$
and for $x\to \infty$
$$\frac{1}{\sqrt[3]{x^{p}-1}} \sim \frac1{x^{p/3}}$$


text:
Q: Any way to extract the sign of a number in Python? I have am coding the algorithm of Bolzano in Python. This is my code for now:
def Bolzano(fonction, a, b, tol=0.000001):
   while abs(b-a)>tol:
       m=(a+b)/2
       if cmp(fonction(m))==cmp(fonction(a)):
           a=m
       else:
           b=m
   return a, b

It works until it encounters cmp, which it doesn't recognise. However I don't see another way to do it, since Python doesn't have a sign function. Is there any other way to extract the sign of a number?

A:
Is there any other way to extract the sign of a number?

How about writing your own?
Implementation
def sign(num):
    return -1 if num < 0 else 1

Example
>>> sign(10)
1
>>> sign(-10)
-1

Ohh and cmp is a built-in that requires two parameters (numbers) and simply compares them and checks which of them is larger. You should have used it as follows
def Bolzano(fonction, a, b, tol=0.000001):
   while abs(b-a)>tol:
       m=(a+b)/2
       if cmp(fonction(m), fonction(a)) == 0:
           a=m
       else:
           b=m
   return a, b

A: Maybe use:
if cmp(fonction(m),fonction(a)) == 0:

A: def same_sign(a, b):
    return (a * b) >= 0

Examples:
>>> same_sign(3, 4)
True

>>> same_sign(-3, 4)
False

>>> same_sign(3, -4)
False

>>> same_sign(-3, -4)
True

>>> same_sign(-3, 0)
True


text: Q: Testing on staging slot using same config urls as production slot I deployed an Angular app to azure with two slots. One is the staging slot and the other is production slot. The idea is to deploy to staging slot, test and ensure that everything works fine and then swap it with the production slot. I am currently using Microsoft ADAL for authentication of users. Is there a way to test my website using same config urls, redirect urls and 'Application settings' of production in the staging slot or do I have to add the staging slot urls in config file separately for staging slot? My staging slot website is https://my-website-staging.azurewebsites.net and my production website is https://my-website.azurewebsites.net. I would like to replicate all the production stuff in stating slot by browsing to https://my-website-staging.azurewebsites.net but I need to configure adal as well. So what is the best to achieve the desired result?


text:
Q: Crontab did not run as desired I set crontab but nothing happened,
crontab -l
03 04-22 * * * python /me/radio_alarm.py

What's the reason, the command works as intended on Linux.

A: Store the script stdout and stderr:
03 04-22 * * * python /me/radio_alarm.py > log.txt 2>&1

And then check in log.txt, whats the error.
for crontab log, look into /var/log/cron


text:
Q: How to merge a serialized protobuf with a another protobuf without deserializing the first I'm trying to understand if it's possible to take a serialized protobuf that makes up part of another protobuf and merge them together without having to deserialize the first protobuf.
For example, given a protobuf wrapper:
syntax = "proto2";

import "content.proto";

message WrapperContent {

 required string metatData = 1;
 required Content content = 2;

}

And then imagine we get a serialized version of Content below (i.e. Content is coming that is coming from a remote client):
syntax = "proto2";

message Content {

 required string name = 1;
 required bytes payload = 2;

}

Do you know if any way I can inject the serialized Content into the WrapperContent without first having to deserialize Content.
The reason I'm trying to inject Content without deserializing it, is that I'm try and save on the overhead of deserializing the message.
If that answer is, no, it's not possible. That is still helpful.
Thanks, Mike.

A: In protobuf, submessages are stored like bytes fields.
So you can make a modified copy of your wrapper:
message WrapperContentBytes {
 required string metatData = 1;
 required bytes content = 2;
}

and write the already serialized content data into the content field.
Decoders can use the unmodified WrapperContent message to decode also the submessage. The binary data on the wire will be the same so decoders do not know the difference.


text:
Q: Find globally unique elements from lists within dataframe I have a dataframe with a column of terms, like:
In [2]: df = pd.DataFrame(
  ...:     [
  ...:         [123, ["D2334","D7645","D0938","D00001"]],
  ...:         [223, ["A938","D00001","D0938"]],
  ...:         [342, ["B983","D2334"]],
  ...:     ],
  ...:     columns=['ID', 'terms'],
  ...: ).set_index('ID')

In [3]: df
Out[3]:
                             terms
ID
123  [D2334, D7645, D0938, D00001]
223          [A938, D00001, D0938]
342                  [B983, D2334]

I want to get for each ID a list of terms which are globally unique, i.e :
ID       terms
123  ["D7645"]
223   ["A938"]
342   ["B983"]

for example , i want to delete "D2334" because it exist in two or many IDs ...

A: You can collapse all list elements to a single numpy array by stacking the values:
all_terms = np.hstack(df.terms.values)

then you can use numpy's unique to find all unique terms, as well as their frequency, and limit to only unique terms which appear once:
unique, counts = np.unique(all_terms, return_counts=True)
unique_with_only_one_appearance = unique[counts == 1]

Finally, it sounds like you're trying to filter the terms to only include these unique terms:
df['unique_terms'] = df.terms.apply(lambda x: [i for i in x if i in unique_with_only_one_appearance])

This isn't a terribly efficient workflow, and there may be better ways of organizing your data if you are working with large sets of tokens besides pandas. You could always check out the Software Recommendations stack exchange site for tips on tools to use for a dataset like this.

A: In case you import from a csv for instance, you may have an str type instead of your list:
import pandas as pd
import ast

test_df = pd.read_csv('test_df.csv', sep=';')

if isinstance(test_df.iloc[0]['terms'], str): # check type of record terms
    print(type(test_df.iloc[0]['terms']))
    test_df['terms'] = test_df['terms'].apply(ast.literal_eval)

test_df = test_df.explode('terms', ignore_index=True)
test_df.drop_duplicates(subset=['terms', ], keep=False, inplace=True)

print(test_df)

output:
<class 'str'>
    ID  terms
1  123  D7645
4  223   A938
7  342   B983

Not exactly your output but my guess is that you may prefer, having the terms as str rather than between brackets.
ref:
cast str to tuple/list
pd.explode doc


text:
Q: How is the information_schema table in trino updated? We use Trino (https://trino.io/) to connect to HDFS. I discovered that the data in the information_schema tables, for example:
select
  *
from
  information_schema.columns clz
where
  clz.table_catalog = 'hive' and
  clz.table_schema = '<schema_name>' and
  clz.table_name = '<table_name>'

doesn't always match up with what I get if I run
show tables from [schema]

show columns in [schema].[table]

etc. It seems that the show tables/show columns commands pretty much always match up with what I see if I run the hadoop command (hadoop fs -ls ...) to show the contents of the hdfs folder.
So I'm trying to figure out:

*

*why the information_schema doesn't give the same results as show tables/show columns/etc.

*if there is a way to refresh/update information_schema to make it current

Thank you.

A: The information_schema table in Trino just exposes the underlying schema data from each data source. It therefore varies depending on the used data source and connector:

*

*For connectors for an RDBMS such as PostgreSQL it basically just exposes the information schema from PostgresSQL after applying type mapping and such.

*For systems like Hive and Iceberg connectors it exposes the information from the Hive metastore service and the table format.

*For other systems like Elasticsearch or so it is completely different again, but basically always gets the information from the underlying system.

For your specific case it might not match up if some external system also messes around in the object storage and the HMS. Specifically there is also a metadata cache in play with HMS which could be stale.


text:
Q: Setting LayoutManager type inside RecyclerView adapter I'm using a ConcatAdapter to set a header for my RecyclerView. I am using two RecyclerAdapters, one that requires no LayoutManager and one that requires a GridLayoutManager. How do I correctly set a LayoutManager inside the RecyclerAdapter class? I've tried doing it, and it doesn't throw any errors, but the data doesn't display.
@NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.viewholder_card_preview, parent, false);

        int spacing = GridAdapterSpacingUtils.convertIntToDP(context, GRID_VIEW_SPACING);

        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, GRID_VIEW_ROWCOUNT);
        recyclerView.addItemDecoration(new GridAdapterItemDecoration(
                GRID_VIEW_ROWCOUNT, spacing, false)
        );

        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(this);

        return new ViewHolder(view);
    }

No Syntax errors, but I'm unsure what I am doing incorrectly. (The Grid Recycler works fine when I test it without a ConcatAdapter).

This is the Kotlin syntax from the Medium post I followed so I'm not sure what the equivalent Java Syntax is.
class BaseGridConcatAdapter(private val context: Context, private val animalAdapter: AnimalAdapter,private val spanCount:Int) :
    RecyclerView.Adapter<BaseConcatHolder<*>>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseConcatHolder<*> {
        val view = LayoutInflater.from(context).inflate(R.layout.animal_concat_row,parent,false)
        view.rv_animal_concat.layoutManager = GridLayoutManager(context, spanCount)
        return ConcatViewHolder(view)
    }

    override fun getItemCount(): Int  = 1

    override fun onBindViewHolder(holder: BaseConcatHolder<*>, position: Int) {
        when(holder){
            is ConcatViewHolder -> holder.bind(animalAdapter)
            else -> throw IllegalArgumentException("No viewholder to show this data, did you forgot to add it to the onBindViewHolder?")
        }
    }

    inner class ConcatViewHolder(itemView: View): BaseConcatHolder<AnimalAdapter>(itemView){
        override fun bind(adapter: AnimalAdapter) {
            itemView.rv_animal_concat.adapter = adapter
        }
    }
}

https://medium.com/@gsaillen95/how-to-inflate-different-layoutmanagers-for-each-adapter-with-concatadapter-76cdee6266ca

A: Don't set the adapter to the RecyclerView in the adapter,
set it in the activity or in fragment.
for more than one layouts, use ViewType.  you can also use Grid view layout with setSpanSize() to set up the layouts.
check out this image. i am working on it now

A: When using extends RecyclerView.Adapter<RecyclerView.ViewHolder>
there is a callback method for when the RecyclerView is attached, if you do it above and try getting reference to the RecyclerView in onCreateViewHolder it will return null.
@Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        //Change the layout manager here
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, GRID_VIEW_COLUMN_COUNT);
        recyclerView.setLayoutManager(gridLayoutManager);
    }

In my case, I was trying to add multiple LayoutManager types to a concat adapter (e.g HorizontalLayout, VerticalLayout, GridLayout managers). I still don't know if this is possible, but if someone has an answer for this, please post it and I can mark yours correct.


text:
Q: self.navigationcontroller pushs viewcontroller without navigation item I am running out of ideas with this problem.
I have a UITabbarcontroller and 2 Tabs with Navigationcontrollers in there.
I have a set of ViewControllers for the navigation. These ViewControllers are used in the same order on both tabs/navigationcontrollers with slightly different data.
The previous-to-last Viewcontroller is making a NSURLConnection, and in connectionDidFinishLoading: the last viewcontroller should be shown, using this code:
[self.navigationController popToRootViewControllerAnimated:NO];
[self.navigationController pushViewController:lastViewController animated:YES];

This will pop to the root viewcontroller, but will never push the last ViewController.
(Sidenote: This was actually working for quite some time, but stopped working when using this also from the second tabbar's navigationcontroller).
Furthermore, if I comment out the first line:
//[self.navigationController popToRootViewControllerAnimated:NO];
[self.navigationController pushViewController:lastViewController animated:YES];

The last viewcontroller is shown, but misses the back button in the navigation bar, and it's not disabled or something.
I suspect that somehow self.navigationcontroller is returning the wrong navigationcontroller. It's as if the navigationcontroller has "forgotten" about the viewcontroller stack.

*

*Could this be related to connectionDidFinishLoading: being a different thread?

*Has someone a suggestion how to get "the navigationcontroller in this tab" in a different way?

I triple checked the code up and down, I couldn't find anything. The other viewcontrollers before this one are being pushed and popped without any problems.
Thanks for any help on this, I feel stuck!

A: What you said gave me an idea.  I was thinking that self.navigationController may be set to nil after it's pushed, therefore, it's not set when you're pushing the new view controller.  Doing this fixed the problem! :)
UINavigationController *navigationController = self.navigationController;
[navigationController popToRootViewControllerAnimated:NO];
[navigationController pushViewController:lastViewController animated:YES];


text:
Q: SQL Relational query Help Student Do Sport Im doing a test exam where I've gotten stuck on one particular query, in both its SQL code, relational algebra and tuple relational calculus.
here scenario.
I have 3 tables
Student (reg_no, name, address)
Heading
Sport (sportId, title)
Student_Sport(reg_no,sportId,Year,Capacity)
In Capacity Field values are Captain, Vice Captain, Member
I Want to get list of sport that has no captains.
Any one Help Me?

A: SELECT * FROM Sport sp, Student_Sport st WHERE
sp.sportId=st.sportId AND st.Capacity IN ('Vice Captain','Member')

A: There many ways of doing this. Here are two:
SELECT * FROM Sport  s
WHERE NOT EXISTS(SELECT * FROM Student_Sport st WHERE st.sportId = s.sportId AND st.name IN('Captain', 'Vice Captain'))

SELECT * FROM Sport  s
LEFT JOIN Student_Sport st ON st.sportId = s.sportId AND st.Capacity IN('Captain', 'Vice Captain')
WHERE st.sportId IS NULL


text:
Q: Multiple-sample z-test for proportions Let's say I want to do a multiple-sample z-test for proportions. Is there any way to rank them?
How would I compare more than two samples at once?

A: The most commonly used - and fairly basic - multisample extension of a two-sample proportions test (akin to the relationship between two-sample t-tests and ANOVA) is the test of homogeneity of proportions.
When you condition on both margins, this is the same as the chi-square test of independence - same test statistic and degrees of freedom.
Also see here.
Any stats package worth the name will do one of these for you easily.
You don't have to rely on the chi-square approximation; it's possible to do an exact test (either akin to a Fisher test in the 2x2 table, or based on the chi-square statistic itself).
Many packages also make such exact tests straightforward. There's also approaches that don't require you to condition on both margins.
A search here on CV will turn up some useful discussion; a wider internet search has many useful resources.


text:
Q: Error in AWS CDK V2 construct for AWS ECR I have written code to create a repo and a few properties.  Even though I am passing reponame as a string 'testing' as part of an interface, my code is going through the else condition and creating the reponame as undefined+date.
2nd issue: Can you also help me to find the issue for the principal in the permission policy?  I am receiving an error saying props.accountIds.map is wrong: I am passing an array to accountIds.
    import * as ecr from 'aws-cdk-lib/aws-ecr';
    import { Duration, RemovalPolicy, Stack } from 'aws-cdk-lib';
    import { Repository, RepositoryEncryption, TagMutability } from 'aws-cdk-lib/aws-ecr';
    import {AWSAccountDetails} from '../lib/utils/definition';
    import * as cdk from 'aws-cdk-lib';

    export class ecrStack extends cdk.Stack {
        constructor(scope: cdk.App, id: string, props: any ){
        super(scope, id);
        const repository = this.createEcr(props);
        this.createAdditionalProperty(repository,props);
      }
    //Method to check and create the AWS ECR REPO
    private  createEcr( props: AWSAccountDetails): any {

    let imageTagMutability : ecr.TagMutability = ecr.TagMutability.IMMUTABLE;
    let imageScanOnPush : Boolean =true;
    let encryption : ecr.RepositoryEncryption =ecr.RepositoryEncryption.KMS;

    if ( props.imageTagMutability  in ecr.TagMutability ) {
      imageTagMutability =props.imageTagMutability;
    }

    if (typeof props.imageScanOnPush ! == 'boolean'){
      imageScanOnPush =props.imageScanOnPush;
    }

    if (typeof props.encryption ! == 'undefined'){
      encryption =props.encryption;
    }
    if (!props.repositoryName) {
      throw  Error('No repository name provided');
    }

      let repository = ecr.Repository.fromRepositoryName(this, 'ecrRepo', props.repositoryName);
    if (!repository.repositoryArn) {
      // Repository does not exist, create a new one with the original name
      repository=new ecr.Repository(this, props.repositoryName, {
        repositoryName: props.repositoryName,
        imageTagMutability: props.imageTagMutability,
        encryption: RepositoryEncryption.KMS,
        imageScanOnPush: props.imageScanOnPush,
        removalPolicy: RemovalPolicy.DESTROY
      });
    } else {
      const modifiedRepositoryName = `${props.repositoryName}-${Date.now()}`;
      repository= new ecr.Repository(this, modifiedRepositoryName, {
        repositoryName: modifiedRepositoryName,
        imageTagMutability: props.imageTagMutability,
        encryption: RepositoryEncryption.KMS,
        imageScanOnPush: props.imageScanOnPush,
        removalPolicy: RemovalPolicy.DESTROY
      });
    }return repository;
    }
    //Method to add the lifecycle policy,Tags and create aws account permissions.
    private createAdditionalProperty(repository: any, props:AWSAccountDetails) {

      let AgeOfImage :number =180;

      if (typeof props.ImageAge ! == 'undefined'){

          repository.addLifecycleRule({
            rulePriority: 1,
            maxImageAge:Duration.days(AgeOfImage)
          });
        } else {
          repository.addLifecycleRule({
            rulePriority: 1,
            maxImageAge:Duration.days(props.ImageAge)
          });
    }
        //Tags
        const Tags:{[key:string]:string}={
            Name: props.repositoryName,
        }
        //Permission to external aws account to grant permission for ECR pull and push
         //  const policy = new iam.PolicyDocument();
            //policy.addStatements(new iam.PolicyStatement({
             // actions: ['ecr:*'],
              //actions: ['ecr:BatchCheckLayerAvailability', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:PutImage']
           //   resources: [repository.repositoryArn],
           //   principals: props.accountIds.map(id => new iam.AccountPrincipal(id))
           // }));
    }
      addLifecycleRule(arg0: { rulePriority: number; maxImageAge: Duration; }) {
        throw new Error('Method not implemented.');
      }
    }

The interface file:
    import * as ecr from 'aws-cdk-lib/aws-ecr';
    import { ecrStack } from '../ecrstack-stack';

    export interface AWSAccountDetails  {
        ImageCount: any;
        readonly repositoryName :'abcd';   /* Repo Name */
        readonly ImageAge:110; //Number of days before image is deleted.i.e 90.  need to change to imageAge
        readonly imageTagMutability : ecr.TagMutability.IMMUTABLE;  /* If the Repo should  enable Tag Immutability  or not; Default setting is Enabled */
        readonly imageScanOnPush : true; /* If the Repo should enable ScanonPush or not ; Default setting is Enabled */
        readonly encryption : 'KMS'; /* If the Repo should KMS or not  ; Default setting is Enabled for AWS managed KMS Key*/
        readonly accountIds : string //Account number to grant access to pull and push.
        readonly encruptionproperty: 'KMS';

    }

A: I have to pass the props as object and then export to the main stack. This solved the issue.


text:
Q: Adding image in ListView Column I am facing problem in adding image to a column in ListView in wpf. I have two column say x and y and i want to add an image in y column. I have tried a lot. My xaml is below---
 `<ListView Name="listView1" ItemsSource="{Binding}" DataContext="{Binding}" SelectionMode="Single">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Directory" DisplayMemberBinding="{Binding Directory}" />
                <GridViewColumn Header="Status" DisplayMemberBinding="{Binding Status}" >
               </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
 `

and my c# code is below
       public class FolderPath
    {
        public string Directory { get; set; }

        public System.Drawing.Image Status { get; set; }
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
 ObservableCollection<FolderPath> _FolderCollection = new ObservableCollection<FolderPath>();
 BitmapImage b = new BitmapImage();
 b.BeginInit();
 b.UriSource = new Uri(@"C:\Users\smk\Documents\Visual Studio 2010\Projects\Folder_locker\Folder_locker\folder_lock.ico");
 b.EndInit();

 System.Windows.Controls.Image i= new System.Windows.Controls.Image();
 i.Height = 20;
 i.Source = b;

 System.Drawing.Image.FromFile(@"C:\Users\smk\Documents\Visual Studio 2010\Projects\Folder_locker\Folder_locker\folder_lock.ico");

      listView1.Items.Add(new FolderPath { Directory = "something", Status = System.Drawing.Image.FromFile(@"C:\Users\smk\Documents\Visual Studio 2010\Projects\Folder_locker\Folder_locker\folder_lock.ico") });
    }

it displays something in first column but displays nothing in 2nd column.
I have tried both system.windows.controls.image and system.drawing.image both but it does not show image. what can I do?

A: Try a CellTemplate
http://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn.celltemplate.aspx

A: Try this:
public class FolderPath
{
    public string Directory { get; set; }
    public string Status { get; set; }
}

<GridViewColumn Header="Status">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <Image Source="{Binding Path=Status}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

private void button1_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<FolderPath> _FolderCollection = new ObservableCollection<FolderPath>();

    listView1.Items.Add(new FolderPath { Directory = "something", Status = @"C:\Users\smk\Documents\Visual Studio 2010\Projects\Folder_locker\Folder_locker\folder_lock.ico" } )
}


text:
Q: Can lightning actually weld fillings in your teeth? So, I remember sometime in my childhood, someone was teaching me about lightning safety, and they explained that it was important to crouch low but keep as little contact with the ground as possible, if you knew lightning was going to strike.
I understand the purpose of that. They also told me that you should keep your mouth open (screaming if possible) to avoid lightning welding your fillings together if you did get struck. So, my question:
Is it possible for lightning to weld your (metal) fillings together if you get struck and your mouth is closed?

A: Your fillings are either gold / palladium inlays or silver-mercury amalgam. The composite or enamel fillings don't apply here.
Welding fillings together will require that you have fillings in opposing teeth. It is certainly possible to weld metals together with a brief electrical current - it's done by robots in car factories every day. However, it requires quite a bit of current - without doing the math I would guess on the order of hundreds of amperes.
Your head (and, indeed, the tooth with the filling) is not a particularly good conductor of electricity, so the base current needed to weld your teeth together will require a much larger current flowing through your jaw. All those soft, wet squishy bits around your teeth will take some current too, reducing the available welding current and in general heating things up.
Your brain is surrounded by a saline liquid, and it's in a very well sealed solid enclosure (your skull). If we apply enough current across your skull that we have 50-100 amps across two fillings (and remember that this has to happen in the timeline of a lightning strike) we will also see considerable current and resultant heat around your brain. Water + enough heat = steam, and your skull is not a pressure vessel.
So, if your teeth do get welded together after a lightning strike it's really of no concern, because your head will explode.


text:
Q: Returning struct from c++ dll to Python I'm trying to return structure so I can use it in Python. I am beginner programmer so please explain me what am I doing wrong. I've succeeded to return simple ctypes earlier (bool, unsigned int) but struct is too complicated for me. This is what I have:
DLLAPI.h
#define DLLAPI extern "C" __declspec(dllexport)
...
DLLAPI myStruct* DLLApiGetStruct();

DLLAPI.cpp
EDIT1: instead of TString, struct members type is wchar_t* now, but error I get is the same
...
typedef struct myStruct{
    wchar_t* id;
    wchar_t* content;
    wchar_t* message;
} myStruct;

DLLAPI myStruct* DLLApiGetStruct(){
    myStruct* test = new myStruct();
    test->id = _T("some id");
    test->content = _T("some content");
    test->message = _T("some message");
    return test;
}

here is my Python code:
...
class TestStruct(Structure):
    _fields_ = [
        ("id", c_wchar_p),
        ("content", c_wchar_p),
        ("message", c_wchar_p)
        ]
class SomeClass(object):
    ....
    def test(self):
        myDLL = cdll.LoadLibrary('myDLL.dll')
        myDLL.DLLApiGetStruct.restype = TestStruct
        result = myDLL.DLLApiGetStruct()
        print "result type: ", type(result)
        print "-"*30
        print "result: ",result
        print "-"*30
        print result.id # line 152

this is what I get:
    result type:  <class 'Foo.TestStruct'>
    ------------------------------
    result:  <Foo.TestStruct object at 0x027E1210>
    ------------------------------
    Traceback (most recent call last):
    ....
    ....
    ....
    line 152, in test
        print result.id
    ValueError: invalid string pointer 0x00000002

TString I've used is std::wstring
Should type in myStruct be pointers or something instead TString?
Please help me, I've spend 5 days trying to make this work.

A: As the others explained, the problem with version 1 of the question is the use of std::string which is not a valid type for interop.
Looking at version 2 of the question, your C++ and Python declarations do not match. The C++ code returns a pointer to the struct, but the Python code expects the struct to be returned by value.
You could change either C++ or Python to match the other.
C++
DLLAPI myStruct DLLApiGetStruct()
{
    myStruct result;
    result.id = L"some id";
    result.content = L"some content";
    result.message = L"some message";
    return result;
}

Python
myDLL.DLLApiGetStruct.restype = POINTER(TestStruct)

Obviously you must apply only one of these changes!
Note that in the C++ code I chose to use explicit wide strings with the L prefix rather than the _T() macro. The former matches wchar_t* and the latter is what you use with TCHAR. I would not recommend TCHAR these days, unless you need to support Win98.

A: http://docs.python.org/3.1/library/ctypes.html
c_wchar_p contains wchar_t *, not std::wstring

A: The problem is you are returning a structure containing std::string's but you are telling Python that the types are pointers to wchar_t. This has the same effect as doing the following in C++.
struct Foo
{
    std::string id;
    std::string content;
    std::string message;
};

struct Bar
{
    wchar_t* id;
    wchar_t* content;
    wchar_t* message;
};

Foo f;
Bar* = reinterpret_cast<Bar*>(&f);


text:
Q: Functional analysis. Finite-dimensional and infinite-dimensional linear spaces
Show that $C[a,b]$ is infinite-dimensional. Consider the sequence of functions $1, t, t^2, \ldots , t^n,\ldots$ and show that $1, t, t^2, \ldots, t^n$ are linearly independent for any natural $n$. Show that $C^k[a,b]$ also infinite-dimensional.

Please, help me. I don't now how I can start doing it.

A: Let $n \in \mathbb N$ ,  $a_0,a_1,...,a_n \in \mathbb R$ and
$p(t):= a_0+a_1t+...+a_nt^n$.
You have to show: if $p(t)=0$ for all $t \in \mathbb R$, then $a_0=a_1=...=a_n$.
Your turn !

A: Once you have proven that $\{1,t,...,t^{n}\}$ is linearly-independant, the second step could go like this:
If $C[a,b]$ was finite-dimensional, let $N$ be its dimension.
Then any family of $N$ linearly-independant elements of $C[a,b]$ should be a base of $C[a,b]$. For instance, $\{1,t,...,t^{N-1}\}$.
Can you then find a function in $C[a,b]$ that is not a linear combinaison of $\{1,t,...,t^{N-1}\}$ ? That would provide a contradiction and solve the exercise... Don't look too far nor too complicated...


text:
Q: Get apostrophe-workflow localizations to work for a website with multiple blogs I have an ApostropheCMS project that has multiple blogs with articles in each of them. For this purpose, I created a separate module for each blog and separate blog pages, to hold the page and article templates (not very DRY, but I understood that this is the only solution to have multiple blogs, if you don't want to rely on tags).
The website also has a navigation macro that contains a language picker macro, in which the user is shown the current locale and can select a different locale to have the page load in another language. The component looks like this, as suggested in this Stack Overflow answer:
{% macro render() %}
{% set lang = '' %}
{% set activeLocale = apos.workflow.lang() %}
{% for l in apos.workflow.localizations() %}
  {% if l.workflowLocale === activeLocale %}
    {% set lang = l.label %}
  {% endif %}
{% endfor %}
<button type="button" data-role="lang-toggle">
  {{ lang }}
</button>

  {% for locale in apos.workflow.localizations() %}
    {% if locale.workflowLocale !== activeLocale %}

        {{ locale.label }}

    {% endif %}
  {% endfor %}

{% endmacro %}

On the Home page, it works like a charm, I can see the current language on the button and the other languages in the drop-down list.
The problem is that, when I create a page of a different type, for example Blog One Index, apostrophe-workflow doesn't seem to be able to retrieve the docs anymore, and so it is not able to construct the localizations object anymore (there are pages/articles created already under that blog).
I have to admit I'm new to ApostropheCMS and Mongo.js, so it's difficult for me to find out how exactly to solve this issue. I can only see that the method self.getLocalizations() inside node_modules/apostrophe-workflow/lib/api.js uses a criteria named workflowGuid to find the documents, but when I navigate from Home to the blog page, it returns 0 results.

A: Most likely you have replicateAcrossLocales: false configured, as we recommend in our docs. So apart from parked pages like the home page and a few similar cases, no document automatically exists in more than one locale, and self.getLocalizations has no additional versions to find, other than the one in the initial language.
However if you go to that "Blog One Index" page and use the editing UI's palette menu (not a custom one) to try to pick another locale, you will be invited to create that document in the other locale, and then you will start to see another locale available in your getLocalizations queries.


text:
Q: What are the cheap and safe alternatives to storing information in file? I have a tsv file storing some information on AWS S3, but because of concurrent uploads/downloads in a cluster environment, the final state of the file does not always remain as expected due to race conditions.
What are some easy and cheap alternatives to this?
The file size is around 150-200 KB. Using a database or cache would not be cost-effective if we use a managed service.

1. Any way to maintain consistency and do some kind of distributed locking.
2. Any cheap and safe alternatives to storing information in a file would also be very helpful.

Thanks for any help.

A: You may use S3 object locks. With S3 Object Lock, you can store objects using a write-once-read-many (WORM) model. You can use it to prevent an object from being deleted or overwritten for a fixed amount of time or indefinitely. Object Lock helps you meet regulatory requirements that require WORM storage, or simply add another layer of protection against object changes and deletion.
Object Lock provides two ways to manage object retention: retention periods and legal holds.
A retention period specifies a fixed period of time during which an object remains locked. During this period, your object is WORM-protected and can't be overwritten or deleted.
A legal hold provides the same protection as a retention period, but it has no expiration date. Instead, a legal hold remains in place until you explicitly remove it. Legal holds are independent from retention periods.
To use S3 Object Lock, follow these basic steps:
Create a new bucket with Object Lock enabled.
(Optional) Configure a default retention period for objects placed in the bucket.
Place the objects that you want to lock in the bucket.
Apply a retention period, a legal hold, or both, to the objects that you want to protect.
https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lock.html
Also, You can try use DynamoDB. Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It's a fully managed, multi-region, multi-active, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications. DynamoDB can handle more than 10 trillion requests per day and can support peaks of more than 20 million requests per second. https://aws.amazon.com/dynamodb/
DynamoDB also supports locking. DynamoDB supports mechanisms, like conditional writes, that are necessary for distributed locks. However, the AWS SDK doesn't include the logic needed to actually implement distributed locks, so this is up to You to implement. There are several examples for that, you may find it here: https://aws.amazon.com/blogs/database/building-distributed-locks-with-the-dynamodb-lock-client/ And here: https://formidable.com/blog/2020/distributed-locking/


text:
Q: NetBeans error: package org does not exist I just installed Netbeans IDE. I am now unable to import any org.* libs and it just says package org does not exist.
Also, I imported jdic.jar into the project and even though the code completion suggestions show up as org.jdesktop.*, it shows the same error.
How do I fix this?

A: I did it easily, just click the Jframe, on Navigator tab, right-click -> Set Layout -> Absolute Layout and YEP, It works for me.

A: org.netbeans.lib.awtextra is part of the AbsoluteLayout library. It should be added automatically by the ide whenever absolutelayout is used in the form. But if you switch to some other layout after using absolute layout, then the jar/library will be removed from the classpath and existing code making calls to the library will not compile.

*

*If you would like to use absolute layout, then please include the library in the project. Select 'Libraries' node in the project, right-click and select 'Add Library' and select 'Absolute Layout' library from the list of available libraries.

*If you do not wish to use absolute layout, then it is best to uncomment/remove code relying on the library and re-do the form design using the new layout.

A: Clearing the cache fixed it.
In windows 7 the cache is located in
C:\Users\username\AppData\Local\NetBeans\...

On Linux, the cache is at:
/home/username/.cache/netbeans/...

On clearing the cache, and restarting netbeans, it started to recognize org.* imports again.

A: Can you try importing
import org.xml.sax.Attributes;

This is part of the JDK.  If you can't find that, something is really wrong.

I suspect you need to add the libraries to your maven pom.xml file.

A: You should redirect all the lost .jar files by exiting netbeans, then reopening it. There should be a prompt asking you to help the IDE find the .jar files. So please do so. If you aren't able to find the jar file. Clean and build the individual packages. There a new directory called a dist directory will be created in the package directory. Now you can redirect them.

A: Above was not working for me so I tried below and its working:

*

*Google "absolutelayout.jar download"

*Download jar

*Open NetBeans and Add this "AbsoluteLayout-RELEASE***.jar" file to your project Library folder.

*now try to run the project/file

A: in my experience the problem was with a Jpanel with AbsoluteLayout, I put free-design and solved the problem


text:
Q: ioctl vs netlink vs memmap to communicate between kernel space and user space Got some statistics information of our custom hardware to be displayed whenever user asks for using a command in the Linux user space. This implementation is currently uses PROC interface. We started adding more statistics information then we encountered a problem wherein the particular statistics command had to be executed twice for getting the entire data as PROC interface was restricted to 1 page.
As mentioned above the data transfer between the kernel and the user space is not critical but as per the data some decisions might be taken by the user. Our requirement for this interface design is that it should be capable of transferring amount of data maybe greater that 8192 bytes and the command needs to use minimal kernel resources (like locks etc.,)  and it needs to be quick.
Using ioctl can solve the issue but since the command is exactly not controlling the device but to collect some statistics information, not sure whether it is a good mechanism to use as per Linux. We are currently using 3.4 kernel; not sure whether Netlink is lossy  in this version (Previous versions I came across issues like when the queue becomes full, socket starts to drop data). mmap is another option . Can anyone suggest me what would be the best interface to use

A: *

*Kernel services can send information directly to user applications over Netlink, while you'd have explicitly poll the kernel with ioctl functions, a relatively expensive operation.

*Netlink comms is very much asynchronous, with each side receiving messages at some point after the other side sends them. ioctls are purely synchronous: "Hey kernel, WAKE UP! I need you to process my request NOW! CHOP CHOP!"

*Netlink supports multicast communications between the kernel and multiple user-space processes, while ioctls are strictly one-to-one.

*Netlink messages can be lost for various reasons (e.g. out of memory), while ioctls are generally more reliable due to their immediate-processing nature.
So If you asking for statistics to kernel from user space(application) it is more reliable and easy to use IOCTL while if you generate statistics in kernel space and you want your kernel space to send those data to user space(application) you have to use Netlink sockets.

A: You can do a ioctl IO call (rather than IOR, IOW, or IORW). Ioctl's can be very useful for collecting information. You'll have a lot of flexibility this way in that you can pass different size buffers or structs to fill with data.


text:
Q: why am I getting a horizontal solid strip when projecting large image? I am using Mapnik to create tiles on a tile server.  I'm depicting sea level rise in North America using SRTM data, and it works fine in most of the continent.  However, when zoomed out in my browser (zoom levels 5 and lower), I get a peculiar horizontal stripe across the entire continent:

When I am zoomed farther in, this stripe does not appear, which makes me think it's not an issue with the data itself.  The stripe is from 51 degrees N to 52N.  I suspect it's some sort of projection issue, but I'm not sure how to troubleshoot.
Mapnik is being used with Tirex; it is reading from a .vrt file which in turn references ~2400 tifs.

A: For those who may be interested:  the problem seems to have been that my .vrt had coordinates that spanned across the -180 longitude.  Left was a pixel or two beyond the line (-180.00004) and right was ~0 degrees).  Clipping it seems to have solved the problem.


text:
Q: How to solve List is not callable in python? I am new to python and I have encounter this List is not callable error.
What should I do to prevent this from happening? Thanks!
def PrintTxt(src, beg, end):
    with open(src, 'r') as f1:
        srctxt = f1.readlines()
        for line in srctxt(beg, end):
            print(line)

Filepath = 'C:\test.txt'

PrintTxt(Filepath,1,5)

A: You seem to be unaware of the correct Python slice notation. After:
srctxt = f1.readlines()  # now srctxt is a list

you can slice the resulting list like:
for line in srctxt[beg:end]:
    # ....


text:
Q: Is there an STL comparator for std::set (or std::map) with shared_ptr keys that provides value-based lookups? What exactly does std::owner_less do? I have a std::map with shared_ptr<T> keys, and I need it to use the actual value (of type T, i.e. *key) for lookups, not the value of the shared pointer itself.
I know I can write my own custom comparator (as I've done below),  but I was  wondering if the STL supplies a comparator specifically for this purpose.
To demonstrate what I'm talking about, I created this simple example that uses a std::set of strings (I've also put it on GitHub as a gist):
#include <set>
#include <string>
#include <memory>
#include <iostream>
#include <functional>

template< typename T >
struct shared_ptr_comparator {
  bool operator()(const std::shared_ptr<T> &a, const std::shared_ptr<T> &b) const {
    return std::less<T>()(*a, *b);
  }
};

void ptr_set_with_custom_comparator() {
    std::set< std::shared_ptr<std::string>, shared_ptr_comparator<std::string> > ptr_set;

    ptr_set.insert(std::make_shared<std::string>("world"));
    ptr_set.insert(std::make_shared<std::string>("hello"));
    ptr_set.insert(std::make_shared<std::string>("abc"));

    for(auto const& entry : ptr_set) {
        std::cout << *entry << std::endl;
    }
}

void ptr_set_with_owner_less() {
    std::set< std::shared_ptr<std::string>, std::owner_less<std::shared_ptr<std::string>> > ptr_set;

    ptr_set.insert(std::make_shared<std::string>("world"));
    ptr_set.insert(std::make_shared<std::string>("hello"));
    ptr_set.insert(std::make_shared<std::string>("abc"));

    for(auto const& entry : ptr_set) {
        std::cout << *entry << std::endl;
    }
}

void raw_set() {
    std::set<std::string> raw_set;

    raw_set.insert("world");
    raw_set.insert("hello");
    raw_set.insert("abc");

    for(auto const& entry : raw_set) {
        std::cout << entry << std::endl;
    }
}

int main() {
    std::cout << "A basic set of strings:" << std::endl;
    raw_set();
    std::cout << std::endl;

    std::cout << "A set of shared_ptr<string>s with owner_less as the comparator:" << std::endl;
    ptr_set_with_owner_less();
    std::cout << std::endl;

    std::cout << "A set of shared_ptr<string>s with the comparator shared_ptr_comparator:" << std::endl;
    ptr_set_with_custom_comparator();

    return 0;
}

The code above can be complied with clang++ -Wall -std=c++11. Here's the output:
A basic set of strings:
abc
hello
world

A set of shared_ptr<string>s with owner_less as the comparator:
world
hello
abc

A set of shared_ptr<string>s with the comparator shared_ptr_comparator:
abc
hello
world

Here, a sorted ordering when iterating and printing the contents std::set implies that the _actual underlying values) are being compared. A quick overview of the example above:

*

*The function raw_set just uses set<string> (doesn't use shared_ptr), and is present for reference.

*I am able to achieve what I want with my hand-written shared_ptr_comparator. The function ptr_set_with_custom_comparator which utilizes it, works as expected.

*The function ptr_set_with_owner_less did not work as expected. Does owner_less (or owner_before) rely on the addresses/values of the pointers themselves?
I have two questions:

*

*Does anything equivalent to shared_ptr_comparator (defined in the program above), exist in the STL? I ask because the comparator I wrote seems like a really common use case, and I would be very surprised if the STL didn't have anything equivalent to it.

*What exactly does owner_less and owner_before (which it calls) do? Do they simply check for equivalence of the underlying pointers? I'm not sure if I'm using it right.
Thanks in advance for any answers to this question.

A:
Does anything equivalent to shared_ptr_comparator (defined in the program above), exist in the STL? I ask because the comparator I wrote seems like a really common use case, and I would be very surprised if the STL didn't have anything equivalent to it.

I'm suprised too, but no, STL doesn't have built-in comparator for pointers that works this way. However there's better way to implement it which allows passing any pointer.
template<typename T, typename comp_t>
bool ptr_compare(T lhs, T rhs, comp_t comp) {
    return comp(*lhs, *rhs);
}

You can call it that way:
ptr_compare(a_ptr, b_ptr, std::less<int>())

And if you want a version compatible with STL containers:
template<typename T>
bool ptr_less(T lhs, T rhs) {
    return std::less<decltype(*lhs)>()(*lhs, *rhs);
}

What exactly does owner_less and owner_before (which it calls) do? Do they simply check for equivalence of the underlying pointers? I'm not sure if I'm using it right.

std::owner_less doesn't compare by value, but by owner, so it isn't relevant to your problem.
std::shared_ptr<T>::owner_before is called by std::owner_less to find out the ordering.


text:
Q: Separate last column from the actual dataset using numpy I have a dataset in csv format (without headers) where I want to split it into two parts: (1) The actual dataset without the last column, (2) the last column (class label). My dataset has 100K rows and 65 features ( where the last column, column 65, is the class label that I want to separate). I wrote the following:
dataset_path = 'dataset.csv'

dataset = np.genfromtxt(dataset_path, delimiter=',')
class_label = dataset[:-1]
dataset.drop(class_label, axis=1, inplace=True)

print dataset.shape
print class_label

This is in fact wrong. I am not able to achieve what I want. Any help is appreciated.

A: assuming that your dataset is without header
class_label = dataset[:, -1] # for last column
dataset = dataset[:, :-1] # for all but last column

A: In case you are interested in using numpy arrays, you can read your data in the csv file into a numpy array:
 from numpy import genfromtxt
 my_data = genfromtxt('E:\Book1.csv', delimiter=',', dtype = 'str',  skip_header=1, unpack=True)

each item in my_data will be a list of each column in your csv file.
 Now you can remove the last column by:
 my_data_without_last_column = my_data[:-1].copy()

A: using [-1] and class_label will still be columns
class_label = dataset[:, [-1]]


text:
Q: Fetch number from and String List from firestore I want to fetch field values in my app and  access  values from firebase Here's how DB looks like

  private FirebaseFirestore firestore;
    static List<String> categoryist =new ArrayList<>(  );

     protected void onCreate(Bundle savedInstanceState) {
            super.onCreate( savedInstanceState );
            setContentView( R.layout.activity_categories );

            firestore = FirebaseFirestore.getInstance();
            loadData();
    }

    loadData(){

    private void loadData() {

            categoryist.clear();

            firestore.collection( "Online Class" ).document("Subjects")
                    .get().addOnCompleteListener( new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if(task.isSuccessful()){
                        DocumentSnapshot doc = task.getResult();

                        if(doc.exists()){

 /*Here i also tried to use int and long data type but it is still giving same error with nul pointer Exception*/

                            Integer count = new Integer( (Integer) doc.get("No_of_subjects") );
                            for (int i = 1; i<=count;i++){
                                String subjectName = doc.getString( "Subject "+String.valueOf( i ) );
                                categoryist.add( subjectName );
                            }

                        }
                        else {
                            Toast.makeText( CategoriesActivity.this,"No Subject Exists" ,Toast.LENGTH_SHORT).show();
                            finish();
                        }

                    }else {

                        Toast.makeText( CategoriesActivity.this,task.getException().getMessage() ,Toast.LENGTH_SHORT).show();
                    }

                }
            } );

        }

    }

Here I am getting this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference

Any Help is appreciated


text:
Q: Retrieve first word in list index python I want to know how to retrieve the first word at list index.
For example, if the list is:
['hello world', 'how are you']

Is there a way to get x = "hello how"?
Here is what I've tried so far (newfriend is the list):
x=""

for values in newfriend:
        values = values.split()
        values = ''.join(values.split(' ', 1)[0])
        x+=" ".join(values)

x+="\n"

A: A simple generator expression would do, I guess, e.g.
>>> l = ["hello world", "how are you"]
>>> ' '.join(x.split()[0] for x in l)
'hello how'

A: You're not far off.  Here is how I would do it.
# Python 3
newfriend = ['hello world', 'how are you']
x = []  # Create x as an empty list, rather than an empty string.
for v in newfriend:
    x.append(v.split(' ')[0])  # Append first word of each phrase to the list.

y = ' '.join(x)  # Join the list.
print(y)

A: import re
#where l =["Hello world","hi world"]
g=[]
for i in range(l):
   x=re.findall(r'\w+',l[i])
   g.append(x)
print(g[0][0]+g[1][0])


text:
Q: Ajax call returnign [object HTMLInputElement] i am learning ajax and doing some practice. I am facing a problem. Here is my code.
<input class="category" id="design" type="button" value="Design" onclick="loadXMLDoc(design)" />

Ajax:
function loadXMLDoc(name)
{
 var xmlhttp;
 if (window.XMLHttpRequest)
 {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }
 else
 {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
    xmlhttp.onreadystatechange=function()
   {
     if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {

    var array = xmlhttp.responseText;
    alert(array);

     }
   }
  xmlhttp.open("GET","server.php?cat="+name,true);
  xmlhttp.send();
 }

server.php:
if(isset($_GET['cat']))
{
    $cat = $_GET['cat'];
    echo $cat;

}

Now, when i click on the button, the alter gives me [object HTMLInputElement] when i am expecting to get "design". What is wrong in it?

A:
What is wrong in it?

You have to pass a string to the function:
onclick="loadXMLDoc('design')"

Currently you are passing the variable design. Since you have an element with ID "design" this variable happens to refer to that element. Then when you are trying to send the element to the server it is converted to a string. The default string representation of an input DOM element in JavaScript is "[object HTMLInputElement]".

A: Try this :
onclick="loadXMLDoc(this.value)"


text:
Q: How to specifically extract files that are in a 7z archive I have a 7z archive that i downloaded from practicalsecurityanalytics.com that contains malware files and benign files of 117GB.
The compressed size of this file is 43.8GB which is large and i do not want to extract the whole archive at once.
Is there a way so that i can specifically extract a few selected files
The selected files are not sequential so that i can't really rely on GUI and select individual files.

File details
metric

Samples
201,549

Legitimate
86,812

Malicious
114,737

Compressed Size
43.8GB

Uncompressed Size
117GB

There is a csv file called samples.csv that shows which file is malware and which is not and the entropy of the file
The file is encrypted so it asks for a password every time I want to extract something.
I am working in linux.

A: A quick way I extracted the specific files is first add all the file names into a text file like this
228161
213960
200290
210832
230546
257545
....

and wrap the file names around like this by using any method (i used a python script to quickly do it) and save it a file - here f1.txt
pe-machine-learning-dataset/samples/228161
pe-machine-learning-dataset/samples/213960
pe-machine-learning-dataset/samples/200290
pe-machine-learning-dataset/samples/210832
pe-machine-learning-dataset/samples/230546
pe-machine-learning-dataset/samples/257545
....

and now executing
7z e foo.7z -o"path to save the files" $(cat f1.txt)

A: One of the 7zip command line options is to extract from an archive but only specific files by name:

*

*Install the 7zip program on Linux (eg, on Ubunutu sudo apt-get install 7zip)

*Run 7zz e yourarchive.7z thefileyouwanttoextract -p archivepassword
You may have to run it via a loop from your CSV if you only want some of the files.


text:
Q: Why is the subjunctive used here? Is the use of the subjunctive correct in this sentence--
"Though he were the speaker, I would say the same."

A: No, the sentence is not correct because the opening clause is not subjunctive.
It begins with "though", which means "despite the fact that..". If something is fact, it isn't hypothetical.
A subjunctive statement would begin...

If he were the speaker..."

But it would make no sense to say "If he were the speaker I would say the same" - how can you say the same as something that hasn't been said?
It would make sense to say:

Though he was the speaker, I would have said the same.

The subjunctive statement is what you would have said, if you had been the speaker, not what the actual speaker did say in the past.
If you wanted to open with a subjunctive clause, you could say:

If I had been the speaker, I would have said the same.


text:
Q: Google Places direction API Autocomplete set the initial location I m using draggable markers + 2 autocompletes to get directions.
https://developers.google.com/maps/documentation/javascript/examples/directions-draggable.
I have a listener who catch events when marker has a new position.
  google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
                var place1 = autocompleteFrom.getPlace();
                var coord1 = [place1.geometry.location.lat(), place1.geometry.location.lng()];

               var place2 = autocompleteTo.getPlace();
                var coord2 = [place2.geometry.location.lat(), place1.geometry.location.lng()];
            });

The problem is autocompleteFrom.getPlace() returns undefined when user has not enter a place in the autocomplete search box.
Is it possible to setup a default location for the autocompletes ?

A: I am sorry because I don't have enough reputation to comment.
You could set default location for place1, this is more simple than set default for autocompleteform.


text:
Q: How to handle two segues going to the same view controller? I have an iPhone app I'm currently building in XCode 4.3 with Storyboard.  I have a "root" view controller with two (2) seques to a view controller containing a UIWebView.  I want to be able to identify the segue (have already set unique identifiers for both segues) so I can "push" the correct content to the UIWebView, based on which segue was activated in the "root" view controller.
I think I have to use "prepareForSegue" method, but don't know where it would go.  Where can I find out how to deal with two segues going to the same view controller?  (I have google'd it and found nothing appropriate to my situation).
Here is the code that I'm using:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"helpSegue"]) {
        NSLog(@"helpSegue");
    }
    else if ([segue.identifier isEqualToString:@"reportSegue"]) {
        NSLog(@"reportSegue");
    }
}

A: You won't call -prepareForSegue:sender:, you'll implement it in your view controller. In it's override of that method, you can check the segue's identifier property (the segue is passed in as a parameter):
if ([segue.identifier isEqualToString:@"Segue Numero Uno"]) {
    // do something here
}

That lets you take some sort of action depending on which segue is causing the transition. You can set the identifier for each segue in the storyboard editor.
Update: Based on the code you provided in your comment (which I've added to your question), you've got the right idea now. At this point, it's just a matter of good old fashioned debugging. Some things to check:

*

*Is the view controller in your storyboard (i.e. the one that the segues in question lead to) set up as an instance of the class which implements this -prepareForSegue:sender:? Check the controller's type in the storyboard.

*Do the strings you use in your code exactly match the identifiers that you set for your segues in the storyboard? Capitalization, spelling, punctuation, and white space all count.

*Is your -prepareForSegue:sender: method being called? Put a breakpoint there and debug. If it is being called, what is the identifier for the segue that's passed in? If it's not being called, the view controller in the storyboard doesn't have the right class.


text:
Q: add search criteria PHP/MySQL I have some code which display's products from a MySQL database. The products shown match a search the user has entered.
Here is my code:
  $result=mysql_query("SELECT * FROM products WHERE catagory  = '$catagory' ")

In the database i also have a column called active, How do i only show reults that match the search criteria (catagory) and have a 1 in the the active box?
Thanks in advance.

A: $result=mysql_query("SELECT * FROM products WHERE catagory  = '$catagory' AND active = '1' ")

Make sure you are escaping the $category variable before using it in your query to prevent mysql injection exploits and please consider upgrading to a modern database api such as mysqli or PDO.


text:
Q: Postgresql regexp_substring I have a text as
Revision:3336179e1ebaa646cf281b7fb9ff36d1b23ce710$ modified $RevDate:10-04-2017 11:43:47$ by $Author:admin

Could you help me out with writing sql query that would get the first 6 chars of revision (333617) and date of RevDate (10-04-2017 11:43:47)? Thanks in advance.
I tried to get revision as
select (regexp_matches ('$Revision:3336179e1ebaa646cf281b7fb9ff36d1b23ce710$ modified $RevDate:10-04-2017 11:43:47$ by $Author:admin$',
'^\$Revision:(a-z0-9+)\$'))[1]

No luck

A: I'd rather go with substr and split_part (they are faster if I'm not mistaken):
t=# with v as (select 'Revision:3336179e1ebaa646cf281b7fb9ff36d1b23ce710$ modified $RevDate:10-04-2017 11:43:47$ by $Author:admin'::text l)
select substr(l,length('Revision:')+1,6),substr(split_part(l,'$',3),length('RevDate:')+1)
from v;
 substr |       substr
--------+---------------------
 333617 | 10-04-2017 11:43:47
(1 row)

A: If regular expressions are preferred, the fixed-up expression would be:
select a[1] as revision, a[2] as date from (
  select regexp_matches('$Revision:3336179e1ebaa646cf281b7fb9ff36d1b23ce710$ modified $RevDate:10-04-2017 11:43:47$ by $Author:admin$',
 'Revision:([a-z0-9]{6}).*RevDate:([^\$]+)') a ) atbl;


text:
Q: Not able to understand the skew symmetry property in Flow Network From Wikipedia:

$G(V,E)$ is a finite directed graph in which every edge $\ (u,v) \in
 E$ has a non-negative, real-valued capacity $\ c(u,v)$. A flow network
  is a real function $\ f:V \times V \rightarrow \mathbb{R}$ with the
  following three properties for all nodes $\ u$ and $\ v$:
Capacity constraints: ...
Skew symmetry:    $\ f(u,v) = - f(v,u)$. The net flow from $\ u$ to $\ v$ must be the opposite of the net flow from $\ v$ to $\ u$.

What exactly is the use of Skew symmetry? I didn't see this property being used anywhere? Basically whats the use of keeping a negative flow from v to u?

A: This is not entirely standard - different sources do this differently. If we do use skew-symmetry, then the advantage is that the expression $$\sum_{v \in V} f(v,w)$$ represents the net flow into a vertex $w$: the total flow entering $w$, minus the total flow leaving $w$. This is because (with skew-symmetry) the expression $f(v,w)$ represents both the flow entering $w$ via edge $(v,w)$ and (with a negative sign) the flow leaving $w$ via edge $(w,v)$.
The other approach to representing flows, which I'll define with a function $g$ to distinguish it, is to represent only the flow from $v$ to $w$ by $g(v,w)$, and require $0 \le g(v,w) \le c(v,w)$. In cases where $(v,w)$ and $(w,v)$ are both edges with positive capacity, both $g(v,w)$ and $g(w,v)$ could be positive, independently, though this is redundant. (For example, rather than sending $2$ flow from $v$ to $w$ and $1$ flow from $w$ to $v$, it's equivalent to only send $1$ flow from $v$ to $w$, and $0$ flow from $w$ to $v$.)
Then $g(v,w)$ is simpler to understand (it only represents one thing) but the net flow into a vertex $w$ has a more complicated expression: it is given by $$\sum_{v \in V}g(v,w) - \sum_{v \in V} g(w,v).$$ The first sum represents the flow into $w$, and the second sum represents the flow out of $w$.
We can go back and forth between the two representations:

*

*Knowing $g$, we can define $f(v,w) = g(v,w) - g(w,v)$, which will satisfy skew-symmetry.

*Knowing $f$, we can define $g(v,w) = \max\{0, f(v,w)\}$: when $f(v,w)$ is positive, $g(v,w)$ will represent the same flow from $v$ to $w$, and when $f(v,w)$ is negative, $f(w,v)$ will be positive and $g(w,v) = f(w,v)$ will represent that flow from $w$ to $v$.


text:
Q: Menu is initially open on page load, should be closed until clicked This may be a silly question but I cannot figure out why my menu displays when the page is loaded. I would like to have it closed and then opened when it is clicked but it is the other way around and I can't seem to fix it.

CLOSE

                Lighting + Video

                Photograms

                About

A:

$(document).ready(function(){
  $('#nav p')
    .css({cursor: "pointer"})
    .on('click', function(){
      var txt =  $(this).text() === "MENU"?"CLOSE":"MENU"; // 3 egals verification
      $(this).text(txt);
      $(this).next('ul').toggle();
  })
  });
ul{
  display: none; /* ADD this */
}

CLOSE

Lighting + Video

Photograms

About

A: You can do most of the stuff from CSS. Create .closed class and assign it to #nav.
#nav.closed > ul{
  display: none;
}

That's it. You are done with minor changes in jQuery click event!
See the snippet below.

$(document).ready(function(){
  $('#nav p').on('click', function(){
      $(this).parent().toggleClass("closed");
    });
  });
#nav{
  cursor: pointer;
}
#nav.closed p::after{
  content : "CLOSE";
}
#nav p::after {
  content: "MENU";
}
#nav.closed > ul{
  display: none;
}

      Lighting + Video

      Photograms

      About


text:
Q: UITextField validation for email, password, name I am developing a register functionality in my app. I have some UITextFields like Email, password, username, first name.... and I want to validate them before I make the request to the server with the information. Now I validate them when I close the keypad doing this:
  -(BOOL) textFieldShouldReturn:(UITextField *)textField{

          if (textField == emailTextField)
        {
            if(emailTextField.text.length > 5){
                if(![self validateEmailWithString:emailTextField.text])
                {
                    // user entered invalid email address
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
 message:@"Enter a valid email address." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                    [alert show];
                    return NO;
                    //email.text=@"";
                } else {
                    [self.emailDelegate sendEmailForCell:emailTextField.text];
                    [textField resignFirstResponder];
                    return YES;

                }
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Email address too Short" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                [alert show];

                return NO;
            }
        }
        return YES;
    }

    - (BOOL) validateEmailWithString:(NSString *)emailStr
    {
       NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
             return [emailTest evaluateWithObject:emailStr];
    }

But, when I do not close the keyPad with textFieldShouldReturn method I can not validate the UITextField where I am typing. I mean, when I click on the next UITextField before I press return key in the keypad I can type in the next UITextField and textFieldShouldReturn never has been called.
So, I guess I should use this method - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string but I do not want to show to the user that it is an invalid email(or pass, or whatever) every time he types a letter.
So, my question is How could I manage this validation when the user stops typing letters in the keyboard but before he close the keypad?
Another question. Could I store in a variable the Boolean of this method shouldChangeCharactersInRange?
Thank you

A: Do the validation in the textFieldDidEndEditing: delegate method. This is called anytime the focus leaves a text field.
You could even do it in the textFieldShouldEndEditing: delegate method. If it's not valid you can return NO and the user won't be able to leave the invalid text field.


text:
Q: javascript Counter always 1 behind I am building a simple slider and can't for the life of me work out why my dots are always 1 step behind, if I do anything to change it with a simple + 1 it throws out my slider loop, see the pen it will make more sense.
https://codepen.io/flashvenom/pen/RwborBy
This works but always 1 step behind
counter++;
dots.querySelector("ul li:nth-child(" + counter + ")").classList.add("dwAccT--active");

This one the dots work but then throws out the slider loop
counter++;
counterPlus = 1 + counter;
dots.querySelector("ul li:nth-child(" + counterPlus + ")").classList.add("dwAccT--active");

A: I simplify your function dwAutoPlay to
function dwAutoPlay(counter){
  if(playing !== true) return;

  setTimeout(function(){
    counter++;
    dwAccUl.style.transform = "translateX(-" + counter%totalTiles + "00%)";
    dots.querySelector(".dwAccT--active").classList.remove("dwAccT--active");
    dots.querySelector("ul li:nth-child(" + (1+counter%totalTiles) + ")")
      .classList.add("dwAccT--active");
    dwAutoPlay(counter);
  }, 3000);
}

const accordion = document.getElementById("dwAcc");
const dwAccUl = document.getElementById("dwAccUl");
let playing = true;
let tiles = accordion.getElementsByClassName("dwAccLi");
let totalTiles = tiles.length;
console.log(totalTiles)
const dots = document.getElementById("dots");
let firstActive = accordion.firstElementChild;

//add initial active class to first slide
firstActive.classList.add("dwAccT--active");

//click dot to slide
function createHandler(n) {
  return function() {
    playing = false;
    //If active class exists
    if (document.querySelector(".dwAccT--active") !== null) {
      //remove active class from all instances
      document.querySelector(".dwAccT--active").classList.remove("dwAccT--active");
    }
    //add active class to current dot
    this.classList.add("dwAccT--active");
    //animate to slide position
    dwAccUl.style.transform = "translateX(-" + n + "00%)";
  };
}

//create dots
const createDotsUl = document.createElement("ul");
//Append ul to #dots
dots.appendChild(createDotsUl);
//For each tile add click event listener and create a dot
for (let i = 0; i < tiles.length; i++) {
  //create a dot
  let createDotsLi = document.createElement("li");
  //reference created dot
  let createdDot = createDotsUl.getElementsByTagName("li");
  //append the created dot to the parent ul
  createDotsUl.appendChild(createDotsLi);
  //remove existing active class from all dots
  document.querySelector(".dwAccT--active").classList.remove("dwAccT--active");
  //add inital active class to first dot
  document.querySelector("#dwAcc ul li:nth-child(1)").classList.add("dwAccT--active");
  //add event handler
  createdDot[i].addEventListener("click", createHandler(i));
}

//autoplay function
//start a counter
function dwAutoPlay(counter){
      if(playing !== true) return;

      setTimeout(function(){
        counter++;
        dwAccUl.style.transform = "translateX(-" + counter%totalTiles + "00%)";
        dots.querySelector(".dwAccT--active").classList.remove("dwAccT--active");
        dots.querySelector("ul li:nth-child(" + (1+counter%totalTiles) + ")")
          .classList.add("dwAccT--active");
        dwAutoPlay(counter);
      }, 3000);
}

//initialize autoplay start
dwAutoPlay(0+0);
/*reset*/
html {box-sizing: border-box; overflow-y:scroll;}
*, *:before, *:after {box-sizing: inherit; }

body{background: #000; color: #fff; font-family: sans-serif; font-weight:300;font-size:100%; margin:0;opacity:1;padding:0;transition:1s opacity;overflow-x: hidden; -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%; }
a:focus,button:focus,input:focus,textarea:focus,:focus {outline: none;}
h1,h2,h3,h4,h5,h6, ul, li, p{margin: 0; padding: 0; -webkit-margin-before: 0;-webkit-margin-after: 0;-webkit-margin-start: 0px;-webkit-margin-end: 0px; text-align: left;}

#app {
  width: 100%;
  height: 100%;
}

/*reset end */
#dwAcc{
display: block;
float: left;
overflow: hidden;
position: relative;
max-height: 100vh;
width: 100%;
}
#dwAccUl{
  display: flex;
  flex-wrap: nowrap;
  margin: 0 auto;
  padding: 0;
  transform: translateX(0);
  transition: all ease-in-out 0.5s;
  width: auto;
}

.dwAccLi{
  flex: 0 0 auto;
  margin: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
}

.dwAccLi img {
  height: auto;
  width: 100%;
}

#dots ul{display: block; position: absolute; left: 2em; bottom: 1em; z-index: 1000; width: 320px; margin: 0; padding: 1em 0; list-style-type: none;}
#dots li{background: transparent; border: 2px solid #000; border-radius: 100%; display: block; float: left; height: 10px; margin: 0 10px 0 0; padding: 0; transition: all ease 0.3s; width: 10px;}
#dots li.dwAccT--active{background: #000;}

A: Try this
function dwAutoPlay(counter) {
  // When counter == 0, the first photo will show 2 cycle, so make it 1500,
  // which is half of 3000
  const delay = counter === 0 ? 1500 : 3000
  if (counter < totalTiles && playing === true) {
    counter++
    // Because the first photo don't need to change, while counter == 1, so here
    // must -1 so it can be same position with dot.
    dwAccUl.style.transform = `translateX(-${counter - 1}00%)`
    dots.querySelector(".dwAccT--active").classList.remove("dwAccT--active")
    dots
      .querySelector(`ul li:nth-child(${counter})`)
      .classList.add("dwAccT--active")
  } else if (counter == totalTiles && playing === true) {
    counter = 0
    dwAccUl.style.transform = "translateX(0%)"
    // Add these 2 lines code to make active dot be correct postion while
    // photo from last one to first one
    dots.querySelector(".dwAccT--active").classList.remove("dwAccT--active")
    dots.querySelector(`ul li:nth-child(${1})`).classList.add("dwAccT--active")
  }
  setTimeout(function() {
    dwAutoPlay(counter)
  }, delay)
}

A: Simplified and fixed using modulo arithmetic
function dwAutoPlay(counter){
  if (playing) {
      counter = (counter + 1) % totalTiles;
        setTimeout(function(){
          dwAccUl.style.transform = "translateX(-" + counter + "00%)";
          dots.querySelector(".dwAccT--active").classList.remove("dwAccT--active");
          dots.querySelector("ul li:nth-child(" + (counter + 1) + ")").classList.add("dwAccT--active");
          dwAutoPlay(counter);
        }, 3000);
  }
}
dwAutoPlay(0);


text:
Q: How to recognize latest sequence ID from the GD project dataset? How can I dynamically refer the latest sequence ID from the GD project dataset when calling sequence function in ETL to connect that project?
If intending to dynamically determine from which number to restart incrementing the sequence, how should I do?

A: I'm afraid there is not any dynamic function to determine the latest sequence ID in a meaning of your question, but it is always possible to save this information somewhere on persistent storage on the ETL level and read it when the next ETL triggers. If the sequence is also being uploaded to the GD project as a fact, you can use the "SELECT MAX(FactName)" function.
Sincerely
Filip


text:
Q: Default value of timeout for a YUI Ajax webservice call Does someone has idea on what is the default timeout for an AJAX call through YUI, e.g. if we do not mention any value as timeout then what would be the value.
Appreciate the help in advance.
Regards,
Vaibhav

A: looking at YUI connection manager code, it seems that if there is no timeout property set in the callback, it will not abort the ajax call (so is left to the browser/network settings)
if(callback && callback.timeout){
        this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
}