text:
Q: Razor can not understand ViewBag inside Html.TextBoxFor I am using mvc 5, Using this code I don´t get ViewBag.Arrival in my controller i get it every time with Null what is the problem
  @Html.TextBoxFor(Model => Model.Parameters.Checkin, "{0:dd-MM-yyyy}", new {     @class = "calendarr font", @id = "Arrival",  @name = "Arrival", @value = (String)ViewBag.Arrival, @readonly = "readonly", @onchange = "changedDate();" })

this is my Home controller :
   if (ViewBag.Arrival == true)
    {
        mySessionObject.Parameters.Checkin = ViewBag.Arrival;
        mySessionObject.Parameters.Checkout = ViewBag.Departure;
    }

A: if you are trying to send back data from view to action with viewbag it wont work because it only does one way trip so you should get the value in Model.Parameters.Checkin and change @value to @Value use capital V because razor wont recognize small v @value
 @Html.TextBoxFor(Model => Model.Parameters.Checkin, "{0:dd-MM-yyyy}", new {@class = "calendarr font", @id = "Arrival",  @name = "Arrival", @Value = (String)ViewBag.Arrival, @readonly = "readonly", @onchange = "changedDate();" })

A: You should fill ViewBag inside controller and use them in Views.
If you use ViewBag.Arrival in your Index view you should fill it inside Index action of Home controller.
public ActionResult Index(){
    ViewBag.Arrival = true;
}

Now ViewBag.Arrival value is true if you use it inside Index view.
Notice that ViewBag variables keep their value just for their own views. This means if you fill ViewBag.Arrival in Index it will be null in ContactUs View.


text:
Q: Is there any way to rotate a button without using animation in android 2.1 I am in search of methodology for rotating a button. without using animations..!
I don't want use animations because of this.
if any body has any idea please help me.
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:id="@+id/ll" android:gravity="center_vertical">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />
    <com.mind.RotateButton android:layout_width="100dp"  android:gravity="center_vertical"
        android:layout_height="100dp" android:id="@+id/ll1">
    <Button android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Button" android:id="@+id/but" />
    </com.mind.RotateButton>
</LinearLayout>

code
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn   = (Button) findViewById(R.id.but);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
            }
        });
    }

Thanks in advance.......!

A: extend Button class:
public class RotateButton extends Button{

    public RotateButton(Context context) {
        super(context);
    }

    public RotateButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.rotate(45, getWidth() / 2, getHeight() / 2);
        super.onDraw(canvas);
        canvas.restore();
    }

}

and in your layout:
<com.samples.myapp.ui.RotateButton
        android:layout_height="wrap_content" android:id="@+id/MyBtn"
        android:padding="5dip" android:textColor="@color/darkGreen"
        android:textSize="16dip" android:text="TextView"
        android:layout_width="wrap_content"></com.samples.myapp.ui.RotateButton>

----------------------------------------------------------------------
edit:
Another approach: design a rotatable LinearLayout and put your controls in it. LinearLayout can be rotated completely:
package org.mabna.order.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class RotateLinearLayout extends LinearLayout{

    private Matrix mForward = new Matrix();
    private Matrix mReverse = new Matrix();
    private float[] mTemp = new float[2];

    public RotateLinearLayout(Context context) {
        super(context);
    }

    public RotateLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {

        canvas.rotate(180, getWidth() / 2, getHeight() / 2);

        mForward = canvas.getMatrix();
        mForward.invert(mReverse);
        canvas.save();
        canvas.setMatrix(mForward); // This is the matrix we need to use for
                                    // proper positioning of touch events
        super.dispatchDraw(canvas);
        canvas.restore();
        invalidate();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        event.setLocation(getWidth() - event.getX(), getHeight() - event.getY());
        return super.dispatchTouchEvent(event);
    }
}

A: Using ideas from breceivemail answer I made rotate layout that actually works. It's designed to hold single view, it will dispatch touch events correctly but no padding or margins are supported in this realization. Also it's only supports angles like 90, 180, 270 etc. Layout size will just match the size of it's child after rotation.
public class RotateLayout extends ViewGroup {

    public static class LayoutParams extends ViewGroup.LayoutParams {

        public int angle;

        public LayoutParams(Context context, AttributeSet attrs) {
            super(context, attrs);
            final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RotateLayout_Layout);
            angle = a.getInt(R.styleable.RotateLayout_Layout_layout_angle, 0);
        }

        public LayoutParams(ViewGroup.LayoutParams layoutParams) {
            super(layoutParams);
        }

    }

    public RotateLayout(Context context) {
        super(context);
    }

    public RotateLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
    }

    public View getView() {
        return view;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        view = getChildAt(0);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
        if(angle != layoutParams.angle) {
            angle = layoutParams.angle;
            angleChanged = true;
        }

        if(Math.abs(angle % 180) == 90) {
            measureChild(view, heightMeasureSpec, widthMeasureSpec);
            setMeasuredDimension(
                resolveSize(view.getMeasuredHeight(), widthMeasureSpec),
                resolveSize(view.getMeasuredWidth(), heightMeasureSpec));
        }
        else {
            measureChild(view, widthMeasureSpec, heightMeasureSpec);
            setMeasuredDimension(
                resolveSize(view.getMeasuredWidth(), widthMeasureSpec),
                resolveSize(view.getMeasuredHeight(), heightMeasureSpec));
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if(changed || angleChanged) {
            layoutRectF.set(0, 0, r - l, b - t);
            layoutTransitionMatrix.setRotate(angle, layoutRectF.centerX(), layoutRectF.centerY());
            layoutTransitionMatrix.mapRect(layoutRectFRotated, layoutRectF);
            layoutRectFRotated.round(viewRectRotated);
            angleChanged = false;
        }

        view.layout(viewRectRotated.left, viewRectRotated.top, viewRectRotated.right, viewRectRotated.bottom);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        canvas.save();
        canvas.rotate(-angle, getWidth() / 2f, getHeight() / 2f);
        super.dispatchDraw(canvas);
        canvas.restore();
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        invalidate();
        return super.invalidateChildInParent(location, dirty);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        touchPoint[0] = event.getX();
        touchPoint[1] = event.getY();

        layoutTransitionMatrix.mapPoints(childTouchPoint, touchPoint);
        event.setLocation(childTouchPoint[0], childTouchPoint[1]);
        return super.dispatchTouchEvent(event);
    }

    @Override
    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new RotateLayout.LayoutParams(getContext(), attrs);
    }

    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams layoutParams) {
        return layoutParams instanceof RotateLayout.LayoutParams;
    }

    @Override
    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams layoutParams) {
        return new RotateLayout.LayoutParams(layoutParams);
    }

    private View view;
    private int angle;

    private final Matrix layoutTransitionMatrix = new Matrix();

    private final Rect viewRectRotated = new Rect();

    private final RectF layoutRectF = new RectF();
    private final RectF layoutRectFRotated = new RectF();

    private final float[] touchPoint = new float[2];
    private final float[] childTouchPoint = new float[2];

    private boolean angleChanged = true;

}

attrs.xml (add this file to res/values folder)
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="RotateLayout_Layout">
        <attr name="layout_angle" format="integer"  />
    </declare-styleable>

</resources>

Usage example:
<com.you.package.name.RotateLayout
    xmlns:app="http://schemas.android.com/apk/res/com.you.package.name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_angle="-90"
        android:text="Rotated Button"/>
</com.you.package.name.RotateLayout>

redpajama_set_name: RedPajamaStackExchange


text: Q: Does Colab run on randomly selected Google Cloud Platform regions? I was wondering if colab uses servers that are in random Google Cloud Platform regions. If so, would it be possible to select a preferred region? This would decrease data transfer costs from GCS to Colab.


text:
Q: How to reduce WhatsApp Desktop App RAM Usage? The WhatsApp Desktop App is always open on my Windows 11 machine since it is a major work tool.
The problem is that it is sacrificing 1GB of RAM.
It consumes around 600MB to 1GB depending on its usage. Just get focus on the window, change between conversations and you can see it growing up memory on Task Manager.
Here there is a similar question, unanswered for mac.
Is there any way to reduce the RAM consumed by WhatsApp App?
Here are some images of the app running in Task Manager:
At Starting Up:

Getting focus, changing between conversations, rolling up and down the scroll bar, etc:

A: I found two workarounds for this problem.
1-Open the WhatsApp Web in the Edge browser and create an app.
-On the Edge go to ...(three dots) -> App -> Install this site as an app.
Edge browser makes better memory usage, and when the app is minimized it puts it in economy mode.
2-Configure Nvidia GPU to run the app.
On Nvidia Control Panel (search for it on the Windows start menu)
go to Panel navigation tree pane -> under 3D Settings -> select Manage 3D settings -> Program Settings tab. and configure the WhatsApp to use the GPU.
By switching to a GPU render engine, WhatsApp will be able to utilize some of the memory on your graphics card and free up space in your system's RAM.
Unfortunately, changing the GPU render engine will only work if you have a graphics card.
Run a program on Nvidia GPU


text:
Q: Navigating between divs using javascript In my asp.net mvc application I have a modal popup.In modal popup i have three divs displayed like tabs.each div has buttons "Next","Back".on click of these buttons i want to navigate between these divs
sample code

one

Two

Three

<input id="btnNext Type="button/>
<input id="btnBack Type="button/>

Please suggest
Thanks

A: using  foloowing line of code on "Onclick" event of button
$('#Div1').tabs("select", tabid);
Here tabid is the id of the tab on which you want to navigate
The code change done is
as below


text:
Q: continuous duplicate of same error report on my site as pasted below my site keep giving me same report as paste below, please how do solved this issue?
a:5:{i:0;s:52:"Front controller reached 100 router match iterations";i:1;s:409:"#0 /home/thewa2m2/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(179): Mage::throwException('Front controlle...')

A: This often happens for two reasons,

*

*You removed/added/changed a module without disabling the configuration cache first

*Configuration cache corruption

To solve 1.
Clear your configuration cache and if the issue is resolved, nothing further is required.

To Solve 2.
This is a core-code bug in some versions of Magento. You can test if it is caused by this bug by editing Mage_Core_Model_Config to reflect the following.
public function init($options=array())
{
    $this->setCacheChecksum(null);
    $this->_cacheLoadedSections = array();
    $this->setOptions($options);
    $this->loadBase();

    $cacheLoad = $this->loadModulesCache();
    if ($cacheLoad) {
        return $this;
    }
+   $this->_useCache = false;

    $this->loadModules();
    $this->loadDb();
    $this->saveCache();
    return $this;
}

A: As seen from the message, the problem occurs because your routers are making circular references for dispatching requests. One of them matches request, but doesn't dispatch and pushes it to redispatch again. Or no router matches request at all.
I cant directly tell the cause of this error, but can work with you to get the cause of it.
In order to debug it first open app/code/core/Mage/Core/Controller/Varien/Front.php and find these lines or somewhat similar
    while (!$request->isDispatched() && $i++<100) {
      foreach ($this->_routers as $router) {

      }
    }

and replace it with (take the backup of the file)
Mage::log('----Matching routers------------------------------');
Mage::log('Total ' . count($this->_routers) . ': ' . implode(', ', array_keys($this->_routers)));
while (!$request->isDispatched() && $i++<100) {
    Mage::log('- Iteration ' . $i);
    $requestData = array(
        'path_info' => $request->getPathInfo(),
        'module' => $request->getModuleName(),
        'action' => $request->getActionName(),
        'controller' => $request->getControllerName(),
        'controller_module' => $request->getControllerModule(),
        'route' => $request->getRouteName()
    );

    $st = '';
    foreach ($requestData as $key => $val) {
        $st .= "[{$key}={$val}]";
    }
    Mage::log('Request: ' . $st);
    foreach ($this->_routers as $name => $router) {
        if ($router->match($this->getRequest())) {
            Mage::log('Matched by "' . $name . '" router, class ' . get_class($router));
            break;
        }
    }
}

after that wait for the site to produce the error. then open your system.log file and see whats going wrong ? what router break ?
Ideally this issue arises once magento is not able to load a core module.
If you have trouble to find out the solution. Let me know I will try to help you.


text:
Q: How does the Negotiate HTTP authentication mechanism establish a session? As described in RFC 4559, the Negotiate mechanism may take several requests to complete a GSSAPI context. I cannot understand from the RFC what mechanism is used to associate those requests with one another, however. To take the example described in section 5 of the the RFC:
1:
  C: GET dir/index.html

2:
  S: HTTP/1.1 401 Unauthorized
  S: WWW-Authenticate: Negotiate

3:
  C: GET dir/index.html
  C: Authorization: Negotiate a87421000492aa874209af8bc028

4:
  S: HTTP/1.1 401 Unauthorized
  S: WWW-Authenticate: Negotiate 749efa7b23409c20b92356

5:
  C: GET dir/index.html
  C: Authorization: Negotiate 89a8742aa8729a8b028

This is clear to me up until step 5. Assuming there are potentially many clients doing authentication at the same time, how does server know that the Authorization header in step 5 is the response to the data from step 4? I can't see any mention of session cookies or anything, and while I'm not an expert on GSSAPI, I don't think there's anything inherent in the GSSAPI data that can be used to associate it with an authentication session.
So what's the deal? :)

A: State is maintained using the TCP connection.  RFC-4559 doesn't spell this out directly, likely because it would make the author feel dirty.  But they elude as much in section 6 when discussing "Session-Based-Authentication" when proxies are involved.  This requirement is also "called-out" in the last paragraph of RFC-7230 section 2.3 when discussing how HTTP is supposed to be a stateless protocol:

Some non-standard HTTP extensions (e.g., [RFC4559]) have been known to violate this requirement, resulting in security and interoperability problems

There is even more ambiguity with another requirement in the last paragraph in Section 6:

When using the SPNEGO HTTP authentication facility with client-supplied data such as PUT and POST, the authentication should be complete between the client and server before sending the user data.  The return status from the gss_init_security_context will indicate that the security context is complete.  At this point, the data can be sent to the server.

So the server should remember the authentication state after the context is successfully completed (and sent the client the 200 with the last token), to let-in one last request containing the actual payload?
Your confusion is justified.

A: From RFC 7235

5.1.2. Considerations for New Authentication Schemes
There are certain aspects of the HTTP Authentication Framework that
put constraints on how new authentication schemes can work:
o  HTTP authentication is presumed to be stateless: all of the
information necessary to authenticate a request MUST be provided
in the request, rather than be dependent on the server remembering
prior requests.  Authentication based on, or bound to, the
underlying connection is outside the scope of this specification
and inherently flawed unless steps are taken to ensure that the
connection cannot be used by any party other than the
authenticated user (see Section 2.3 of [RFC7230]).

Which is how I remembered it, but I wanted to make sure. So each request that the user sends includes all the necessary credentials. The server itself knows nothing about what the authentication is. It just asks whether the credentials are valid, and if the answer is yes, go on with the request.


text:
Q: Enum initialized with a non-existent rawValue does not fail and return nil I have the following code in a playground (Xcode 9.0.1):
import MapKit

enum Test: UInt {
    case first
    case second
    case third
}

let test = Test(rawValue: 4) as Any
print(test)           // nil

let type = MKMapType(rawValue: 999)
print(type == nil)    // false
print(type!.rawValue) // 999

MKMapType is defined as
enum MKMapType : UInt

As the maximum value of a MKMapType is 5, I expect the initializer of the enum to fail and return nil. Instead it returns 999. Am I missing some ObjC/Swift bridging here or could this be a bug?

A: I filed a bug with Apple and this is the reply I received:

"Engineering has determined that this issue behaves as intended based on the following information:
Because C enums may have values added in future releases, or even have "private case" values used by the framework that are not included in the headers, there's no way to check whether a value provided in Swift is actually valid or invalid. Therefore, init(rawValue:) is obliged to produce a value just as a C cast would. There are discussions in the Swift Open Source project on how to improve this situation in later versions of Swift, but the initializer for MKMapType still won't return nil."

Thanks to Apple Engineering for this explanation.


text:
Q: owl carousel slide n by n Using owl carousel and trying to slide items five by five, now i have 5 items, i want when i push next or prev button it move to next five item, currently it move to next item, is it possible?
$('.owl-carousel').owlCarousel({
    loop:true,
    items:5,
    margin:10,
    nav:true
})

Demo
i googled and checked plugin website but couldn't find anything.

A: Use the slideBy options in the owlCarousel config:

$('.owl-carousel').owlCarousel({
    loop:true,
    items: 5,
    margin:10,
    slideBy: 5, // slide 5 items
    nav:true
})
.item {
  background: red;
}
<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/css/docs.theme.min.css" rel="stylesheet"/>

<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"/>
<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.theme.default.min.css" rel="stylesheet"/>

1

2

3

4

5

6

7

8

9

10

11

12

A: You should include slideBy: 5 or slideBy: 'page' option, as they describe it on their documentation.
https://jsfiddle.net/w3ka3vqw/151/


text:
Q: Exibir data atual em layout manipulado por ViewPager Quando clico num botão da Main Activity cria-se um ViewPager que me possibilita transitar entre 7 layouts que possuo. O pager está setado para apresentar primeiramente o layout chamado "domingo.xml" e tudo funciona normalmente. Eu quero apenas que nesse layout seja mostrada uma data, para isso utilizo esse código:
    Locale local = new Locale("pt", "BR");
    DateFormat sdf = new SimpleDateFormat("EEEE - dd/MM", local);
    Date d = Calendar.getInstance().getTime();
    String mostrarData = sdf.format(d).toUpperCase(local);
    final TextView textoData = (TextView) findViewById(R.id.textView1);
    textoData.setText(mostrarData);

Criei um layout novo só para testar e o código da data funciona e exibe a data normalmente, mas no layout domingo.xml (que é manipulado pelo ViewPager) não consigo de jeito nenhum.
Esse é o código do botão que chama o ViewPager:
public void btTela1(View v) {
startActivity(new Intent(getBaseContext(), Pager.class));
}

E este é o código do ViewPager:
public class Pager extends Activity {

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

    AdapterPages adapter = new AdapterPages();
    ViewPager myPager = (ViewPager) findViewById(R.id.pager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
}}

Há ainda o código do PagerAdapter que serve para configurar o ViewPager. Onde devo escrever o código da data ? Já tentei em vários lugares, mas sempre dá erro. Não sei também se há algum erro conceitual que eu não entendo. Sou novo em programação e esta é a primeira vez que posto em um fórum. Se for necessário mais informações me falem que eu adiciono. Obrigado.
Código do PagerAdapter:
public class AdapterPages extends PagerAdapter {

@Override
public int getCount() {
    return 7;
}

@Override
public Object instantiateItem(View collection, int position) {

    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int resId = 0;
    switch (position) {
    case 0:
        resId = R.layout.domingo;
        break;
    case 1:
        resId = R.layout.segunda;
        break;
    case 2:
        resId = R.layout.terca;
        break;
    case 3:
        resId = R.layout.quarta;
        break;
    case 4:
        resId = R.layout.quinta;
        break;
    case 5:
        resId = R.layout.sexta;
        break;
    case 6:
        resId = R.layout.sabado;
        break;
    }

    View view = inflater.inflate(resId, null);

    ((ViewPager) collection).addView(view, 0);

    return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {

    return arg0 == ((View) arg1);
}

@Override
public Parcelable saveState() {
    return null;
}}

Código do domingo.xml:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/data_domingo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#BEBEBE"
        android:gravity="center"
        android:textStyle="bold" />
    ...

A partir do que @Wakim me ensinou eu modifiquei uma pequena parte do código do PagerAdapter e ficou assim:
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
Locale local = new Locale("pt", "BR");
DateFormat sdf = new SimpleDateFormat("EEEE - dd/MM", local);
Date d = Calendar.getInstance().getTime();
String mostrarData = sdf.format(d).toUpperCase(local);
TextView textoData = (TextView) collection
        .findViewById(R.id.data_domingo);
textoData.setText(mostrarData);
return view;

Agora a data apareceu, porém, quando deslizo para o terceiro layout trava tudo. O que está acontecendo ?

A: O ViewPager trabalha de forma parecida que o ListView, exibindo uma pequena parte do modelo associado.
O Modelo é associado através de um Adapter, onde o mesmo é responsável por retornar a presentação visual do modelo, para uma dada posição.
No caso o seu modelo é uma lista de datas, que pode ser derivado a partir de apenas uma data.
Vou assumir que o domingo.xml será o padrão para todas as datas, onde o que varia é o conteúdo do TextView cujo ID é data_domingo que ele exibe. Caso haja mais alterações no layout, é só falar que eu ajudo a montar.
Sua Activity Pager continua o mesmo.
O que muda é o seu AdapterPages que fica:
public class AdapterPages extends PagerAdapter {

    // Data base do ViewPager (posição 0), onde cada posição derivará dessa
    Calendar mBaseDate = Calendar.getInstance();
    // DateFormat usado para formatar a data
    DateFormat mDateFormat = new SimpleDateFormat("EEEE - dd/MM", Locale.getDefault());

    // É legal "cachear" o LayoutInflater, para não ficar requisitando um toda hora.
    LayoutInflater mLayoutInflater;

    public AdapterPages() {
        // Configurar a data base para corresponder ao primeiro dia da semana, domingo.
        mBaseDate.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
        mBaseDate.clear(Calendar.MINUTE);
        mBaseDate.clear(Calendar.SECOND);
        mBaseDate.clear(Calendar.MILLISECOND);

        // get start of this week in milliseconds
        mBaseDate.set(Calendar.DAY_OF_WEEK, mBaseDate.getFirstDayOfWeek());
    }

    @Override
    public int getCount() {
        // Ok, sao 7 dias
        return 7;
    }

    @Override
    public Object instantiateItem(View collection, int position) {

        if(mInflater == null) {
            mInflater = LayoutInflater.from(collection.getContext());
        }

        // Infla o layout padrão do ViewPager. É retornado uma
        // referência para a raiz (LinearLayout).
        // A partir dele, você consegue acessar todos os filhos.
        View view = mInflater.inflate(R.layout.domingo, null);

        TextView tv = view.findViewById(R.id.data_domingo);

        // Calculo qual o dia baseado na posicao e no dia base
        Calendar currentDate = (Calendar) mBaseDate.clone();
        currentDate.add(Calendar.DAY_OF_YEAR, posicao);

        // Fornece a data formatada relativa à posição do modelo
        tv.setText(mDateFormat.format(currentDate.getDate()).toUpperCase());

        // Voce pode fazer mais customizacoes aqui baseada na "view" e seus
        // elementos, e o seu modelo, a data relativa a posicao que vai ser exibida.

        ((ViewPager) collection).addView(view);

        return view;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == ((View) arg1);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }
}

Acho legal citar também que o ViewPager constrói as Views sobre demanda, isso é, ele por padrão mantém na memória 3 Views (a visível, a anterior e a próxima), conforme você vai navegando ele destrói e constrói as Views. Esse comportamento pode ser alterado pelo atributo OffscreenPageLimit (sendo 1 por padrão), mas a idéia dele é para dar fluidez ao movimento de Slide.
Referências:

*

*https://stackoverflow.com/questions/2937086/how-to-get-the-first-day-of-the-current-week-and-month

*http://developer.android.com/reference/android/support/v4/view/ViewPager.html


text:
Q: xstream flatten an object I am trying to flatten the xml output of xstream using a converter/marshaling with no luck. For example,
public class A{
    public B b;
    public int F;
    public String G;
}

public class B{
    public String C;
    public String D;
    public int E;
}

is output as

     <C></C>
     <D></D>
     <E></E>

  <F></F>
  <G></G>

but I need

  <C></C>
  <D></D>
  <E></E>
  <F></F>
  <G></G>

is this possible? How to get rid of B? (C, D, E are uniquely named). Thanks.
My attempt thus far has been
...
public void marshal(Object value, HierarchicalStreamWriter writer,
    MarshallingContext context)
{
    B b = (B) value;
    writer.startNode("C");
    writer.setValue(b.getC());
    writer.endNode();

    writer.startNode("D");
    writer.setValue(b.getD());
    writer.endNode();

    writer.startNode("E");
    writer.setValue(b.getE());
    writer.endNode();
}

A: I found a temporary solution, though it is not the best.
If I set my canConvert function to check the surrounding object A instead of B, I can manipulate the entire inner object.
public boolean canConvert(Class c)
{
    return A.class == c;
}

Since I have to define all of class A, this is a lot more work (especially in a real XML object, instead of my contrived example).
Does anyone know of a way to get the same result using a Converter on inner class B only?
public boolean canConvert(Class c)
{
    return B.class == c;
}

A: Depending on how tied you are to XStream, you can do this quite easily in EclipseLink MOXy using the @XmlPath annotation:
public class A{
    @XmlPath(".") public B b;
    public int F;
    public String G;
}

public class B{
    public String C;
    public String D;
    public int E;
}

For Information on MOXy's XPath based mapping see:

*

*http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html


text:
Q: NEAR NEAR CLI has a minor update available 2.1.1 → 2.2.0 │ │ Run yarn add near-cli to avoid unexpected behavior (does not resolve) Running the exercises from: /starter--near-sdk-as
yields ...
NEAR CLI has a minor update available 2.1.1 → 2.2.0   │
│   Run yarn add near-cli to avoid unexpected behavior
Running the yarn command as instructed - does NOT resolve or remove the "recommendation/message".
Pls advise
This is run under WSL2 n Ubuntu 20.04.3 under Windows X (with its Bash Terminal, NOT powershell, etc.)

A: NEAR CLI is most likely installed globally.
If you post a screenshot of the message here, my guess is there is a global flag included.
The command should probably be something like npm install -g near-cli
If using yarn then I think it's something like yarn global add near-cli

If this is not the case and you actually are using near-cli as a local project dependency then you can do the following:

*

*delete the node_modules folder

*delete package-lock.json file (or yarn.lock file)

*update package.json with the new near-cli version

*run npm install (or yarn) to bring it all back


text:
Q: LVM Check Disk for Bad Sectors with RAID Mirroring to Fix Them? I'm working on creating a very reliable, high-volume storage server on Ubuntu.
Suppose you have a large 4 TB RAID1 set of 2 disks on LVM... At this size, I find it's more common to get a bad sector.
How can I manually scan the disks while they are live/mounted, and reallocate/fix any bad sectors? (Say, once every 3 months, to clean up any bad sectors.)
You might ask why the scan is necessary. My Reasoning: Because I want the system very reliable for infrequently-used data. Over time, disks degrade. So, it seems very possible that there could be a bad sector on disk #1, and then a failure on disk #2. That would result in corruption from bad sectors on disk #1, since there's no place to restore the data from. To help prevent this, I'd want scanning to clean up any bad sectors on a regular basis.


text:
Q: How to control the text inside DIV tag by not allowing the text to be increased? I have this CSS code :
    #d_image {
    float: left;
    width: 320px;
    margin-top: 20px;
    margin-left: 25px;
}
#d_coll {
    width: 320px;
    float: left;
}

#n_div {
    width: 240px;
    text-align: right;
    padding-top: 10px;
    float: left;
    padding-right: 10px;
    padding-left: 0px;
}
#n_text {
    text-align: right;
    float: left;
    clear: both;
}
#im {
    height: 50px;
    width: 50px;
    float: right;
    padding-right: 15px;
}
#n_col {
    clear: both;
    width: 310px;
    float: right;
    border-bottom-width: 2px;
    border-bottom-style: solid;
    border-bottom-color: #CCC;
    padding-bottom: 10px;
}
#n_tittle {
    text-decoration: none;
    text-align: right;
    padding-bottom: 10px;
    padding-right: 15px;
}
#n_tittle a {
    text-decoration: none;
    text-align: right;
    color: #1C60B3;
}
#n_tittle a:hover {
    text-decoration: underline;
    text-align: right;
    color: #FF0000;
}

I have this HTML code :

sample text

Here will be photo

sample text

small photo will be here

long text

I have proplem in n_div, if I put in it a very long text it will be under im div and I want the text inside it to go to new line when it reach the end because the image should be to the right of the text in im div .
How I can do that?
Thanks in Advance.

A: You want to use word-wrap:
word-wrap: break-word;


text:
Q: Error when calling CreateEnvelope: Invalid Username For Recipient I am using the updated DocuSign API with my .NET application and for the Authentication, I'm using the Authentication Code Grant workflow using 'signature%20extended' as the Code. I can successfully authenticate and get back an access token for the user I'm authenticating with.
I then get the Account details without any issue
ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");
var docuSignUserInfo = apiClient.GetUserInfo(accessToken).Accounts.FirstOrDefault();

I then proceed with creating my Signer and Document Model
Document document = new Document
            { DocumentBase64 = Convert.ToBase64String(ReadContent(docName)),
              Name = "Lorem Ipsum", FileExtension = "pdf", DocumentId = "1"
            };
Document[] documents = new Document[] { document };

// Create the signer recipient object
            Signer signer = new Signer
            { Email = "test@example.com", FirstName = "Jane", LastName="Doe" ClientUserId = "1000",
              RecipientId = "1", RoutingOrder = "1"
            };
Signer[] signers = new Signer[] { signer };
Recipients recipients = new Recipients { Signers = new List<Signer>(signers) };

EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition
            { EmailSubject = "Please sign the document",
              Documents = new List<Document>( documents ),
              Recipients = recipients,
              Status = "sent"
            };

ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");
apiClient.Configuration.AddDefaultHeader("Authorization", "Bearer " + accessToken);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient.Configuration);

//This is the API call that throws the error below
EnvelopeSummary results = envelopesApi.CreateEnvelope(accountId, envelopeDefinition);

Error calling CreateEnvelope: {
  "errorCode": "INVALID_USERNAME_FOR_RECIPIENT",
  "message": "The user name for the recipient is invalid. Envelope definition is missing a UserName for recipientId: 1"
}

From my understanding, I shouldn't need to specify any Username/Passwords as I'm using the Access Token for Authentication. Also, I don't understand why a recipient would require a UserName?

A: I think you need to provide the Name property for the Signer model. Please try that.
I agree that the FirstName and LastName sound like they are all that is needed, but those attributes may not be fully implemented yet (or a bug).
Please advise if this solved your problem. Thank you.
Added
The FirstName and LastName attributes are optional. DocuSign internal bug report DEVDOCS-1079 has been filed to have the documentation for those fields improved.


text:
Q: Is there a way to dump the whole postgres db using pg_dumpall from remote host by specifying certificates? I have a kubernetes cluster and I have configured a statefulset with two replicas (lets say postgres-0 and postgres-1), one will be active and another will be standby for a perticular time. Now I want to run pg_dumpall from postgres-1 to connect to postgres-0 by specifying certificates (which I already created).
I am able to dump a particular database using :
pg_dump "port=5432 host=10.20.30.40 user=postgres dbname=test sslcert=pg.cert.pem sslkey=pg.key.pem sslrootcert=ca.crt sslmode=verify-ca" -f test.sql
I need to do the same with pg_dumpall. Is there any to do that?
Ref: https://www.postgresql.org/docs/9.2/app-pg-dumpall.html

A: Sure, but you have to use the connect string as an argument to the -d option:
pg_dumpall -d 'host=... port=... ...' -f test.sql


text:
Q: unable to add roles in asp.net identity I was using the following code to add roles of the user.
    Roles.AddUserToRole(model.Email, "COMPANYVIP");

and then i got this error:
    The Role Manager feature has not been enabled

after some research i found out that we have to add the following connection string in web.config
    <configuration>
      <system.web>
        <roleManager enabled="true" />
      </system.web>
    </configuration>

adding this eliminated my first error but now i get this error:
    A network-related or instance-specific error occurred while establishing a connection to SQL Server

what should i do now?

A: Remove your change in web.config and in Startup.Auth add the following reference to ConfigureAuth:
public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    // Add this reference to RoleManager (without changing any other items)
    // Make sure it is added below ApplicationDbContext.Create
    app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
}

Then in your Controller, make sure it includes this in the constructor:
public class YourController : Controller
{
    // Add this
    private ApplicationRoleManager _roleManager;

    // Add roleManager
    public YourController(ApplicationRoleManager roleManager)
    {
        // Add this
        RoleManager = roleManager;
    }

    public ApplicationRoleManager RoleManager {
        get {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set {
            _roleManager = value;
        }
    }
}

and also include this in the Controller's Dispose (if you have it):
protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        // include this
        if (_roleManager != null)
        {
            _roleManager.Dispose();
            _roleManager = null;
        }
    }

    base.Dispose(disposing);
}

You may also need to add this code to IdentityConfig (in the App_Start folder if you're using the template):
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
    : base(roleStore)
    { }

    public static ApplicationRoleManager Create(
        IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationRoleManager(
            new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
        return manager;
    }
}

You should now be able to use the RoleManager in the Controller.


text:
Q: Initialisation of Delphi Record containing a dynamic array with 'Implicit' class operator I'm trying to figure out whether it is possible to initialise a record containing a dynamic array using the "implicit" class operator in Delphi (Berlin 10.1 upd 1)
The attached program produces the following output:
ci iA r1 r2 r3
1  1  1  1  49694764491115752
2  2  2  2  11570520
3  3  3  3  0
4  4  4  4  0
5  5  5  5  0

*

*TRec is the record type containing a dynamic array that I want to initialise.

*ci is a constant array of integer.

*ia is a dynamic array of integer.

*r1,r2,r3 are records of type TRec which are initialised in different ways.

As you can see from the output, the first two assignments (r1,r2), using constants work as expected. The third assignment r3 := iArray is accepted by the compiler, but the result is broken. The debugger shows that the value of v in TRec.Implicit is already wrong.
What is going wrong here? Is this possible at all?
program Project5;

{$APPTYPE CONSOLE}

{$R *.res}

type
  TRec = record
    iArray: array of UInt64;
    class operator Implicit(const v: array of UInt64): TRec;
  end;

{ TRec }

class operator TRec.Implicit(const v: array of UInt64): TRec;
var
  i: integer;
begin
  setlength(Result.iArray, Length(v));
  for i := 0 to High(v) do
    Result.iArray[i] := v[i];
end;

const
  ciArray: array [0 .. 4] of UInt64 = (1, 2, 3, 4, 5);

var
  i         : integer;
  iArray    : array of UInt64;
  r1, r2, r3: TRec;

begin
  iArray := [1, 2, 3, 4, 5];

  r1 := [1, 2, 3, 4, 5];
  r2 := ciArray;
  r3 := iArray;

  Writeln('ci iA r1 r1 r3');
  for I := 0 to High(ciArray) do
    Writeln(ciArray[i], '  ', iArray[i], '  ', r1.iArray[i], '  ', r2.iArray[i], '  ', r3.iArray[i]);

  readln;

end.

A: Looks like you found a bug with the codegen there (and it also exists in the Win64 Compiler). I looked through the generated asm and it seems the compiler produces a wrong instruction for the operator overload instead. That is why wrong values end up in the array inside the operator overload. Please report this in Quality Portal.
Code generated for the bad result:
Project109.dpr.46: r3 := iArray;
0040B1F2 A1FC044100       mov eax,[$004104fc]
0040B1F7 8945E8           mov [ebp-$18],eax
0040B1FA 837DE800         cmp dword ptr [ebp-$18],$00
0040B1FE 740B             jz $0040b20b
0040B200 8B45E8           mov eax,[ebp-$18]
0040B203 83E804           sub eax,$04
0040B206 8B00             mov eax,[eax]
0040B208 8945E8           mov [ebp-$18],eax
0040B20B 8D4DD8           lea ecx,[ebp-$28]
0040B20E 8B55E8           mov edx,[ebp-$18]
0040B211 4A               dec edx
0040B212 B8FC044100       mov eax,$004104fc // <-- wrong one
0040B217 E87CF5FFFF       call TRec.&op_Implicit

Code for an equal method:
Project109.dpr.47: r3 := TRec.Implicit(iArray);
0040B22F A1FC044100       mov eax,[$004104fc]
0040B234 8945E4           mov [ebp-$1c],eax
0040B237 837DE400         cmp dword ptr [ebp-$1c],$00
0040B23B 740B             jz $0040b248
0040B23D 8B45E4           mov eax,[ebp-$1c]
0040B240 83E804           sub eax,$04
0040B243 8B00             mov eax,[eax]
0040B245 8945E4           mov [ebp-$1c],eax
0040B248 8D4DD4           lea ecx,[ebp-$2c]
0040B24B 8B55E4           mov edx,[ebp-$1c]
0040B24E 4A               dec edx
0040B24F A1FC044100       mov eax,[$004104fc] // <-- correct one
0040B254 E8CFF5FFFF       call TRec.Implicit

However you can avoid this by adding another overload for the Implicit operator with the parameter type TArray<UInt64> and then also declare your local variable as that type so the compiler choses the correct overload (the one it does not generate wrong code for in this case).
But be aware that this will only work when you pass variables of the type TArray<UInt64> and call the wrong one when you have any other dynamic array of UInt64 because of Delphis strict type rules.
Update: This defect was reported in RSP-16084 and fixed in Delphi 10.2 Tokyo.


text:
Q: USB host APIs public or blocked on Samsung Galaxy S3 we know the Samsung Galaxy S3 will have USB host but do you guys have any knowledge if also the USB APIs will be public/accessible or blocked on the Samsung Galaxy S3 to allow developing apps requiring access to these APIs?

A: It will be similar to other SGs.
Same access through the android OS/(Linux if rooted) as normally.

A: I have a galaxy S3 and apps like 'USB Host Viewer' and 'USB Host Controller' are able to see slave devices just fine with an OTG host adaptor connected.
I'm going to assume this means that the APIs are enabled but as I'm yet to find a usb driver that will l


text:
Q: How to pass the assembly name as a command-line argument when debugging I have an NUnit test assembly (a .NET DLL).  When I click Run in Visual Studio I want it to launch NUnit and run the tests in this assembly.  I can do all of that.
Instead of specifying the full assembly name and path in the command line arguments, does Visual Studio support some sort of macro that expands into that for the Command Line Arguments box?  Most other development tools I have used support this, but I cannot find anything in the documentation about this.
I was expecting something like: %assembly_full_path%
The reason I want to do this is so if the assembly name or build location changes, then I don't have to update the command line arguments as well.

A: This doesn't work as far as I can tell.  Macros in the Command Line arguments box do not get expanded.  Not even environment variables.  Bummer.
A workaround is to create a custom tool.  Tools + External Tools, Add.  Title = Run tests, Command = nunit.exe, Arguments = $(TargetPath), Initial Directory = $(TargetDir).  Tweak as needed.  You could assign a keystroke to this new tool command, even F5.

A: Using VS2005, the only item I need to provide in the Command Line Arguments is the name of the dll. I suspect VS sets the default working directory to the project's output directory, as I've never specified the path and yet the tests always load correctly.


text:
Q: visual studio 2019 project Everytime I run debugger I receive this message in the output:
'Project1.exe' (Win32): Loaded 'C:\Users\123em\OneDrive\Project1.exe'. Symbols loaded.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'.
The thread 0x23e1c has exited with code 0 (0x0).
The program '[139372] Project1.exe' has exited with code 0 (0x0).

How can I see the result of my project? I am building a code to rotate an array.

A: I don't know what kind of result you expect, so I listed two methods for your reference.

*

*Set a breakpoint and add the variable you want to monitor in "Add item to watch", so that you can observe the value of the variable, and it needs to be used with F11, I suggest you refer to this document for this.

*Right-click the breakpoint, then select Action, and enter your ideal output format. When executing the program, you can see the output you set in output.


text:
Q: Acceleration of body rolling down inclined plane Acceleration of a body rolling down an inclined plane is given by:
$$\frac{g\sin\theta}{1+\frac{k^2}{r^2}}$$
$g$=acceleration due to gravity
$\theta$=angle of inclined plane
$k$=radius of gyration
$r$=radius of abject
How come acceleration is independent of coefficient of friction of plane when friction itself is causing the torque?
I am not able to understand this although I am able to derive the formula on my own.

A: For this equation to be valid you also have to assume that the body rolls without slipping. In that case the friction is static and defined by the no-slipping constraint, but for this the coefficient of friction has to be bigger than a certain value.

A: The reason that the acceleration is independent of the friction for an object rolling down a plane (assuming no slipping) is because the friction in this system is static friction, and it does no work on a rolling object.  Consider the following diagram:

The point of contact with the surface denoted by the red dot only comes into contact with a single point on the surface while rolling.  Since friction only acts when it is in contact with the surface, and the distance the point travels while in contact with the surface is $\Delta x = 0$, the friction acting on the object can be considered to be static.  The static frictional force is generally written as $F_s = \mu_s N$, where $\mu_s$ is the static frictional coefficient, and $N$ is the normal force.  This isn't strictly true, and should be more generally written as $F_s \leq \mu_s N$.  So, the magnitude of the force can change depending on the incline to a value necessary to supply the needed torque to get the object rolling.
Now, lets consider the work done by a static frictional force.  The work done on a system can be considered to be how much you change the energy of the system.  Since static friction does not change the energy, the conversion of gravitational potential energy to rotational and translational kinetic energy remains the same regardless of the coefficient of friction, $\mu_s$.  Therefore, the acceleration is not affected by it.  So, how do we know it does no work.  Consider the following definition for work.
$W = F\Delta x$
where $F$ in this case is the force of friction, and $\Delta x$ is the distance over which the friction acts.  Now, you might say that since the object is rolling, the frictional force acts over distance the object rolls, but this is not the case as we've established, because the point of contact with the surface for the rolling object does not actually move relative to the surface when it is in contact with the surface.

A: The forces perpendicular to the incline surface need to be balanced $$mg\cos {\theta}=N\quad \quad (1)$$
Forces parallel to the incline generate the parallel acceleration$$mg\sin{\theta}-f_r=m\frac{\mathrm{d}v}{\mathrm{d}t}\quad \quad(2)$$
playing around with equation 2, we get $$\frac{\mathrm{d}v}{\mathrm{d}t}=\frac{mg\sin{\theta}-f_r}{m}\\ \int g\sin{\theta}\mathrm{d}t-\frac{1}{m}\int f_r\mathrm{d}t=v(t)\quad\quad(3)$$
The torque is defined as $$\tau=I\frac{\mathrm{d}\omega}{\mathrm{d}t}\quad \quad (4)$$But also $\tau=\vec{r}\times\vec{F}$. Thus here $\tau=f_rR$ and the Moment of inertia $I$ is $I=mK^2$. Plugging all this into equation 4 and playing around, we get...$$\frac{\mathrm{d}\omega}{\mathrm{d}t}=\frac{f_rR}{mK^2}\\\omega(t)=\frac{R}{K^2}\frac{1}{m}\int f_r\mathrm{d}t\\
\frac{1}{m}\int f_r\mathrm{d}t=\frac{K^2}{R}\omega(t)\quad \quad (5)$$
Plugging eq5. into eq.3, we get
$$\int g\sin{\theta}\mathrm{d}t-\frac{K^2}{R}\omega(t)=v(t)\quad \quad (6)$$
Now is the important part. For, PURE ROLLING, $v(t)=\omega(t)R$. Thus using this fact in eq.6, eq.6 can be rewritten as
$$\int g\sin{\theta}\mathrm{d}t-\frac{K^2}{R^2}v(t)=v(t)\\v(t)=\frac{1}{1+\frac{K^2}{R^2}}\int g\sin{\theta}\mathrm{d}t$$
Hence the acceleration can be written as $$a(t)=\frac{\mathrm{d}v(t)}{\mathrm{d}t}=\frac{g\sin{\theta}}{1+\frac{K^2}{R^2}}$$

A: Imagine a really rough surface with infinite coefficient of friction. The body will still roll just fine. So the amount of friction does not affect the rolling or not. Only the presence of friction does.
In general, try to consider the extreme situations in order to understand how and why an equation works (or not).

A: As long as grip is maintained, coefficient of static friction doesn't affect the magnitude of the friction force.  It's only when the situation asks for a stronger friction force, and grip is lost, that the coefficient of static friction comes into play to determine exactly how strong is too strong.


text:
Q: Combine Content Egg Search form with WordPress and Woocommerce How I can combine Content Egg Search form or make it search from WordPress posts and Woocommerce products as well.
What I want is
Content Egg + WordPress + Woocommerce Search form combined
Content Egg Search Form Here it is Content egg Search Form
<form role="search" method="get" class="search-form" action="<?php echo esc_attr(\ContentEgg\application\ProductSearchWidget::getSearchFormUri()); ?>">

      <input type="text" name="s" placeholder="Product search...">
      <input type="hidden" name="post_type" value="product" />

      <button type="submit">Search</button>

</form>

Woocommerce Search Form
<form role="search" method="get" class="woocommerce-product-search" action="<?php echo esc_url( home_url( '/'  ) ); ?>">
    <?php _e( 'Search for:', 'woocommerce' ); ?>
    <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search Products…', 'placeholder', 'woocommerce' ); ?>" value="<?php echo get_search_query(); ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label', 'woocommerce' ); ?>" />
    <input type="submit" value="<?php echo esc_attr_x( 'Search', 'submit button', 'woocommerce' ); ?>" />
    <input type="hidden" name="post_type" value="product" />
</form>

WordPress Search Form
<form action="/" method="get">
    Search in <?php echo home_url( '/' ); ?>
    <input type="text" name="s" id="search" value="<?php the_search_query(); ?>" />
    <input type="image" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/images/search.png" />
</form>

All of these three search form result displayed on diff. search result pages
Content Egg shows on

ce-product-search.php

and I'm using code like - which works prefect
<?php echo do_shortcode('[content-egg module=Amazon template=grid]'); ?>

WooCommerce and WordPress uses diff. template as well.
Currently I'm using

A: If anyone have same question here is what I did to combine search result and get from diff. query type
First Create a Search-Result.php file that your search form redirect to.
As you can see I store search query to variable and get output according to it.
<?php
                        $s=get_search_query();
                        $args = array(
                        's' =>$s,
                        'posts_per_page' => 10,
                        'post_type' => 'product'
                        );
                        $the_query = new WP_Query( $args );
                        if ( $the_query->have_posts() ) {
                            while ( $the_query->have_posts() ) {
                            $the_query->the_post();
                     ?>
                  <?php wc_get_template_part( 'content', 'product' ); ?>

Output type 2
<?php
                $news=get_search_query();
                $argsn = array(
                's' =>$news,
                'posts_per_page' => 10,
                'post_type' => 'post'
                );

                $the_query = new WP_Query( $argsn );
                    if ( $the_query->have_posts() ) {
                        while ( $the_query->have_posts() ) {
                        $the_query->the_post();

the_title();

}?>

Output type 3
<?php echo do_shortcode('[content-egg module=Amazon template=grid]'); ?>

This is simple solution fit to me currently I faced issue for many days.


text:
Q: Evitar ingreso en caso de que el usuario y contraseña ingresados no sean de un administrador La siguiente sentencia es para preguntar si un usuario con la contraseña está registrada de acuerdo a un cargo, el cual debe ser administrador:
String sql="SELECT * FROM usuario WHERE rutfuncionario='"+usuario+"'and contrasena='"+pass+"'" ;

El formulario recibe dos datos del usuario, su contraseña y su rut.
Tengo 2 tablas:
tabla usuario(rutfuncionar(pk) , nombrefuncionario,cargo,fechamodificacion ,contrasena)
tabla cargo (idcargo (pk) , nombrecargo)

A: Como te habían comentado, es mejor utilizar prepared statement.
En una sentencia simple para validar también el cargo según lo que solicitas, la sentencia sería la siguiente:
String sql="SELECT * FROM usuario u INNER JOIN cargo c ON c.idcargo = u.cargo WHERE rutfuncionario='"+usuario+"' and contrasena='"+pass+"' and c.nombrecargo = "'+nombrecargo+'";

La u después de usuario y la c después de cargo es un alias para la tabla.
Recuerda que el INNER JOIN se realiza después del FROM o de otros INNER JOINs (para especificar relaciones adicionales entre tablas).
La solución haciendo uso de PreparedStatement(la cual es mas segura) sería de la siguiente forma:
String sql="SELECT * FROM usuario u INNER JOIN cargo c ON c.idcargo = u.cargo WHERE rutfuncionario= ? and contrasena= ? and c.nombrecargo = ?";

PreparedStatement selUs = con.prepareStatement(sql);//se crea el objeto prepare Statement que devuelve el método prepareStatement() de tu conexión.
selUs.setInt(1,usuario); //en la primera posición de el '?', ingresa un Int (usuario) que es el ruc.
selUs.setString(2,pass); //En la segunda posición del '?' ingresa la contraseña (un String)
selUs.setString(3,nombrecargo); //En la tercera posición del '?' ingresa el nombrecargo que estás buscando (un String)

ResultSet rs = selUS.executeQuery(); //Ejecuta la consulta del preparedStatement y devuelve un ResultSet


text:
Q: Is the zero vector in the definition of linear dependence arbritary? The definition of linear dependence according to wikipedia is

The vectors in a subset $S=(v1,v2,...,vk)$ of a vector space $V$ are said to be linearly dependent, if there exist a finite number of distinct vectors $v1, v2, ..., vn$ in $S$ and scalars $a_1$, $a_2$, ..., $a_n$, not all zero, such that
   $ a_1 v_1 + a_2 v_2 + \cdots + a_k v_k = 0, $
  where zero denotes the zero vector.

I was wondering if the zero vector in the definition of linear dependence is arbritary?
Thanks,
Jackson

A: Well, if it were, then we would have a very curious situation. Try replacing $0$ with some fixed vector $v_0 \ne 0$. Then the set $\{ 0 \}$ is independent, but the set $\{ v_0 \}$ isn't!
To make things worse: if you had two vectors $a$ and $b$ such that $\{ a, b, v_0 \}$ was independent in the standard sense, then the set $\{ \lambda a + \mu b \mid \lambda, \mu \in \mathbb{R} \}$ is independent, despite being a whole subspace!
EDIT: Maybe a specific example will help. Say we define "independent" to mean "there is a linear combination that sums to $\langle 1,1,1 \rangle$. Then the set $\{ \langle 1, 0, 0 \rangle, \langle 0, 1, 0 \rangle, \langle 1, 1, 0 \rangle \}$ is independent (no matter what combination you take, the $z$-component is zero, not one, so you can never get $ \langle 1, 1, 1 \rangle $). But this is clearly silly, because one vector is the sum of the other two, and so whatever our definition is describing, it doesn't capture the notion of independence.

A: A set of vectors are called linearly dependent if at least one of them can be expressed as a linear combination of the others. Moving them all to one side we get that linear dependence is equivalent to the existence of a linear combination with one coefficient being $1$ that is the same as the zero vector. Since vector spaces are over fields, we can drop the requirement of one of the coefficients being $1$ and just require the linear combination to be non-zero (not all zero).

A: As I understand; it is not necessary that the vector on the right hand side be zero. The only necessary condition is that there exist a non-trivial representation of the the vector as a linear combination of the other vectors.
Trivial Solution
a1v1+a2v2+.........+anvn=0 only if a1=a2=a3=......=an
Alternatively; there exist atleast one non-zero scalars (a1,a2,....,an) for the set to be linearly dependent. So, the RHS can be non-zero.


text:
Q: forkJoin undefined when share component (and combining boolean variables) I have a service used in many components and I need to share the result of a forkjoin, but the component is coming as undefined
My service logic layer
         @Injectable({
                providedIn: 'root'
            })

            export class CoreStateService {
                private subject = new BehaviorSubject<any>([]);
                hasError$: Observable<any> = this.subject.asObservable();

                constructor(private api: HomeGuardService) {}

                    public verifyFailed(): Observable<any>{
                    return forkJoin([this.api.getPerfilNew$, this.api.getPosicaoConsolidada()])
                         .pipe(
                            catchError(err => {
                                this.statusError = err.status;
                                console.log('--->', this.statusError);
                                return of([]);
                            }),
                            map(([perfilInvestors, position]) => {
                                this.perfilInvestors = perfilInvestors;
                                this.investments = position;
                                //verify if perfil failed
                                if (this.statusError) {
                                    this.perfilFailed = true
                                } else {
                                    this.perfilFailed = false
                                }
                                //verify if  investments failed
                                if (this.investments) {
                                    this.hasInvestiments = true;
                                }
                                //combine investments and statusError
                                this.hasError$ = combineLatest([this.statusError, this.hasInvestiments])
                                    .pipe(
                                        map(([statusError, hasInvestiments]) => statusError && !hasInvestiments)
                                    );
                            }),
                            tap(hasError$ => this.subject.next(hasError$)),
                        );
                }
    }

In my component:
   constructor(private coreState: CoreStateService) {}

public ngOnInit() {
        this.coreState.subscribe(res => {
            console.log(res)
        })
    }

Result in console:

I Need to return to components if hasError$ is true or false.

A: 1- You need to subscribe on hasError$ instead to subscribe the whole service:
this.coreState.hasError$.subscribe(res => {
            console.log(res)
        })

2- Is there any calling to verifyFailed() in any place? because it needs to be called to produce the results.


text:
Q: Android creating a Spotify like slider menu I am making an app that should implement a slider menu like the one in Spotify (where you slide the triangle in the middle to show the current playing song). The problem is I can't seem to figure out a decent method of doing this. I tried it with a Facebook like menu I found here.
However that just provides me with 2 linear layouts which are placed next to each other and are basically stretched or unstretched when expanding the menu. This gives some layout issues when expanding/collapsing (all items are placed below each other in the linearlayout when expanding and are quietly moved into the right place when collapsing the menu again).
In Spotify on the other hand it seems as if the layouts are on top of each other when the menu is expanded. This seems like a much cleaner way. However I have no idea on how to tackle this and Google doesn't really provide a lot of answers. Physically sliding the menu up isn't necessary, just getting the layouts on top of each other with some sliding animation on clicking the menu button.
Sorry for the long post, it seemed necessary to specify the question.

A: You dont need to re-invent a view or do anything fancy to get this functionality. Its called SlidingDrawer and is already available in the framework. Read this and this or watch this video.


text:
Q: drupal 8 item.url returns error on non default language Recently my drupal 8 site which is running in both english and french fails to load in french. (English is the default language)
The error returned is

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 187 of core/lib/Drupal/Core/Routing/RouteProvider.php).

I've tracked it down to the item.url function in menu.html.twig

{{ link(item.title, item.url) }}

it returns the url is fine in english, and returns the correct item.title if called outside of link() in both languages, it's just "link.url" in the french version. Any ideas?


text:
Q: Magento2: Why does the Compare Products sidebar on category pages not show up, but return when I delete a certain layout file? See further explanation The Compare Products sidebar on category pages does not show up, and I was trying to figure out why. So I temporarily deleted files under the app/design/frontend/customer-name/default folder to see if it would come back (with help of version control to restore them).
I discovered that when I temporarily delete the file in app/design/frontend/customer-name/default/Magento_Catalog/layout/catalog_category_view.xml, the Compare Products sidebar on category pages returns.
When I try to re-add this file with only boilerplate layout xml code, it disappears again.
Adding a layout xml file with only boilerplate code should not change anything, right? Here is that file before I delete it:
<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="css/listing.css" />
        <css src="css/brand.css" />
        <link src="Magento_Catalog::js/body-class-tag-brand-modify.js" />
        <link src="js/category.js" />
    </head>
<body>
        <referenceContainer name="content" >
            <block class="Magento\Catalog\Block\Category\View" name="this.is.a.brand" template="Magento_Catalog::category/brand_tag_class.phtml"/>
           <block class="CompanyName\CategoryPage\Block\FeaturedInCategory" name="category.products.list.no.toolbar" template="Magento_Catalog::product/list_without_toolbar.phtml" />
        </referenceContainer>
        <move element="category.image" destination="columns.top" before="page.main.title"/>
    </body>
</page>

Here is the file when I re-add with only boilerplate layout xml code:
<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
    </body>
</page>

A: Discovered a solution. The boilerplate was wrong.
The difference is the value of page layout="2columns-left" in the 2nd line, instead of page layout="1column".
<?xml version="1.0"?>
<page layout="2columns-left" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="css/listing.css" />
        <css src="css/brand.css" />
        <link src="Magento_Catalog::js/body-class-tag-brand-modify.js" />
        <link src="js/category.js" />
    </head>
<body>
        <referenceContainer name="content" >
            <block class="Magento\Catalog\Block\Category\View" name="this.is.a.brand" template="Magento_Catalog::category/brand_tag_class.phtml"/>
           <block class="CompanyName\CategoryPage\Block\FeaturedInCategory" name="category.products.list.no.toolbar" template="Magento_Catalog::product/list_without_toolbar.phtml" />
        </referenceContainer>
        <move element="category.image" destination="columns.top" before="page.main.title"/>
    </body>
</page>


text:
Q: CMake: find Qt packages when two Qt versions are installed On my computer (Ubuntu-Gnome) are two Qt-versions installed. One with the package manager (5.x) and one manually to /opt/Qt (5.9).
For one project I need to use the /opt/Qt-installation with CMake. But find_package(Qt5Core 5.9 COMPONENTS CORE REQUIRED) does not find the correct installation:
  Could not find a configuration file for package "Qt5Core" that is
  compatible with requested version "5.9".

  The following configuration files were considered but not accepted:

    /usr/lib/x86_64-linux-gnu/cmake/Qt5Core/Qt5CoreConfig.cmake, version: 5.7.1

I tried to set CMAKE_PREFIX_PATH and CMAKE_MODULE_PATH to add a search path to CMake with all variants of paths but it does not work at all.
How can I correctly set the search path to the second installation at /opt/Qt/?

Updates in order to @Florian input
This works:
find_package(
   Qt5Core 5.9
   COMPONENTS
      Core
   REQUIRED
)

together with
cmake -DQt5_DIR:PATH=/opt/Qt/5.9.2/gcc_64/lib/cmake/Qt5Core

but in this case I found only QT5Core. With that it seems to work for all components as well:
find_package(
   Qt5 5.9
   COMPONENTS
      Core
   REQUIRED
)

together with
cmake -DQt5_DIR:PATH=/opt/Qt/5.9.2/gcc_64/lib/cmake/Qt5

2nd Edit
To avoid to always put the the full path in the call I add this to the my CMakeLists.txt:
set(QT_INSTALL_PATH /opt/Qt)
file( GLOB_RECURSE sres ${QT_INSTALL_PATH}/*/Qt5Config.cmake )
get_filename_component( Qt5_DIR ${sres} DIRECTORY )

Afterwards this works fine:
find_package(
   Qt5 5.9
   COMPONENTS
      Core
      Network
   REQUIRED
)

A: Use cmake -DQt5_DIR:PATH=/opt/Qt5/5.9.2/gcc_64/lib/cmake/Qt5
Documentation


text:
Q: How to store a table's values in a list and sort them? I want to test if sorting of first names column in a table is working fine or not. This table consists of 3 columns, "First name", "Last name" and "Email".
This is how the first name column is :
First Name column
Columns
I can get the all the "First name" values in table and see all of them in console.
My question is how can I store this value in a list and sort them and then compare them with the table values.
Here is the code :
int numOfClicks = Int32.Parse(driver.FindElement(By.XPath(".//*[@id='injectview']/div/div/div/table[2]/tbody/tr/td[1]/ul/li[8]/a")).Text);
        Console.WriteLine(numOfClicks);
        driver.FindElement(By.XPath(".//*[@id='injectview']/div/div/div/table[2]/tbody/tr/td[1]/ul/li[1]/a")).Click();
        Thread.Sleep(2000);

        for (int i = 1; i <= numOfClicks; i++)
        {
            IList<IWebElement> records_in_page = driver.FindElements(By.XPath(".//*[@id='injectview']/div/div/div/table[1]/tbody/tr/td[1]"));

            for (int j = 1; j <= records_in_page.Count; j++)
            {

                string firstName = driver.FindElement(By.XPath(".//*[@id='injectview']/div/div/div/table[1]/tbody[" + (j + 1) + "]/tr/td[1]")).Text;
                Console.WriteLine(firstName);

            }
            driver.FindElement(By.CssSelector("#injectview > div > div > div > table:nth-child(3) > tbody > tr > td:nth-child(1) > ul > li.pagination-next.ng-scope > a")).Click();
        }

Rest of the code is just navigating to the page and I just sent the part that gets column's values.
Thank you for your help.

A: You have to save your first name in a list and then compare them.
If you have Id/Class name for the first name you can get all the first names with a better approach
    List<string> fromTable = new List<string>();

    for (int j = 1; j <= records_in_page.Count; j++)
    {
    string firstName = driver.FindElement(By.XPath(".//*
    [@id = 'injectview'] / div / div / div / table[1] / tbody[" + (j + 1) +
    "]/tr/td[1]")).Text
    fromTable.Add(firstName)
    }

    public bool  Comparer(List<string> fromTabel, List<string> fromDb)
    {
        bool equals = false;
        if(fromDb.Count().Equals(fromTabel.Count()))
        {
              foreach (var name in fromDb)
              {
                equals = fromTabel.Any(n => n == name);
                if(equals == false)
                  return equals;
              }

        return equals;
        }
    }


text:
Q: How to check if the X11 display manager is installed? I recently had some problems on sharing the screen on zoom, and I found out that disabling Wayland does the trick.
It worked fine for my computer, but when I tried doing this on another computer, I wasn't able to login anymore.
My question is: How can I check if I X11 is installed before disabling Wayland?
Thank you in advance!

A: To see if you have x11 installed, simply run this command from a terminal:
dpkg -l | grep xserver-xorg-core

and if you get something like:
ii  xserver-xorg-core                      2:1.19.5-0ubuntu2                                          amd64        Xorg X server - core server

then you have the server installed.


text:
Q: Basic Variable Indexing How do you do a simple index/array in Python?
For example, in a traditional BASIC language, all you would have to do is something like
10 Dim V(5)
20 For N = 1 to 5:V(N)=2^N+1/N:? N,V(N):Next

which would output:
1  3.0
2  4.5
3  8.33333333333
4  16.25
5  32.2

If I wanted the weights of Gaussian quadrature, I could do:
UL=5
[x,w] = p_roots(UL)
for N in range(UL):
     print N,w[N]

which works:
1  0.236926885056
2  0.478628670499
3  0.568888888889
4  0.478628670499
5  0.236926885056

but if I try my BASIC, as it would seem to be
UL=5
for N in range(1,UL+1):
    V[N]=2**N+1.0/N
    print N,V[N]

which rejects it as
    V[N]=2**N+1.0/N
NameError: name 'V' is not defined

and if I try to mimic the Gaussian example
UL=5
[V]=2**UL+1.0/UL
for N in range(1,UL+1):
    print N,V[N]

I get
    [V]=2**UL+1.0/UL
TypeError: 'float' object is not iterable

In terms of arrays/indexing, isn't V[N] the same as w[N] (which works in its example)?
All of the Python documentation seems to jump into more complicated cases, without providing more rudimentary examples like the above.

A: Your errors seem clear: in your first you have not defined V at all (compare with your BASIC version where you used Dim V) and in your second you have assigned V to a single value (2**UL+1.0/UL), not a list of values.
However, you should note that Python lists are not arrays, and you do not size them. Instead, you compose them as you go by appending. For instance, in the first version:
UL = 5
V = []
for N in range(1,UL+1):
    V.append(2**N+1.0/N)


text:
Q: Automatic VPN connection if a trusted network isn't found? I'm trying to figure out if this is even possible. I want my laptops to automatically connect to a trusted network if they're in range (Ie my wireless or hardwired). If they're not in range I want the computer to automatically connect to my internal network through VPN.
I know that I can configure a VPN to automatically connect to a specific network. I'm not aware if it's possible to let the in-range trusted network connection to take connection precedence and connect automatically. If it's not found, then make sure that connection automatically uses VPN to connect to my internal network. I don't want the user to have to connect through VPN manually.
Any one have experience with this or have heard about it?
Edit for clarification: Basically I want my laptop to automatically connect to my intranet via VPN if the computer is not in range of my own secured Wi-Fi. If I'm on my own network's Wi-Fi and try to connect to it via VPN the credentials will just cycle. Re-configuring the network to accept internal vs external IPs via VPN isn't possible in my situation. I basically need a way to automtically tell the machine without user intervention "If Sh0ck's-Trusted-Wifi isn't found, connect to his intranet via  VPN with whatever connection you do have"

A: Yes. Windows Server 2008 R2 and newer has a technology that specifically works this way. It's called Direct Access. It's easier to setup in most network architectures under Server 2012. The client must be Windows 7 Enterprise or Ultimate, or Windows 8 Enterprise.
It uses IPSec and HTTPS; it works based on the machine containing a cert from your domain, and your user credentials. It's totally in the background, requiring no user intervention at all.


text:
Q: Read data in Raspberry Pi from an SPI connection with spidev library in python I want to transfer data from an external device to my Raspberry Pi 3 model B. I'm using SPI protocool to do this task. I'm using spidev library on python. I have already created the next program:
#/usr/bin/env python3
import spidev
import time

spi = spidev.SpiDev(0,0)
spi.max_speed_hz= 122000

while True:
    print(spi.readbytes(1))
    time.sleep(2)

When I run the program I get always the same result: ([0]).
I don't know if this is the correct method to read data on spidev. I'm new with spidev library and I would be so grateful to hear any suggestions of how to do this task.


text:
Q: convert columns into rows pandas So my df has some information by store ,type of product (price) , and date
the problem is that the tree different products are in columns but I need in rows.
For example my df looks like this:

Store
PRODUCT X
PRODUCT Y
product z
date

aaa
$$$$
$$$$
.  $$$$
2021/02/07

bbb
$$$$
$$$$
.  $$$$
.

and I want to look like

Store
PRODUCTS
PRICE.
date

aaa
PRODUCT X
$$$$
2021/02/07

aaa
PRODUCT y
$$$$
2021/02/07

aaa
PRODUCT z
$$$$
2021/02/07

bbb
PRODUCT X
$$$$
2021/02/07

bbb
PRODUCT y
$$$$
2021/02/07

bbb
PRODUCT z
$$$$
2021/02/07


text:
Q: What is the best way to store the amount of time spent (hours : minutes) in MongoDb? I'm playing with a small web application to store tasks and time spent on a daily basis, and report on it in weekly and monthly reports.
For my back-end I wanted to work with MongoDb but can't immediately find what the best way would be to store the time spent on a task.
I have no interest in storing the actual timeframe (start and stop date), just the time spent in hours:minutes.
Since I will be making weekly and monthly reports, I need to be able to calculate the sum on a weekly, monthly basis.
What would be the best way to store the time spent?
I'm leaning towards just storing the amount of minutes in a 32-bit integer and convert it to hours:minutes on the client. (Or better yet, convert it already in a Mongodb Aggregation Query, if that's possible?)
My Task document would look like this then
{
    "task_id": {
        "$oid": "5311a0a4e4b0386017fce592"
    },
    "timeEntry_date": "ISODate('2014-03-02')",
    "timeSpent_minutes": 30
}

Is this the way to go in MongoDb?
Sorry if I'm stating the obvious here, just starting to learn about MongoDB...

A: As always on MongoDB "It depends on your usage". In MongoDB you should construct your "schema" so that it will describe your application needs and not your data structure.
If your application is write intensive you should have a really fast and simple writing procedure. eg you can store the milliseconds spent and then do the calculations on read
If you want your application to be faster in reads you can have something like
time_spent: {
  hours: 1,
  minutes: 23,
  seconds: 45
}

in your document
PS I think that
"task_id": {
        "$oid": "5311a0a4e4b0386017fce592"
}

would be better as
task_id: "5311a0a4e4b0386017fce592"

A: Given the requirements as stated, you'll be best served by serving the data as a numerical value. There are far more query and aggregation operators that would be easily used for a numeric value than the few other options that are available.
While you could store the period as a string, it would need to be consistently zero padded to sort correctly. With a string, you could only effectively do exact matches and range queries (find all that are "0030" or between "0015" and "0045" for example).
While you could also store the start and end times and try to calculate the period, it adds unnecessary complication to queries, and in fact may make some types of queries only possible using the aggregation framework. You might find some of the ideas here interesting depending on your needs as well.
The absolute performance difference between any option where the time length is directly stored as a value rather than computed is not likely to be measurable, as they would consume nearly the same amount of space for each option.  If you're concerned about absolute disk space usage, I'd suggest you consider using shorter field names. Every document contains the full field name. Some drivers for Mongo provide a handy way of using an alias for field names (by keeping the name you use in code friendly and using a shortened version n the stored document).
I'd go with storing a integer numeric value that best suits the maximum length of time you'll encounter. You can add an index if it's frequently queried, and easily convert it on the client into something more human friendly.


text:
Q: How to get a refresh token from Google YouTube Data API OAuth 2 iOS I am using OAuthSwift pod for Google API authentication. In the callback, the refresh token is missing. As Google is returning 500 Server Error, when trying to ask for a new token after user already authenticated, I want to store the refresh token, and authorise the user the next time they login, and retrieve a new token.
This is my code:
           let callback = "\(Bundle.main.bundleIdentifier ?? ""):/oauth2Callback"
            _ = ytOAuth2Swift?.authorize(
                withCallbackURL: URL(string: callback)!,
                scope: "https://www.googleapis.com/auth/youtube", state: state,
                success: { credential, response, parameters in

                   print("YouTube Access_Token \(credential.oauthToken)")
                    print("YouTube efreshR_Token \(credential.oauthRefreshToken)")
                },
                failure: { error in
                    print("ERROR: \(error.localizedDescription)")
            }
            )

This is the response we do get back!

According to Google API docs, this is the response that should come in:
{
   "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
   "expires_in":3920,
   "token_type":"Bearer",
   "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

I tried using an embedded WebView no luck:
[

A: Well it looks like google API gave you refresh token once at the begining, and new requests doesn't give it anylonger. If yes you should know that refresh_token is only provided on the first authorization, so if you authorize more times it may not return the refresh_token again. Please try following instructions:

*

*Go to your account security settings: https://www.google.com/settings/u/1/security.

*Click the edit button next to "Authorizing applications and sites".

*Then click "Revoke Access" next to your app.

After it you next call should also return a refresh_token
It might be a bit different, because I do not use english language in my panel. When I was using refresh_token from google it never expires, you can use it forever to create new access_tokens.
Another solution
If it won't work, try  to set up in your code access_type as offline (I think easiest way is just to add a GET param in your API url as access_type=offline).
Necessary may be also prompt=consent in query. It will force user to authorize, and should then return refresh_token
More informations can be found in Google Documentation: Oauth2
Tip
Good thing in Google API is that refresh_token never expires, until you wont revoke it or create a new one. So you can even hardcode it and use everytime you want to get a new access_token.


text:
Q: Why Spring MVC doesn't validate parameter with generic type
I know there are several questions related this subject. This question is about "why"

When resolving argument in controller, validation not works as expected.
both of codes below not working
public void foo(@RequestBody @Valid List<MyDTO> requests) {
 ...
}

public void foo(@RequestBody List<@Valid MyDTO> requests) {
 ...
}

However, when I add @Validated annotation to my controller, then it works.
After I digged into the code, I found that the argument resolver just finds annotations by getParameterAnnotation in java.lang.reflect and this doesn't extract @Valid annotation in type like List<@Valid MyDTO>.
However, proxy handler of @Validated can extract it through ParameterizedType in java.lang.reflect. (this may be wrong `cause I'm not good at debugging)
Why are they different ? Is this just mistake ? or Is there any reason?


text:
Q: when I create a ViewController, "also create a xib" can't be seleted
last week, it work well. and there is nothing like "viewDidLoad" at the .m file.
My xCode version is 7.1.1. what's wrong.

A: Make sure you selected iOS Source in the left part of the image

A: Can you check? The issue might be you didn't select cocoa class from iOS.
Possible solution can be found here.
Can not create an iPhone xib file with Xcode 6


text:
Q: File access error - already in use when reading from file (vb.NET 2.0) Using:
Dim fileStream as System.IO.FileStream = System.IO.File.Open(filename, FileMode.Open)

as opposed to (see end of line):
Dim fileStream as System.IO.FileStream = System.IO.File.Open(filename, FileMode.Open, FileAccess.Read)

In
Dim fileStream as System.IO.FileStream = System.IO.File.Open(filename, FileMode.Open)
Dim data(fileStream.length) as Byte
fileStream.read(data, 0, fileStream.length)
fileStream.close()

Would the addition of the FileAccess.Read flag stop the encountering of already in use when reading from file exception?
Put better - Can you access in Read-only mode even when open somewhere else?

A: If you don't specify the access explicitly with FileAccess.[Value] then the System.IO.File.Open(...) function defaults to read/write, inducing the error.
See: http://msdn.microsoft.com/en-us/library/system.io.file.open.aspx


text:
Q: Sparkling Water (pysparkling) in Spark Standalone cluster I've set up a Spark Standalone cluster (1 master and 2 slaves, to start with) and like to use Pysparkling on in. My understanding is that I have to install h2o_pysparkling_2.0 (I'm running Spark 2.0.2), requests, tabulate, colorama and future on the master instance (I'm using Anaconda distribution, so that I shouldn't care about numpy and the like):
pip install h2o_pysparkling_2.0
pip install requests
pip install tabulate
pip install future
pip install colorama

However, I don't know whether I must install the same packages on the slave instances. I think so, but I'd like to know whether any of you have some information on this. Available official documentation and blog posts do not provide specific information on this issue.

A: The python dependencies need to be available on all nodes where Spark/Sparkling Water is running - that means on both executors and driver.
This is because the operations are executed in parallel and require the same dependencies as on driver. What I would suggest is to run your Spark application in the uniform environment - ie, have same environment, dependencies for all spark executors and driver to prevent bunch of issues


text:
Q: How thesy are valid if the coordinate is a right-handed coordinate system? I am trying to understand how $(1),(2) \text{ and } (3)$  are valid if the coordinate is a right-handed coordinate system. The definition of a right-handed coordinate system is a one such that $\overrightarrow{i} \times \overrightarrow{j} =  \overrightarrow{k}$ is valid. To me, to prove that I must compute all possibilities to verify that result. Is there any other method?
$$\overrightarrow{i} \times \overrightarrow{j} =  \overrightarrow{k} \qquad(1)\\
  \overrightarrow{j} \times \overrightarrow{k} =  \overrightarrow{i} \qquad(2)\\
  \overrightarrow{k} \times \overrightarrow{i} =  \overrightarrow{j} \qquad(3)$$
I want to very that $(1),(2) \text{ and } (3)$ is valid as long as it is a right-handed coordinate system. what I mean by possibilities is to try all the different ways that $x,y$ and $z$ can be. For example:

[https://en.wikipedia.org/wiki/Cross_product#Computing_the_cross_product]

A: $\vec i \times \vec j = \vec k$ in a right-handed orthonormal coordinate system. That is, a coordinate system where the three basis vectors are all orthogonal to each other and have length $1$. General coordinate systems may have $\vec i \times \vec j \ne \vec k$. They are called right-handed when $(\vec i \times \vec j) \cdot \vec k > 0$.
I will assume that you are only asking about orthonormal coordinate systems. One identity for the cross product is the "bac-cab" rule:
$$\vec a \times (\vec b \times \vec c) = \vec b(\vec a\cdot\vec c) - \vec c(\vec a \cdot \vec b)$$
Since the coordinate system is orthonormal, if $\vec i \times \vec j = \vec k$, then $$\vec j \times \vec k = \vec j \times (\vec i \times \vec j) = \vec i (\vec j \cdot \vec j) - \vec j(\vec j \cdot \vec i) = 1\vec i - 0\vec j = \vec i$$
$$\vec k \times \vec i = \vec k \times (\vec j \times \vec k) = \vec j(\vec k \cdot \vec k) - \vec k (\vec k \cdot \vec j) = 1\vec j - 0\vec k = \vec j$$


text:
Q: Assignment on PDE with Neumann boundary conditions So, I got the following assignment.
Let $D\subset\mathbb{R}^n$ bounded open set woth smooth boundary. Consider the Neumann boundary problem $$-\Delta u =f \text{, and } \left.\frac{\partial u}{\partial \nu}\right|_{\partial D}=0.$$
(a) Define the notion of weak solution.
(b) Formulate and prove an existance theorem for weak solutions.
So, what I have done so far.
We have $-\int_D\Delta u\; v=\int_D Du\; Dv-\int_{\partial D}\frac{\partial u}{\partial \nu}v$ when ever this makes sense and by enforcing the boundary conditions we get $-\int_D\Delta u\; v=\int_D Du\; Dv$. A solution to the problem satisfies $-\int_D\Delta u\; v=\int_D f\; v$, $\forall v\in L^2(D)$, so we get $$-\int_D\Delta u\; v=\int_D f\; v, \forall v\in H^1 (D).$$
Let $u\sim v \Leftrightarrow u-v=c\in\mathbb{R}$ and let $V$ be the space created of choosing from every equivalent class in $H^1(D)$ the function with the smallest norm. It's eaasy to show that $V$ is Hilbert.
Anyway, I would like to use LAx-Milgram on $V$. So let $B(u,v)=\int_D Du\; Dv$. $B(\cdot,\cdot)$ is clearly bilinear. $|B(u,v)|\le ||Du||_{L^2(D)}||Dv||_{L^2(D)}\le ||u||_{H^1(D)}||v||_{H^1(D)}$.
Then assume that $B(u,u)=0\;\Rightarrow\;\int(Du)^2=0\; \Rightarrow u=c$, but by definition of $V$, $u=0$. So Lax-Milgram theorem can be applied here, which means that for every functional $F(v)=\int_Df\;v$ on $V$ there is a unique element $u$ of $V$ for which we have $B(u,v)=F(v)$.
The problem I have here is that $V$ is too big, in fact I forgot about the boundary condition. Now I would like to define $V_0=\{u\in V:\left.\frac{\partial u}{\partial \nu}\right|_{\partial D}=0\}$ but I am afraid that $\left.\frac{\partial u}{\partial \nu}\right|_{\partial D}$ is not in $L^2(\partial D)$ for all elements of $V$ but rather for only for $V\cap H^2(D)$.
Also there is a hint in the assignment that says to use the fact that if $v\in H^1(D)$ and $\int_D f=0$ then $||f||_L^2(D)\le C ||Df||_{L^2(D)}$ and I cannot see how this is useful to me.

A: *

*Weak solution $u$ to the homogeneous Neumann boundary value problem:
$$\text{Solution space: }u \in H^1(D), \quad \int_{D} u =0$$
such that
$$
\int_{D} \nabla u\cdot \nabla v = \int_D fv,\quad \text{ for any } v\in H^1(D).\tag{1}
$$
Brief derivation: multiply the equation $-\Delta u = f$ by a test function $v$ and integrating by parts on $D$
$$
\int_{D} -\Delta u v = \int_{D} \nabla u \cdot \nabla v - \color{red}{\int_{\partial D} (\nabla u\cdot \nu)v \,dS} = \int_D fv.
$$
Red term vanishes because of the boundary condition. The weak formulation of the Neumann boundary problem is (1), and it is NOT $$\displaystyle \int_{D} -\Delta u \,v = \int_D fv,\tag{2}$$ for now in (1) the lowest regularity $u$ can have is $H^1(D)$, if we write in integration way somehow we are assuming $-\Delta u\in L^2$, a.k.a. strong solution, if we don't abuse our notation using integration to represent the duality pair between $\big(H^1(D)\big)'$ and $H^1(D)$. Now solution to (2) is automatically solution to (1). Conversely, the weak solution, which is the solution of (1), is not the strong solution unless certain conditions are met.

*Lax-Milgram: You already checked the continuity, the coercity can be checked using the hint which is the Poincaré inequality for zero average functions. Let $\bar{u} = \frac{1}{|D|}\int_D u = 0$, we have
$$
\|u\|_{L^2(D)} = \|u - \bar{u}\|_{L^2(D)} \leq C\|\nabla u\|_{L^2(D)},
$$
hence
$$
\int_{D} \nabla u\cdot \nabla u \geq c \left(\int_{D} \nabla u\cdot \nabla u + \int_{D} u^2\right) = c\|u\|_{H^1(D)}^2,
$$
which is the coercivity. Now you can use Lax-Milgram.

*Compatibility condition: the right hand side data $f$ has to have average $0$ as well, for
$$
\int_D f = \int_D -\Delta u = -\int_D \nabla u\cdot \nu \,dS=0.
$$
To guarantee the weak formulation (1) has a solution, this compatibility condition has to be met.

A: It actually just hitted me. The space $V$ is defined by taking one function from each equivalent class. We might as well define $V:=\{f\in H^1(D):\int_Df=0\}$. Then $B(\cdot,\cdot)$ can define an equivalent norm on $V$, by using the hint, so there is no need for Lax-Milgram theorem, Reisz representation theorem tells us that indeed there is a unique element $u$ in $V$ such that $B(u,v)=F(v)$. So there is a weak solution of the problem if $\int_Df=0$.
Actually i think that $\{f\in H^1(D):\int_Df=0\}$ and $V$ as defined in the question are in fact the same space but I couldn't figure out a quick proof.


text:
Q: Qmake does not support build directories below the source directory I have created an application that compiles and runs like a charm on OS-X.  I would now like to start getting it to work on Windows.  To start, I copied the project to a windows machine and just tried to compile, but got this error:

:: warning: Qmake does not support build directories below the source directory.

Any ideas?

A: Andref gave the correct answer to resolve this warning, but you may want to understand why this requirement exists.
In fact, the build directory must be at the same folder level as the project (i.e. it can't be above or below). The reason why is that the linker is called from the build directory. Hence, any relative paths to library files will be different than what you entered in your project file.
It kinda sucks. I like to put all intermediate files in their own folder. But you simply can't with qmake.

A: .pro.user are generated files by Qt Creator. They are unrelated to qmake and should not be touched (and not put into a VCS for that matter)

A: Set the shadow build directory to some folder on the same level of your project directory:
folder/
  project/
  project-shadow-build-release/
  project-shadow-build-debug/

You can do this in the "Projects" view, via the toolbar on the left. To me, this warning was just an annoyance, a project never failed to build because of it.

A: Don't copy your project.pro.user file when you are copying a project from one machine to another, or from one directory to another. When you open the project, Qt Creator will offer to create a new build directory in the proper place.

A: Just remove the files with the pro.user extension , worked for me

A: I also got this, trying to compile a project created on linux.
Another way to solve it is to change the paths in the .pro.user file (in the directory of your project)

A: *

*Right Click on a project: Set As Active Project

*Click on the Projects button (The one with the spanner image)

*Edit build configuration : Debug / Profile / Release / and change the default directories, OR just uncheck the Shadow build check box.

*

*The Build directory path should now change to black, from red


text:
Q: Replace a specific part of a string using MySql I have many Strings in the database Like

I want to change these in a way like,
Original: www.youtube.com/embed/-qTiYA1WiY8&index=8&list=PLPNcLSfYNC3Dw535smncyHRCBRmdf1Bti
Desired:- www.youtube.com/embed/-qTiYA1WiY8
So the final String can be converted to

I can do this using php but I prefer to do it with a mysql query
I tried to use:
UPDATE MyTable

    SET StringColumn = REPLACE (StringColumn, 'SearchForThis', 'ReplaceWithThis')

It needs to be a general solution that can replace string from & and before " if exist in a String

A: This ought to do what you want
UPDATE MyTable
SET StringColumn = REPLACE (StringColumn, CONCAT('&', SUBSTRING_INDEX(SUBSTRING_INDEX(StringColumn, '"', 2), '&', -2)), '')
WHERE ConditionColumn = <CONDITION>

assuming that the value of src contains two instances of & and is enclosed in double quotes

A: use as per below-
UPDATE mytable SET stringcolumn=SUBSTRING_INDEX(stringcolumn,'&',1);

You can check your output before updation by below query-
SELECT SUBSTRING_INDEX(stringcolumn,'&',1) FROM mytable;


text:
Q: Gradle eclipse task adds unnecessary test sources to Web Deployment Assembly in Spring Source Tools I am getting in trouble with Spring Tool Suite Eclipse and Gradle. When I run "eclipse" task, it modify my Web Deployment Assembly (WDA) as shown on picture.

Last tree items in WDA (not in screen, they are in bottom of list) are correcly set sources:
src/main/java | WEB-INF/classes
src/main/resources | WEB-INF/classes
src/main/webapp | /

but all these folder sources as you can see on screen are wrong. I cant start application because it try create beans from test config. Everytime i have to delete them manually and it waste my time.
How can I solve this behaviour?
I dont know if there is trouble somewhere in definition, that the deploy path is WEB-INF/classes (and if so, how to make it corretly) or if problem is in adding these folders to WDA. I can`t find where is this behaviour defined.
Or is possible to remove them with gradle in eclipse task? I cant figure out where is this stored in eclipse and if I can manipulate with it.

A: I ended with this hack. It manipulates with .settings/org.eclipse.wst.common.component file and removes all nodes whose source starts with "/src/"
eclipse.wtp.component {
    file.withXml { xml ->
            def node = xml.asNode()
            def wbrNodes = node.'**'.findAll { it.name() == 'wb-resource' && it.'@source-path'.startsWith("/src/")}

            if (wbrNodes.size() > 0) {
                    wbrNodes.each { n -> n.parent().remove(n) }
            }
    }

}

A: I've found Gradle's eclipse and eclipseWtp task to do a pretty bad job of generating the Eclipse project configuration and they don't seem to update them to keep up with WTP changes. So instead I install the Gradle plugins for Eclipse (part of Spring Tool Suite) and then manually configure the project after running gradle eclipse one time. Then check in all the Eclipse project files (which is how Eclipse is designed to work). That way I get the Eclipse project configured exactly the right way and anyone else who checks it out can do so directly into Eclipse without any other steps.
With the Eclipse project configured as a Gradle project, I can easily update it if the dependencies are changed by right-click on project and choosing Gradle > Update Dependencies which just re-generates the dynamic Gradle classpath container without touching any of the Eclipse files.