text:
Q: Redireccionamiento laravel vue broadcasting Quisiera saber si a alguien se le ocurre como puedo solucionar el siguiente inconveniente que estoy teniendo.
Tengo una vista de perfil de administrador que valida en tiempo real con broadcasting y eventos unos datos.
Por otro lado la vista a validar donde el usuario espera esa autorización.
Al validar los datos la vista del usuario debe ser redirigida a otra vista y la del perfil administrador debe permanecer sin ningún redireccionamiento.
El problema es que ambas vistas son redirigidas a través del objet mounted de vuejs. No comprendo por que hace esto si mounted sólo está en la vista del usuario no en el perfil administrador.
Admin Controller
public function cambiarEstado($estado, $id){
    Acceso::where('id', $id)->update(['estado' => $estado]);

    //Usamos broadcast
    $message = 'Usuario verificado!';
    $user = User::find(Auth::id());
    event (new ChatEvent ($message, $user));

    return redirect('/admin');
}

Vue usuario
mounted(){
    Echo.private('my-chat')
    .listen('ChatEvent', (e) => {
        window.location.href = '/mails';
    });
}

EDITADO:
Vue Admin
    @extends('layouts.app')

@section('content')

Validador

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

                          N°
                          Instagram
                          email
                          celular
                          codigo
                          {{-- estado	 --}}
                          Estado
                          Cambio de Estado
                          Fecha

                        <?php $i=1; ?>
                        @foreach($datos as $usuario)

                          {{$i++}}
                          {{ $usuario->user->IdInstagram }}
                          {{ $usuario->email }}
                          {{ $usuario->celular }}
                          {{ $usuario->codigo }}
                          {{-- {{ $usuario->estado }}	 --}}

                            @if($usuario->estado == '1')
                              Aprobado
                            @else
                              Desaprobado
                            @endif

                              id}}">APROBAR
                              id}}">DESAPROBAR

                          {{ $usuario->created_at}}

                        @endforeach

@endsection

EDITADO:
VUE VIEW
validarCodigo: function(){

        var url = '/acceso';
        axios.post(url, {
            usuario_id: this.usuario_id,
            email: this.email,
            celular: this.celular,
            codigo: this.codigo,
            estado: this.estado
        });

        if(this.estado == '2')
            $("#ocultaEstado").css("display", "block");
        else{
            $("#ocultaEstado").css("display", "none");
        }
    }

El problema es ese las dos vistas son redireccionadas a la dirección mails. ¿Que podría hacer para solucionarlo?
Agradezco mucho el tiempo invertido en leer mi consulta. Toda sugerencia es bienvenida


text:
Q: How to Python requests to follow URL like my browser I've noticed that the requests library for Python does not follow certain URL redirects like my browser.
For example, when I do:
response = requests.get('http://www.bbmt.org/', verify=False, allow_redirects=True)

The final URL is https://secure.jbs.elsevierhealth.com/action/consumeSsoCookie?redirectUri=http%3A%2F%2Fwww.bbmt.org%2Faction%2FconsumeSharedSessionAction%3FMAID%3DJ3%252BqsjOKzWZhWAeF2bXl%252FA%253D%253D%26JSESSIONID%3DaaaorUqRLHgAe4WCenKv%26SERVER%3DWZ6myaEXBLEt1UgI9cIkvA%253D%253D%26ORIGIN%3D470200154%26RD%3DRD&acw=&utt=
However, in my browser, I am eventually redirected back to http://www.bbmt.org/.
Is there a way to have requests behave like my browser in these scenarios?

A: The redirect inside the https://secure.jbs.elsevierhealth.com is a javascript redirect.
You can see it inside the source-code:
window.location.href = "http://www.bbmt.org/action/consumeSharedSessionAction?SERVER=WZ6myaEXBLHj3ZzqSv9HPw%3D%3D&MAID=IBS8Eq6B1iRWhf2ywTW5pg%3D%3D&JSESSIONID=aaa8eY-zM394XcPptT_Kv&ORIGIN=670572791&RD=RD";

You will need to run javascript in order to do this redirect (and this is something requests do not do).
If you need a solution for this specific redirect, you can parse the content of the response (in python) and take that specific URL and use it to create a new request.
If you need a general solution - you will need to use a headless browser to do that. You can find more information in this question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scoped style affecting other pages I have two pages in my nuxt app and both pages should have different backgrounds. However one background is overriding the other
index.vue

<style scoped>
body {
  background-color: #ffffff;
}
#banner {
  background-image: url("~assets/img/newbg.png");
}
</style>

login.vue
<style >

body {
  background-image: linear-gradient(
      to right,
      rgba(0, 0, 0, 0.9),
      rgba(0, 0, 0, 0.4)
    ),
    url("~assets/img/starter_image.jpg");
  background-position: center;
  background-size: cover;
  position: relative;
}
</style>

The background of the login.vue overrides the index.vue. if a scope the style of login.vue the styling of the page changes.

A: It will definitely override the styles because you're not using scoped attribute which will allow it to override the styles of the parent component.
If you want to have another background in Login.vue
then this might help:
Inside Login.vue
HTML:
<div id="wrapper" v-bind:style="bgc">
    *Write your html here*
</div>

CSS
#wrapper {
  height: 100vh;
  width: 100vw;
  background-color: #111;
  position: absolute;
  left: 0;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  transition: 0.5s;
}

JS
new Vue({
    el: '#wrapper',
    data: {
        bgc: {
            backgroundColor: ''
        }
    }
})

A:

index.vue

    <style scoped>
    body {
      background-color: #ffffff;
    }
    #banner {
      background-image: url("~assets/img/newbg.png");
    }
    </style>

  login.vue

    <style scoped>

    body {
      background-image: linear-gradient(
          to right,
          rgba(0, 0, 0, 0.9),
          rgba(0, 0, 0, 0.4)
        ),
        url("~assets/img/starter_image.jpg");
      background-position: center;
      background-size: cover;
      position: relative;
    }
    </style>

you can use scoped for your component that will not affect to your other component.there are two different components (login, index).


text:
Q: JSSOR - Cannot read type property 'currentStyle' of undefined I'm trying to implement the Jssor slider into my page, but I keep coming up with that error in the title.
My content is being dynamically created via Javascript, like so:
var slide = app.createHTML('div', "", {'id':'inventorySlides'}, null);

var div = document.getElementById('invDiv');
div.appendChild(slide);

and then I procedurally generate cell divs in the same way and append them to slide.
I've defined a function in my main controller as in the example on the basic usage page (http://www.jssor.com/development/basic-usage-no-jquery.html), and after all the content has been generated and appended, I call the function
jssor_slider1_starter('inventorySlides');

But then I get the error message in the console. I've tried logging the inventorySlides div, and it definitely exists in the DOM, so I know it's not that. I tried searching for currentStyles, which turns out is just on IE and Opera, and I'm using Chrome.
So is it something I'm doing wrong? Or is it Jssor that's misbehaving?

A: So firstly, I had forgotten to include jssor.core.js and jssor.utils.js, though that did not fully solve my problem.
The Solution was that I needed to create a div with an attribute u="slides", which goes inside the 'inventorySlides' div, and the cells are nested inside this new div

NOTE: I made this answer much later than when it was asked because at the time I did not have enough reputation to be able to answer my own question, and now I no longer have access to the code this question is referencing, so I can't really add much more detail to the answer than what had already been discussed in the comments. I apologize if there's any details you need that this answer does not provide, but I can't help much past this point. Cheers - Dan

A: If you are including jssor.js file after the html slider elements, then you are getting same error.
The solution : include jssor.js file bottom of the page.


text:
Q: select values seperated by Comma using Group By I want to select commaa seperated values using Group By.
Example: If i want to list  all states of America seperated by comma and group by country Name which is America.

A: Here you go: Since you are not sharing more details with us, this is not done using "GROUP BY", but rather abusing the GROUP (which is stackoverflow):
America, Alabama
America, Alaska
America, Arizona
America, Arkansas
America, California
America, Colorado
America, Connecticut
America, Delaware
America, Florida
America, Georgia
America, Hawaii
America, Idaho
America, Illinois
America, Indiana
America, Iowa
America, Kansas
America, Kentucky
America, Louisiana
America, Maine
America, Maryland
America, Massachusetts
America, Michigan
America, Minnesota
America, Mississippi
America, Missouri
America, Montana
America, Nebraska
America, Nevada
America, New Hampshire
America, New Jersey
America, New Mexico
America, New York
America, North Carolina
America, North Dakota
America, Ohio
America, Oklahoma
America, Oregon
America, Pennsylvania
America, Rhode Island
America, South Carolina
America, South Dakota
America, Tennessee
America, Texas
America, Utah
America, Vermont
America, Virginia
America, Washington
America, West Virginia
America, Wisconsin
America, Wyoming


text:
Q: Unable to use the full space of canvas I need to use the full space of canvas to draw. But here unable to use the top and left of the canvas to draw. I try make some changes in css, still no luck. Please help.
p.s. By clicking the button the canvas will popup.
<button onClick="openPopup();">click here</button>

    <canvas id="canvas1" width="750" height="720" style="border: 1px solid black"></canvas>

A: The drawing point is not synced with mouse pointer.
That is the reason why you can't draw at the left part and the top part of the canvas, because the mouse is already out of the canvas if you try to draw something nearby the left edge.
Notice that how you get the current position of the drawing point:
function getMouse(e) {
    var element = can, offsetX = 0, offsetY = 0;
    mx = e.pageX;
    my = e.pageY;
}

the variable e refers to mouseEvent object. and e.pageX means the distance between the mouse  and the left side of the page, NOT YOUR CANVAS. So you should minus the left offset of the canvas from mx and do the same to my, so that the drawing point is right on where you want.
One simple solution:
set the canvas's margin, border and padding to 0;
.popup{
    //everything else..
    boder: 0;
    margin-left: 0px;
    margin-top: 0px;
    }

Better solution:
minus the left offset to mx and my
function getMouse(e) {
    var element = can, offsetX = 0, offsetY = 0;
    mx = e.pageX - 305;
    my = e.pageY - 95;

    //Dynamically getting those padding and margin and border would be better!
}


text:
Q: Columnar Database Comparisons and DBA efforts I'm trying to find a database solution and I came across Infobright and Amazon Redshift as potential solutions. Both are columnar databases. Infobright has been around for quite sometime whereas Amazon Redshift is newer.

*

*What is the DBA effort between Infobright and Amazon Redshift?

*How accessible is Infobright (API, query interface, etc.) vs AWS?

*Where do both sit in your system architecture? Do the operate as a layer on top of your traditional RDBMS?

*What is the DevOps effort to setting up both Infobright and Redshift?

I'm leaning a bit more towards Redshift because my application is hosted on AWS and I thought this would create tangible benefits in the long-run since everything is in AWS. Thank you in advance!

A: Firstly, I'll admit that I work for Infobright.  I've done significant research into Redshift, and I feel I can give an honest opinion.  I just wrote up a comparison between the two technologies; it can be found here: https://www.infobright.com/wp-content/plugins/download-monitor/download.php?id=37

*

*DBA Effort - Infobright requires very little administration.  You cannot index; you don't need to partition/etc.  It's an SMP architecture and scales well.  Thus, you won't be dealing with multiple nodes.  Redshift is also fairly simple.  You will need to maintain sorts as well as ensure Analyse is run enough.

*Infobright uses a MySQL Shell. Thus, any tool that can utilize MySQL can utilize Infobright.  Therefore, you have the same set of tools/interfaces/APIs for Infobright as you do with MySQL.  AWS does have an SQL interface, and it does have some API capabilities.  It does require that you load directly from S3.  Infobright loads from flat files and named pipes from local or remote servers.

*Both databases are analytic databases.  You would not want to use either as a transactional database.  Instead, you typically push data from your transactional system to your analytic database.

*DevOps to setup Infobright will be lower than Redshift.  However, Redshift is not that overly complicated either.  Maintenance of the environment is more of a requirement for Redshift, though.
Infobright does have many AWS-specific installations.  In fact, we have implementations that approach nearly 100TB of raw storage on one server.  That said, Redshift with many nodes can achieve petabyte scale on an implementation.
There are other factors that can impact your choice.  For example, Redshift has very nice failover/HA options already built-in.  On the flipside, Infobright can support many concurrent queries and users; Redshift limits queries to 15 regardless of cluster size.
Take a look at the document, and feel free to contact me if you have any specific questions about either technology.


text:
Q: How to mount a windows administrative share on linux via SMB I'm currently trying to mount a windows shared drive under linux.
The machine is using windows 7 and by default it shares all windows drives if you login as an administrator. I've been able to login and list/copy/delete files via my android phone but I'm having a problem with mounting it on a server.
The command I'm trying:
mount -t smbfs -o username=MyUsername //10.0.0.2/$D /mnt/machine_1_d
I think the problem comes from the $ sign in $D. I just can't remember what was the fix for this. I'm sure it was something really simple but I can't find it on the net also.

A: tftd,
try escaping the $ character with a \
mount -t smbfs -o username=MyUsername //10.0.0.2/D\$ /mnt/machine_1_d

dc

A: Administrative shares in Windows are named with the volume letter first, then the '$' symbol, not the other way around.
C: --> C$
D: --> D$
sudo mount -t smbfs -o username=graeme,domain=example //server.example.com/C$ /mnt/bla

A: My issue was related to:
"mount error(13): Permission denied Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)"
For me the solution was adding key to regedit in Window. Below is my answer in other topic:
https://serverfault.com/a/619963/237340

A: I would add a line for that purpose to /etc/fstab file:
//10.0.0.2/d$/ /mnt/documents cifs noserverino,rw,iocharset=utf8,password=xxxxxxxxxx,username=user_with_administrative_rights,domain=my_windows_domain 0 0

After saving changes to this file, mount the file system by means of the command mount -a.
In this case the option rw allows the directory to be read-write, otherwise it should have the option ro.


text:
Q: Trouble understanding Java threads I learned about multiprocessing from Python and I'm having a bit of trouble understanding Java's approach.  In Python, I can say I want a pool of 4 processes and then send a bunch of work to my program and it'll work on 4 items at a time.  I realized, with Java, I need to use threads to achieve this same task and it seems to be working really really well so far.
But.. unlike in Python, my cpu(s) aren't getting 100% utilization (they are about 70-80%) and I suspect it's the way I'm creating threads (code is the same between Python/Java and processes are independent). In Java, I'm not sure how to create one thread so I create a thread for every item in a list I want to process, like this:
    for (int i = 0; i < 500; i++) {
        Runnable task = new MyRunnable(10000000L + i);
        Thread worker = new Thread(task);
        // We can set the name of the thread
        worker.setName(String.valueOf(i));
        // Start the thread, never call method run() direct
        worker.start();
        // Remember the thread for later usage
        threads.add(worker);
    }

I took it from here. My question is this the correct way to launch threads or is there a way to have Java itself manage the number of threads so it's optimal? I want my code to run as fast as possible and I'm trying to understand how to tell and resolve any issues that maybe arising from too many threads being created.
This is not a major issue, just curious to how it works under the Java hood.

A: You use an Executor, the implementation of which handles a pool of threads, decides how many, and so forth. See the Java tutorial for lots of examples.
In general, bare threads aren't used in Java except for very simple things. Instead, there will be some higher-level API that receives your Runnable or Task and knows what to do.

A: Take a look at the Java Executor API. See this article, for example.
Although creating Threads is much 'cheaper' than it used to be, creating large numbers of threads (one per runnable as in your example) isn't the way to go - there's still an overhead in creating them, and you'll end up with too much context switching.
The Executor API allows you to create various types of thread pool for executing Runnable tasks, so you can reuse threads, flexibly manage the number that are created, and avoid the overhead of thread-per-runnable.
The Java threading model and the Python threading model (not multiprocessing) are really quite similar, incidentally. There isn't a Global Interpreter Lock as in Python, so there's usually less need to fork off multiple processes.

A: Thread is a "low level" API.
Depending on what you want to do, and the version of java you use, their is better solution.
If you use Java 7, and if your task allow it, you can use the fork/join framework : http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
However, take a look at the java concurrency tutorial : http://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html


text:
Q: I am trying to save the values form the DataGridPro MUI, a TreeData ... How can i save Values of the Cells after i edit them I am novice at this. I am trying to save the values form the DataGridPro MUI,  I am using a TreeData. How can i save Values of the Cells after i edit them. I watched a video online in by which i was able to understand how it will work on a Single DataTable, But for the Parent one, i dont know how i will be able to save it. I have looked up but i found no method which could be helpful. I am getting the values from the GridColumn and GridRowsProp.
Basically i want to save the values of the children. how can i save them?
Thanks.
import * as React from "react";
    import { DataGridPro, GridColumns, GridRowsProp, DataGridProProps } from "@mui/x-data-grid-
    pro";
    import {
    GridCellEditCommitParams,
    GridCellEditStopParams,
    GridCellEditStopReasons,
      GridRowModel,
  MuiEvent,
} from "@mui/x-data-grid";
import { applyInitialState } from "@mui/x-data-grid/hooks/features/columns/gridColumnsUtils";

const rows: GridRowsProp = [
  {
    hierarchy: ["Documents"],
    rubrics: "Head of Human Resources",
    totalMarks: "",
    id: 0,
  },
  {
    hierarchy: ["Scope"],
    rubrics: "Head of Sales",
    totalMarks: "15",
    id: 1,
  },
  {
    hierarchy: ["Scope", "Rubric item 1"],
    rubrics: "Sales Person",
    totalMarks: "2",
    id: 2,
  },
  {
    hierarchy: ["Scope", "Rubric item 2"],
    rubrics: "Sales Person",
    totalMarks: "5",
    id: 3,
  },
  {
    hierarchy: ["Scope", "Rubric item 3"],
    rubrics: "Sales Person",
    totalMarks: "8",
    id: 4,
  },
];

const columns: GridColumns = [
  { field: "rubrics", headerName: "Rubric Type", width: 200, editable: true },
  {
    field: "totalMarks",
    headerName: "Total Marks",

    width: 150,
    editable: true,
  },
];

const getTreeDataPath: DataGridProProps["getTreeDataPath"] = (row) => row.hierarchy;

export default function TreeDataSimple() {
  const [state, setState] = React.useState<GridRowModel[]>(applyInitialState); //i was seeing online for this how can i add the array here but no luck.
  const handleCommit = (e: GridCellEditCommitParams) => {
    const array = state.map((r) => {
      if (r.id === e.id) {
        return { ...r, [e.field]: e.value };
      } else {
        return { ...r };
      }
    });
    setState(array);
  };
  return (
    <div style={{ height: 400, width: "100%" }}>
      <DataGridPro
        treeData
        rows={rows}
        columns={columns}
        getTreeDataPath={getTreeDataPath}
        onCellEditCommit={handleCommit}
        experimentalFeatures={{ newEditingApi: true }}
        onCellEditStop={(params: GridCellEditStopParams, event: MuiEvent) => {
          if (params.reason === GridCellEditStopReasons.cellFocusOut) {
            event.defaultMuiPrevented = true;
          }
        }}
      />
    </div>
  );
}}


text:
Q: Select and insert by keeping references to original data in OrientDB I am exploring graphDB query languages. At the moment looking at OrientDB query language. I would like to see how a transaction would look like in OrientDB with the following structure:
Suppose, I have two vertices, A and QA:
CREATE CLASS A EXTENDS V

CREATE CLASS QA EXTENDS V

Class A has a property called p1 of Integer:
CREATE PROPERTY A.p1 integer

Assume that A has three records  called a1,a2,a3 with their corresponding values for p1 are a1.p1=2; a2.p1=5; a3.p1=10;:
INSERT INTO A SET p1 = 2            // call this a1
     Created record with RID #11:1
INSERT INTO A SET p1 = 5            // call this a2
      Created record with RID #11:2
INSERT INTO A SET p1 = 10           // call this a3
      Created record with RID #11:3

And assume that I have an edge called isA from QA to A.
CREATE CLASS isA EXTENDS E    // it seems that I can not restrict isA records to connect only QA records to A

I would like to see how the following transaction would look like in OrientDB:
first: select all A's content where p1 < 6 => so I will get {a1,a2}
second: for each element in the first query create an element in QA => so I will get for example {qa1,qa2}
third: Add records to isA Edge such that they connect elements in QA to their corresponding elements in A; =>so, for example connect qa1 to a1 and qa2 to a2.
It seems all three queries are inter-related.
My 1th Question: how the above transaction (i.e., set of inter-related queries)  would look like in OrientDB?
Note that elements of A are dynamic (not fixed during my system) and I would like to synch QA elements with A, whenever A's content changes by employing the above transaction; for example, if I add a4 to A with p1=3, and run the above set of queries, I am expecting to get a new record in QA, say qa4 which is linked to a4.


text:
Q: variable string = value (string) but the result is false Please Help,
whay the result if(Title.toString().trim() == "camera") is false?
my code:
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                //Get item at position
                GridMenuItem item = (GridMenuItem) parent.getItemAtPosition(position);
                String Title =item.getTitle();
                if(Title.toString().trim() == "camera"){

                    String strPhoneNumber;
                    Bundle b = getIntent().getExtras();
                    strPhoneNumber = b.getString("phonenumber");

                    Intent myIntent = new Intent(v.getContext(), UploadActivity.class);
                    Bundle bs = new Bundle();
                    bs.putString("phonenumber", strPhoneNumber); //Your id
                    myIntent.putExtras(b); //Put your id to your next Intent
                    startActivityForResult(myIntent, 0);
                    finish();
                }
                if(Title.toString() =="history"){
                    Intent myIntent = new Intent(v.getContext(), HistoryActivity.class);
                    startActivityForResult(myIntent, 0);
                }
                if(Title.toString() =="setting"){
                    Intent myIntent = new Intent(v.getContext(), HistoryActivity.class);
                    startActivityForResult(myIntent, 0);
                }

            }
        });

debug

A: Change the code like this:
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                //Get item at position
                GridMenuItem item = (GridMenuItem) parent.getItemAtPosition(position);
                String Title =item.getTitle().toString().trim();
                Log.d("testString",Title);
                if(Title.equals("camera")){

                    String strPhoneNumber;
                    Bundle b = getIntent().getExtras();
                    strPhoneNumber = b.getString("phonenumber");

                    Intent myIntent = new Intent(v.getContext(), UploadActivity.class);
                    Bundle bs = new Bundle();
                    bs.putString("phonenumber", strPhoneNumber); //Your id
                    myIntent.putExtras(b); //Put your id to your next Intent
                    startActivityForResult(myIntent, 0);
                    finish();
                }
                if(Title.equals("history")){
                    Intent myIntent = new Intent(v.getContext(), HistoryActivity.class);
                    startActivityForResult(myIntent, 0);
                }
                if(Title.equals("setting")){
                    Intent myIntent = new Intent(v.getContext(), HistoryActivity.class);
                    startActivityForResult(myIntent, 0);
                }

            }
        });

Please post the value of log "testString" in the comment below.
Look if it shows "Camera" instead of "camera" then change the if statement accordingly.

A: Try this
Title.equals ("camera")

Since title is a string there is no need for using toString and trim

A: if(Title.toString().equal("camera"))
Because in java, String is an Object Type(Reference) so you must use equal instead of ==.
"==" operator is using for primitive types only (like int, long ...)


text:
Q: Math text scaling in LaTeX I was wondering if anyone knew of a package or command I could use to prevent TeX from scaling  values in an equation. An example of this would be if you have a fraction in a fraction, the text ends up getting fairly small and hard to read. Is there a way to stop this from happening?
Example:
\frac{5}{\frac{1}{2}}

the 1/2 in the denominator will be pretty small and  hard to read.

A: You can use \dfrac or \tfrac to force the size you want.
LaTeX questions will get better answers on https://tex.stackexchange.com/

A: You can use the \cfrac command for the _c_ontinued fraction.


text:
Q: jQuery validations are not working on IE10 Here I am using validation on form. It works on Chrome, Firefox but gives the problem in IE10. Some of the validations are not working like email, telephone. And this problem is on all the html pages.
$('#contact').validate({
    onfocusout: function (element) {
        $(element).valid();
    },
    rules:{
        prenume:{
            required:true,
        },
        nume:{
            required:true,
        },
        email:{
            required:true,
            email:true
        },
        password_new:{
            required:true,
        },
        telefon:{
            required:true,
        },
        address:{
            required:true,

        },
        password_repeat:{
            required:true,
        }
    },

    messages:{
        prenume:{
            required:'
Acest câmp este obligatoriu.
',
        },
        nume:{
            required:'',
        },
        email:{
            required:'
Acest câmp este obligatoriu.
',
            email:'
Adresâ de e-mail incorectâ.
',
        },
        password_new:{
            required:'
Acest câmp este obligatoriu.
',
        },
        telefon:{
            required:'
Acest câmp este obligatoriu.
',
        },
        password_repeat:{
            required:'',
        }
    }
});

A: IE is syntax strict browser, please care about extra comma(,)
password_repeat:{
  required: '',
}

To
password_repeat:{
  required: ''
}

A: @Girish solution would solve the problem and for compatibility mode in IE10 to IE8 = it returns an empty string even if ah attribute doesn't exist. So
 $(event.target).attr("formnovalidate") !== undefined

is always true and the validation is skipped forked the jQuery validation plugin and fixed it,
here is the fix


text:
Q: I'm trying to join a set object in a method and using async fetch hook for fetching the data on server-side and its showing me an error in Nuxt I'm trying to fetch data from API on Server Side using async fetch() but now in the method, I'm trying to join a set object, that I'm calling it in the template and it isn't working.
Always giving me an error that required function is not a function.
Any idea on how to fix that?

A: I figured out the problem. The thing was that I wasn't using the right way to join a set. I was using
setObj.join("; ")

and this was working fine on the client-side.
But I think because of the different render engine on the server-side. It wasn't resolving.
Solved it using
[...setObj].join("; ")

This was a JavaScript mistake rather than Nuxt.
I'm new to this thing. Correct me if I'm wrong somewhere.


text:
Q: `firebase deploy` with CLI tools 3.17.0 gives "Error: Firebase config variables are not available" Full error dump:
Error: Error occurred while parsing your function triggers. Please ensure you have the latest firebase-functions SDK by running "npm i --save firebase-functions@latest" inside your functions folder.

Error: Firebase config variables are not available. Please use the latest version of the Firebase CLI to deploy this function.
    at init (/Users/dougstevenson/work/google/firebase/functions/tmp/functions/node_modules/firebase-functions/lib/config.js:51:15)
    at Object.config (/Users/dougstevenson/work/google/firebase/functions/tmp/functions/node_modules/firebase-functions/lib/config.js:29:9)
    at Object.ref (/Users/dougstevenson/work/google/firebase/functions/tmp/functions/node_modules/firebase-functions/lib/providers/database.js:75:33)
    at Object.<anonymous> (/Users/dougstevenson/work/google/firebase/functions/tmp/functions/lib/index.js:9:32)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Module.require (module.js:604:17)

A: With firebase-tools (the Firebase CLI) version 3.17.0, it's required to use the latest firebase-functions (version 0.8.1) and firebase-admin (version 5.8.1) SDKs.  Update them by running this command from the functions folder:
npm install firebase-functions@latest firebase-admin@latest

After this, a deploy should succeed.
EDIT: This bug was fixed in CLI version 3.17.1.  A similar bug appears also when running the emulator with the CLI, and that was fixed in 3.17.3.

A: To fix this I needed to run from the root path of your firebase functions folder:
npm update -g firebase-functions;

run it again..
npm update -g firebase-functions;

Then update the node_modules within your functions directory per above advice
cd functions;
npm install firebase-functions@latest firebase-admin@latest;

Note: Interestingly NPM complained the install of both packages was invalid, even after running install again. However executing a firebase deploy --only functions worked perfectly.
Incidentally, my simple deploy shortcut script may come in handy for those who don't like working in one big index.js file:
#!/bin/bash

(cd functions/; cat header.js get*.js process*.js set* > index.js; );

firebase deploy --only functions

say "fire base deploy done";


text:
Q: Images in kiwi logo slider(wordpress plugin) are tiny in safari The problem page
How it should be

So this is an interesting issue. On every browser except safari, The images display normally. However, in safari, they are super tiny.
.bx-wrapper ul.kiwi-logo-carousel.align-center li img {
    max-height: 60%;
    max-width: 76%;
    display: inline-block;
}

The only things that my research on this issue has turned up were ineffective in solving the issue:
First attempt
Second Attempt

A: Solved it by targeting Safari only in CSS.
@media screen and (-webkit-min-device-pixel-ratio:0) {

    /* Safari only override */
    ::i-block-chrome, .bx-wrapper ul.kiwi-logo-carousel.align-center li img {
        max-height: none;
        max-width: none;
   }
}


text:
Q: Область видимости переменной, внутри функции Не понимаю, почему не видит переменную $a, если я указал, что она глобальная, значит должна взяться из области видимости функции inFoo?
Как тогда к ней обратиться?
function inFoo() {
    $a = 5;

    function foo() {
        global $a;
        return $a;
    }
    return foo();

}

echo '<pre>';
print_r(inFoo());
echo '</pre>';

A: Использовать замыкание надо и use:
function inFoo() {
    $a = 5;

    $inner = function() use ($a) {
        return $a;
    };

    return $inner();
}

http://php.net/manual/ru/functions.anonymous.php


text:
Q: Get data from mysql db by slug url not id Im facing problem in getting data from mysql db by slug url. When i get data from id it works fine. I substituted urlslug also but no use.
Im trying to change my site article url(s)
mysite.com/public.php?id=12    to    mysite.com/public/google-search

My table:
+----+---------------+---------+------------------------------------+
| id | title         | article |   urlslug  VARCHAR 500 NULL        |
+----+---------------+---------+------------------------------------+
| 12 | google search | xxxxxxx |   google-search                    |
| 13 | bing yahoo    | xxxxxxx |   bing-yahoo                       |
| 14 | friendly seo  | xxxxxxx |   friendly-seo                     |
+-------------------------------------------------------------------+

code to get data by id:
$id = $_GET['id'];
$id = mysqli_real_escape_string($conn,$id);
$query = "SELECT * FROM `table` WHERE `id`='" . $id . "'";
$result = mysqli_query($conn,$query);

while($row = mysqli_fetch_array($result)) {
echo ($row['title']);
echo ($row['article']);    }

Please help. Thanks.

A: Alright, Here you go
When a user goes here....
mysite.com/public/google-search

This rewrite code will change the server side to this
mysite.com/public.php?id=12

By adding this to your .htaccess file
RewriteRule ^public/google-search mysite.com/public.php?id=12 [NC]

You would need to do this for all files that you want to mask.

A: You should make your route function, this links may help you:
http://blogs.shephertz.com/2014/05/21/how-to-implement-url-routing-in-php/
PHP Application URL Routing


text:
Q: How to allow two ember-cli services to cross communicate? Using ember-cli version 0.0.42
Run these commands
ember new myApp
cd myApp
ember generate service serviceOne
ember generate service serviceTwo
ember generate controller application

Make these updates
controllers/application.js
import Ember from 'ember';

export default Ember.Controller.extend({
    init: function() {
        var a = this.get('serviceOneService.testFunction');
    }
});

initializers/service-one-service.js
export default {
    name: 'service-one-service',
    initialize: function(container, app) {
        app.inject('route', 'serviceOneService', 'service:service-one');
        app.inject('controller', 'serviceOneService', 'service:service-one');
    }
};

services/service-one.js
import Ember from 'ember';

export default Ember.Object.extend({
    testFunction: function(){
        //How would I make a call to serviceTwo.testFunction here instead of returning 123
        return "123"
    }
});

services/service-two.js
import Ember from 'ember';

export default Ember.Object.extend({
    testFunction: function(){
        return "Test function from service 2"
    }
});

My question is how to I inject serviceOne into service two and serviceTwo into service one. One I do that how do I access service two from service one.  Inside when calling I have an idea of how to injest the service directly into all controllers but when I try and inject into another object (service) inside of testFunction "this" refers to the window and not an ember object.
My first thought was to just inject each service into the overal service namespace but I get this message:
Uncaught Error: Cannot inject a `service:service-one` on other service(s). Register the `service:service-one` as a different type and perform the typeInjection.

A: You can inject one service into the other by defining an initializer and setting setting the after property to something like after: ['service-one', 'service-two'], which would cause it to run after both of those services have been registered.
The initializer would look something like...
Ember.Application.initializer({
  after: ['service one', 'service two'],
  name: 'service injections',
  initialize: function(container, application){
    application.inject('service:service-one', 'serviceTwoService', 'service:service-two');
  }
});

Unfortunately if you then try to inject service:service-one into service:service-two you'll get an error stating Maximum call stack size exceeded which happens because the container ends up in a loop while trying lookup all the needed injections.
You can see a working bin here: http://emberjs.jsbin.com/fitaka/1/edit


text:
Q: When the validation fails at the bottom, why the browser shows at the top of the page? I have just implemented a RequiredFieldValidatior with ValidationSummary by setting a ValidationGroup.
It works fine, when I click the relevant button!
But the viewport changes and shifts at the top of the page and my validaiton result and the button etc stays at the very bottom of the page which is not nice.
Is there a way to prevent this and let the browser still be shopwing the same area after button click?
Additional Note: The validation fails on the client-side; so no post-back occurs. Basically, validation fails, and the viewport slides at the top of the page.

A: You can achieve this by adding the following directive to the top of your page:
<%@ Page MaintainScrollPositionOnPostback="true" %>

A: In your RequiredFieldValidator there is an option to SetFocusOnError which will then move the cursor to the Textbox/input type.
Then in your Page declaration at the top of the page, add in MaintainScrollPositionOnPostback="true"
<%@ Page MaintainScrollPositionOnPostback="true" %>

A: I have done this before to set focus on the fist element that didn't validate when calling validation manually:
//has to be called after Page_ClientValidate()
function ValidatorFocus()
{
    var i;
    for (i = 0; i < Page_Validators.length; i++)
    {
        if (!Page_Validators[i].isvalid)
        {
            document.getElementById(Page_Validators[i].controltovalidate).focus();
            break;
        }
    }
}


text:
Q: Constructing non-isomorphic groups such that the counts of elements of given order match In one of the simplest ways of proving that two groups aren't isomorphic, we can compare the orders of each element of both groups. If we find an order $\ell$ such that one of the groups has more elements of this order than the other group, we're done.
I am interested in finite groups where this fails --- ones that aren't isomorphic, but the counts for each order are the same:
$$\DeclareMathOperator\ord{ord} G \not\cong H \quad \land \quad \forall\ell.\ |\{g \in G \mid \ord g = \ell\}| = |\{h \in H \mid \ord h = \ell\}|$$
With some SageMath code, I have computed that the smallest groups where this happens are of order 16. However, I am more interested in how one could methodically find such a counterexample, apart from just trying out groups you can think of until something sticks. How would you find such a pair of groups without a computer?

A: Here is one family of such groups.
The nonabelian group of order $p^3$ and exponent $p$ can be realized as the multiplicative group of $3\times 3$ unipotent matrices with coefficients in $\mathbb{Z}/p\mathbb{Z}$, i.e., matrices of the form
$$\left(\begin{array}{ccc}
1 & a & c\\
0 &1 & b\\
0 & 0 & 1
\end{array}\right),\qquad a,b,c\in \mathbb{Z}/p\mathbb{Z}.$$
In this group, every nontrivial element has order $p$, and so you get the same count as you do for the abelian (an dhence non-isomorphic) group $(\mathbb{Z}/p\mathbb{Z})^3$.
You can also construct further examples, known as extra-special $p$-groups (of exponent $p$), by taking central products of copies of the group above. Let us denote the group above by $\mathbf{E}_3$ ($E$ for "extra-special"; it's a technical term). Note that the center is cyclic of order $3$, given by the matrices with $a=b=0$. Now, we construct $\mathbf{E}_5$ by taking $\mathbf{E}_3\times\mathbf{E}_3/N$, where $N$ is group of elements of the form $(z,z^{-1})$ with $z\in Z(\mathbf{E}_3)$ (this "identifies" the centers of each copy of $\mathbf{E}_3$). This is again a nonabelian group of exponent $p$, with center of order $p$, of order $p^5$.
Assuming we have defined $\mathbf{E}_{2n+1}$, nonabelian group of order $p^{2n+1}$, exponent $p$, and center of order $p$, we construct $\mathbf{E}_{2n+3}$ by identifying generators $w$ and $z$ of $Z(\mathbf{E}_{2n+1})$ and $Z(\mathbb{E}_3)$, and constructing $\mathbf{E}_{2n+1}\times\mathbf{E}_3/N$, where $N$ consists of the elements of the form $(w^k,z^{-k})$. This will be a nonabelian group of order $p^{2n+3}$, exponent $p$, with center of order $p$.
Then $\mathbf{E}_{2k+1}$ and $(\mathbb{Z}/p\mathbb{Z})^{2k+1}$ will have the desired property, for all $k\geq 1$.

Now, say you have (finite) groups $G$ and $H$ as desired (nonisomorphic, but for each $k$ the number of elements of order $k$ in $G$ and $H$ are the same). Let $K$ be any finite group. I claim that $G\times K$ and $H\times K$ also satisfy the desired properties. That they are not isomorphic is not trivial, but nonetheless it is true (e.g., it follows from the Remak-Krull-Schmidt Theorem). Now I claim that for every $r$, the number of elements of order $r$ in $G\times K$ and in $H\times K$ is the same.
An element $(g,k)\in G\times K$ has order $r$ if and only if (i) the order of $g$ divides $r$; (ii) the order of $k$ divides $r$; and (iii) at least one of the orders of $g$ and $k$ is exactly equal to $r$. Thus, letting $G(d)$ be the set of elements of $G$ of order exactly $d$, and similarly for $H(d)$ and $K(d)$, we have that
$$(G\times K)(r) = \left(\sum_{d|r}|G(d)||K(r)|\right) + \left(\sum_{d|r}|G(r)||K(d)|\right) - |G(d)||K(d)|.$$
Similarly,
$$(H\times K)(r) = \left(\sum_{d|r}|H(d)||K(r)|\right) + \left(\sum_{d|r}|H(r)||K(d)|\right) - |H(d)||K(d)|.$$
Since $|G(m)|=|H(m)|$ for all $m$ by assumption, it follows that $|(G\times K)(r)|=|(H\times K)(r)|$.

An interesting question might be to determine all $n$ for which there exist two non-isomorphic groups $G$ and $H$ of order $n$ for which the count of elements of order $k$ is equal for all $k$. From the above, we see that if $n$ divisible by the cube of an odd prime, or by $16$, then such groups exist. We also know that if $n$ is cubefree and a nilpotent number, then every group of order $n$ is abelian, so no such examples exist. This reduces the problem to $n$ that is cubefree but not a nilpotent number, and to numbers of the form $2^km$ where $m$ is odd and cubefree, $k=3$. I expect counterexamples exist in that case as well.


text:
Q: PHP function problem I have a php function script that is supposed to uncheck a checkbox or checkboxes if a user unchecks it when the preview button is clicked but I can only get the last
checkbox that was unchecked to stay unchecked but not the other checkeboxes how can I fix this so that all the checkboxes that where unchecked stay unchecked?
Here is part of my PHP function that is giving me the problem.
if(isset($_POST['preview'])){
    foreach($query_cat_id as $qci) {
        if(!in_array($qci, $cat_id)){
            $unchecked = $purifier->purify(strip_tags($qci));
        }
    }
}

for ($x = 0; $x < count($query_cat_id); $x++){
    if(($query_cat_id[$x] == $cat['id']) && ($cat['id'] != $delete_id) && ($cat['id'] != $unchecked)){
        echo 'checked="checked"';
    }
}

A: Why not just just check if the variable is set, if the checkbox is checked when the form is submitted, it will be available in $_POST['checkboxName'], otherwise, isset($_POST['checkboxName']) will return false.
Basic script to test it
<?php
if (isset($_POST['heh']))
    echo $_POST['heh'];
else
    echo "Not checked";
?>
<form action='yourPage.php' method='post'>
<input type='checkbox' name='heh' />
<input type='submit' />
</form>

View it in action
http://robertsquared.com/so.php

A: i solve this problem on client side
i have a input of type hidden with the same name as the checkbox with the value of 0 and the checkbox right after the hidden field with the value of 1
if the checkbox is not checked i get the value of 0 from the hidden field and if someone checks i got the 1 from the checkbox.
so i only need to check if $value==1 then checked=checked


text:
Q: validate session in java ee project I need to make a controller which first validates the session, and if it's not valid, it sends me back to login page. If it's valid I need to stay on the current page; I always get too many redirects; Is there a way to redirect from a void method? This is the method from the controller:
public String onLoad(HttpSession session){
    AngajatiBean ab=(AngajatiBean) session.getAttribute("myAng");
    session.setAttribute("forms",pas.getForms(ab));
    if(ab!=null)
        return "redirect:hello.htm";
    else
        return "redirect:here.htm";

}

A:
Is there a way to redirect from a void method?

Actually, you can implement Filter's method doFilter in order to redirect users to login page when session expires.
public class RedirectFilter implements Filter{

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        req.getSession().setAttribute("forms",pas.getForms(ab));
        if(req.getSession().getAttribute("myAng")==null){
            req.getRequestDispatcher("/here.htm").forward(request, response);
        }else{
        chain.doFilter(request, response);
        }
    }
    public void destroy() {}
}

Then add this to your web.xml to configure your filter
<filter>
        <filter-name>FilterExample</filter-name>
        <filter-class>com.stackoverflow.answer.RedirectFilter</filter-class>
</filter>
<filter-mapping>
       <filter-name>FilterExample</filter-name>
       <url-pattern>/here.htm</url-pattern>
</filter-mapping>


text:
Q: Javascript Validation - Letters and Space Good day. I'm very new to Javascript. I have this expression: var firstname = /^[A-Za-z]+$/; to validate first name in a form. However, this code only allows the user to input a single name without any space. How about if the user has two or more given first name?
I would like to know how to validate letters and space. I have searched similar questions here in Stackoverflow, but none of the answers worked for me.
I have tried these codes which I have found here: /^[A-Za-z ]$/ or this one /^[a-zA-Z\s]*$/ but these didn't work. Still, whenever I input two names in the First Name field, my alert message prompts me that I have entered an invalid character.
Thanks.

A: There is a problem with each one that you posted for what you want:

*

*var firstname = /^[A-Za-z]+$/; should be var firstname = /^[A-Za-z ]+$/; (added space)

*/^[A-Za-z ]$/ should be /^[A-Za-z ]+$/ (added +)

*/^[a-zA-Z\s]*$/ is a problem because I assume from the other examples that you want at least one letter, so it should be /^[a-zA-Z\s]+$/ (*replaced * with +)


text:
Q: How do you turn back on the menu-bar permanently having installed the emacs-starter-kit? I'm just trying to pick up emacs after 20 or so years away as it appears to be the best way to use Clojure and Overtone. Having installed the emacs-starter-kit I have lost the menubar which was proving very useful to reorient myself with the emacs commands. From searching I can see that C-x F10 restores it for a session, how do I turn it back on by default?

A: Hopefully, emacs-starter-kit would not be so unwise as to make it difficult to turn menus back on.
Try putting this in your init file (~/.emacs), after whatever you have that loads the starter-kit:
 (menu-bar-mode 1)


text:
Q: How is p[a:b:c] handled by python? I am trying these in the python shell and am getting quite confusing results.
>>> p = [1, 2, 3, 4, 5, 6, 7, 8]
>>> p
[1, 2, 3, 4, 5, 6, 7, 8]
>>> p[2:8:2]
[3, 5, 7]
>>> id(p[2:8:2])
37798416
>>> id(p[2:8:2])
37798416
>>> id(p[2:8:2])
50868392

Note how the id changed the 3rd time !
>>> id(p[2:8:2])
37798336

And changed again !
Question#1: How and why did that happen ?
Question#2:
>>> p[2:8:2] = [33,55,77]
>>> p
[1, 2, 33, 4, 55, 6, 77, 8]

How does python exactly "store" p[2:8:2] ? (may be "store" is not the right word, but I hope you get the idea). It does not look like it is a distinct list from the original list (though it is made up of non-sequential immutable items from the original list), as changes to this list are reflected in the original list !

A: Slicing, with rare exception, makes brand new copies of whatever you're slicing. So all the id checks are telling you is that sometimes the new list reuses the memory from last time, and sometimes it uses a different bit of memory. The exact behavior is pure implementation detail. In CPython (the reference interpreter) id happens to correspond to memory addresses, so all you're seeing is a behavioral artifact of the allocator, not some deep meaning to slicing.
On your question #2: When use in an assignment context, slicing modifies the original sequence, it doesn't create a new list at all. Don't try to draw meaningful parallels between slicing (read oriented, makes new sequences) and slice assignment (write oriented, modifies existing sequences); the behaviors under the hood are different in almost every way.

A: For question 1:
The id of an object is guaranteed to both be unique and stay constant during the lifetime of that object. See here in the Python library docs:

id(object) - return the identity of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

Since you're creating and destroying objects with your slicing, the id is actually following the rules.
If you're using the reference (and I suspect most common) implementation, CPython, it simply gives you the memory address of the object. The source code can be found in Python/bltinmodule.c, simplified and annotated below:
static PyObject *builtin_id(PyModuleDef *self, PyObject *v) {
    PyObject *id = PyLong_FromVoidPtr(v); // Turn object address into
    return id;                            //    long and return it.
}

That ensures that it's unique and the vagaries and order of memory allocation calls also explain why it can repeat and/or be different.

For question 2:
Assigning to the "slice" does not actually involve creating the sliced object and assigning to it. It simply sets certain values in the already existing object as specified by the slice notation to those given on the right hand side of the assignment.
More detail can be found in the sliceobject files in the CPython source code, specifically Objects/sliceobject.c and Include/sliceobject.h. These involve the creation of a PySliceObject which consists of a {start, stop, step} tuple.
When you apply this tuple to an object on the right hand side of an assignment, such as x = y[2:8:2], it uses the PySliceObject to create a new list x based on y, getting only the relevant elements.
When used on the left hand side, such as x[2:8:2] = [33,55,77], it uses the PySliceObject to decide which elements of x are set to the values on the right.


text:
Q: SimpleDateFormat throws ParseException in AndroidStudio before compiling I'm making an app, that is storing some dates in a SQLite db on an android device.
Currently, most of it works as intended, except for parsing the text string that i store the date as.
    private final String ALARMS_COLUMN_TIME = "time";

    Calendar cal = Calendar.getInstance();
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      String dateString = cursor.getString(cursor.getColumnIndex(ALARMS_COLUMN_TIME));
      cal.setTime(dateFormat.parse(dateString));

The problem is that, even before compiling, it gives me a, seemingly syntax error, with the "unhandled exception java.text.ParseException".
the imports i'm using in that class are these:
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;

I have tried with various Locales as well, as part of the SimpleDateFormat constructor, but it haven't made any difference.
What can be the cause of this unhandled exception, prior to compiling?
Thanks in advance,
Ronnie

A: It's not that a ParseException is being thrown - the problem is that the compiler is complaining because you're calling parse which can throw a ParseException, and you're not handling it.
ParseException is a checked exception, which means that if you call a method that is declared to throw it, then you either need to catch it yourself, or you need to declare that your method might throw it. (We can't tell from your code which of those you want to do. You might want to catch it and rethrown an unchecked exception, for example.)


text:
Q: Directshow continious capture I have Mp4 Capture Application in direct show. In my application i need to capture 30 min(or say some dynamic value) video continuously
for the I made one WaitableTimer Routine , after 30 minutes i want to stop the capture and then start again ... but after i stop capture on next sample in start capture the stream not get added to the file.  to start next capture , i have to release all the capture variables again get devices and build graph and then i can start capture.
Cant i simply stop capture , then rename the output file and again start capture?? is anything needed to add additional to do that??
Please help me on this.
Thanks
Edit :
Below is the graph i use for recording
Video Source --> x264vfw - H.264/MPEG-4 AVC Codec --------->GDCL MPEG-4 Multiplexer --> File Writer
                                                        |
Audio Source --> ACM Wrapper --> Monogram AAC Encoder --|

A: We do something similar to capture DV-Avi's. Have you tried to:

*

*stop the graph

*remove File-Writer

*create new File-Writer (and configure)

*connect File-Writer to mux

*and start again

If this does not work then there is something wrong with the Muxer or one of the other filters. You can easily test this, just replace the Muxer with an audio and video-renderer and try to play, stop, play.
You can also just try another MP4 mux filter, like the monogram mp4 mux.


text:
Q: Jenkins replay feature I would like to use Replay feature. The documentation said:
1) Can be called multiple times on the same run
2) Can also be called on Pipeline runs that are still in-progress
What is the difference with these two points? Could you explain me better?

A: 1) Each 'Build' (or 'Run') has some configuration (like parameters of the build for 'Build with parameters') that sometime you want to reuse in Replay. You can launch multiple Replay on the same 'Build'. Each of the Replayed Build will get the same parameters as the original one.
2) You are able to launch Replay also on the 'Build' that is still in-progress. It is irrelevant for Replayed 'Build' because once launched, the original 'Build' already updated its object in Jenkins master with all that will be of use for Replay.


text:
Q: I can not export the image to the drive in Google Earth Engine (GEE) Whenever I try to export to the drive the image gives me the following error:
Error: Invalid argument: 'image' must be of type Image.

This is my code:
var mod11 = ee.ImageCollection("MODIS/MOD11A2");

// Specify name of country.
var country_names = ['Vietnam'];
// get fusion table with countries
var countries = ee.FeatureCollection('ft:1tdSwUL7MVpOauSgRzqVTOwdfy17KDbw-1d9omPw');
// select the country from the fusion table
var vietnamCountry = countries.filter(ee.Filter.inList('Country', country_names)).geometry();

// set start date
var startdate = ee.Date.fromYMD(2000,1,1);
// set end date
var enddate = ee.Date.fromYMD(2017,12,31);

// filter the data collection
var temp =  mod11.filterDate(startdate, enddate)
  .sort('system:time_start', false)
  .filterBounds(vietnamCountry)
  .select("LST_Day_1km")

// convert LST to celcius
var toCelsius = function(image){
  var time = image.get('system:time_start')
  var celsius = image.multiply(0.02) // scale factor
                     .subtract(273.15) // from kelvin to C
                     .rename("Celcius")
                     .set('system:time_start',time)
  return celsius;
};

var CollectioninCelsius = temp.map(toCelsius)

var viz = {min:20.0, max:34, palette:"000b5e,96048f,4286f4,e2f442,960424"};
Map.addLayer(CollectioninCelsius.median().clip(table),viz,"temperature map")
Map.centerObject(vietnamCountry,5)

// Predefine the chart titles.
var title = {
  title: 'Temperature over time',
  hAxis: {title: 'Time'},
  vAxis: {title: 'Temperature (C)'},
};

// create the chart
var tempchart = ui.Chart.image.seriesByRegion(CollectioninCelsius,
                           vietnamCountry,
                           ee.Reducer.mean(),
                           'Celcius',
                            1000,
                           'system:time_start',
                           'PROJECT').setOptions(title);

// print the chart
print(tempchart);

Export.image.toDrive({
  image: mod11.select('Temp'),
  description: 'Temperatura',
  scale: 10,
  region: table,
  crs: 'EPSG:4326',
  folder: 'TCC',
  maxPixels: 10000000
});

https://code.earthengine.google.com/25c00e940fdcd572f8b0524a50b86d94
Table:
https://code.earthengine.google.com/?asset=users/eldileoliveira/Novapasta

A: You need to use the visualize function. It's hard to tell exactly what you want visualize, but I have a feeling this is what you're going for. I couldn't get the table to load right so I just used the Vietnam geometry for clipping instead. Here, what gets plotted on the map pane is the same image as what exports to drive but at a different resolution. If you want full resolution you can change that under the scale option in Export.image.toDrive() - it's a coarse resolution in this example for download speed/file size.
var mod11 = ee.ImageCollection("MODIS/MOD11A2");

// Specify name of country.
var country_names = ['Vietnam'];
// get fusion table with countries
var countries = ee.FeatureCollection('ft:1tdSwUL7MVpOauSgRzqVTOwdfy17KDbw-1d9omPw');
// select the country from the fusion table
var vietnamCountry = countries.filter(ee.Filter.inList('Country', country_names)).geometry();

// set start date
var startdate = ee.Date.fromYMD(2000,1,1);
// set end date
var enddate = ee.Date.fromYMD(2017,12,31);

// filter the data collection
var temp =  mod11.filterDate(startdate, enddate)
  .sort('system:time_start', false)
  .filterBounds(vietnamCountry)
  .select("LST_Day_1km");

// convert LST to celcius
var toCelsius = function(image){
  var time = image.get('system:time_start');
  var celsius = image.multiply(0.02) // scale factor
                     .subtract(273.15) // from kelvin to C
                     .rename("Celcius")
                     .set('system:time_start',time);
  return celsius;
};

var CollectioninCelsius = temp.map(toCelsius).median();

var viz = {min:20.0, max:34, palette:"000b5e,96048f,4286f4,e2f442,960424"};

Map.addLayer(vietnamCountry,{},"vietnamCountry");

var regionTemp = CollectioninCelsius.clip(vietnamCountry);

Map.centerObject(vietnamCountry,5);
Map.addLayer(regionTemp, viz,"temperature map");

print("region Temp",regionTemp);

var tempExport = regionTemp.visualize({bands:'Celcius', min:20.0, max:34, palette:"000b5e,96048f,4286f4,e2f442,960424"});

Export.image.toDrive({
  image: tempExport,
  description: 'Temperatura',
  scale: 10000,
  region: vietnamCountry,
  crs: 'EPSG:4326',
  folder: 'TCC',
  maxPixels: 10000000
});


text:
Q: are methods that modify input parameters and return them bad? I have the following code:
public class MyClass
{
        ....
}

public static MyClass MyClassModifier(MyClass myinstance)
{

  ......
 return myinstance;
}

It seems to me that returning myinstance doesn't actually do anything here, in other words this, achieves the same as the code above (As long as myinstance is not assigned to another object in the method):
public static void MyClassModifier(MyClass myinstance)
{

  ......

}

I could, of course, do this:
public static MyClass MyClassModifier(MyClass myinstance)
{

  ......
  return new MyClass();
}

but this seems pretty clunky and if the constructor for MyClass has many parameters then this becomes really clunky, so, the question is then, which one is preferable and why?
From a functional programming point of view it seems that the last one is the way to go but I'm not sure that this is the best way.

A:
are methods that modify input parameters and return them bad?

Yes. They're misleading - the client will assume your method reads the input parameter, creates a new object and returns it. When in fact, that's not what's going on. The returned value is the input value, and there's no need for the client to capture it.
Regarding your second question, whether you should mutate the input value or create a new one, the answer highly depends on what you're trying to achieve. It's impossible to give you a better answer without any context.

From a functional programming point of view it seems that the last one is the way to go but I'm not sure that this is the best way.

Yes, in functional programming you want immutable state - which means MyClass cannot be modified, and so you have to return a new instance of it.


text:
Q: LINQ on a list of a class Alright, I have a brain block (pre-thanksgiving haze if you will). I have deconstructed an integer to discover what bits are set (this was set based upon selected listbox items). So if I have my integer value being 11 then bits 1,2,4 are set. So I have deconstructed my bit mask to get which bit is set. I can put that back into a list of integers or an integer array.
Here is my problem. I have a stored procedure that goes to the database and returns a list of a class. This class was constructed by me and contains integers, strings, basically w/e I need in the class. The class looks for records matching user entered criteria. I am adding the multiple selection list box (done) and generating a bit mask that returns the integer value of the bits that are set (done). I make the database call and get the list of transactions based upon user entered criteria. I do not want to rewrite/add to my stored proc because it is used else where a decent amount. I just want to apply some LINQ that will search for all records matching the selections in my list.
The list will return different types of TransactionTypes. I get the transaction types row number (14 transaction types, 14 bits, 1-14 are the row numbers I am identifying off of). I made a loop to to add the row number integer to an array of integers.
for (int i = 0; i <= //countOfSelections is 14; i++)
{
    int num = 0;
    num = (//int of decimal value constructed & (1 << i));
    if (num != 0)
        bits[i] = num;
}

I have a database call that makes var data the list of the class. Is there anyway to loop through using link and apply a loop within the .where clause based upon the selection? So where RowNumber in the class equals the row numbers in the bit[] ?
EDIT: Here is more code.
My list box has selections in it (14 types of transactions).
When the user ctrl+clicks the types of transactions and searches upon them, I add the transaction types row number that is selected to a list of integers. So if selection one two and four are selected, my list containts 1,2,4. I do not want to have 14 where statements or be passing around 14 values since this is hardcoded. (what if i add more to the db table then I have to change this elsewhere).
In order to prevent myself from having to do this I assemble a bit mask and get an integer value (decimal of the binary). I do this like so:
int total = 0;
//Building the bit mask
for (int c = 0; c < optsNum.Count(); ++c)
{
    for (int i = 0; i <= transTypeCount; i++)
    {
        if ((i +1) == optsNum[c])
            total += (1 << i);
    }
}
return total;

Note that optsNum is my list of integers that contains the row numbers of the user selections. Also, transTypeCount is an integer that is the count of the possible selections in my list box. So again, if option 1,2,4 are selected. My returned total will equal 11.
I am then passing 11 to a method in some business logic. This method also receives some other user options (basic drop down boxes and such).
I have a class that contains information for transactions (contains quantities, products, names, and transaction types (my row numbers)). My database call returns a list of this class and it is stored in 'var data'. So 'data' is now a list of those classes.
In my method I now have data and need to filter data.TransactionID based upon the selected transaction types the user wants to see (this is within my decimal i made from the bit mask). So I need to deconstruct my bit mask to find out which bits are set. **I did this in the above code and bits[] array will contain an array of integers set. So again, 1,2,4.
I want to filter data to only get data where TransactionIDs in data are contained within my array bits[]. Is there anyway I can use LINQ to search through the class and only assemble a list of the class where the transaction IDs in that class equal the transaction IDs in my bits[] array? This would be a loop somehow...like loop through the bits[] and selected where transactionID = bits[i]. I am fairly new to LINQ and this is confusing me.

A: You can use a join:
var selectedTransactions =
        from t in data
        join transactionId in bits on t.TransactionID equals transactionId
        select t;


text:
Q: Can bisection method find complex roots? Intuitively, I don't think that the bisection method can locate complex roots due to its use of intervals, midpoints and sign of f(a),f(b) and f(c).
However, I am not sure about this claim. Can anyone please explain this in detail?


text:
Q: How can I change this method to get rid of the warning without anything changing? So this question:Warning-used as the name of the previous parameter rather than as part of the selector
answers part of my problem, but I really don't want anything to change inside this method and I'm a bit confused on how this works. Here's the whole method:
-(void) SetRightWrong:(sqzWord *)word: (int) rightWrong
{
if (self.mastered==nil) {
    self.mastered = [[NSMutableArray alloc]initWithCapacity:10];
}

//if right change number right
if (rightWrong == 1) {
    word.numberCorrect++;
     //if 3 right move to masterd list

    [self.onDeck removeObject:word];
    if(word.numberCorrect >= 3 )
    {
        [self.mastered addObject:word];

    }
    else
    {
         //if not 3 right move to end of ondeck
        [self.onDeck addObject:word];

    }

}
else if(rightWrong == 0)
{
    //if wrong remove one from number right unless 0
    NSUInteger i;

    i=[self.onDeck indexOfObject:word];

    word = [self.onDeck objectAtIndex:i];

    if (word.numberCorrect >0) {
         word.numberCorrect--;
    }
}
}

The warning I am getting is: 'word' used as the name of the previous parameter than as part of the selector.

A: Its because you haven't given a name to the first argument of the method. As it stands right now, you have the following:
-(void) SetRightWrong:(sqzWord *)word: (int) rightWrong

Where rightWrong is the name of the word: argument, but there is no name for the SetRightWrong argument. You should give the first parameter a name, immediately following its type (sqzWord *).
-(void)setRightWrong:(sqzWord *)aWord   word:(int)rightWrong;
   (1)     (2)           (3)     (4)     (5)   (6)  (7)

*

*Return Type

*First part of method name

*Parameter type

*First parameter

*Seceond part of method name

*Parameter type

*Second parameter

A: Do you understand what the problem actually is? You are saying you are confused a bit. So you are confused, you get a warning, which should clearly tell you that there is a problem, and instead of trying to fix the problem, you want help how to get rid of the warning? That is a deeply worrying attitude in a programmer.
To fix your problem: Download some Objective-C sample code. Any sample code. Look at how Objective-C methods are named. Compare it to how your Objective-C method is named. If you can't see the difference, look at it again tomorrow, and before you look at it say to yourself: "My code is wrong. The compiler is right. My task is to find why my code is wrong. "


text:
Q: Is there a way to check if substring in field for Log Analytics? I have a column full of Computers in Log Analytics. An example is, "window432, linus909, windows322, linux432". I am filtering my disk utilization but I also want to filter by the specific word "window" or "lin". Is that possible? I am using Kusto to query so here's an example of my thought process:
Perf
| where Name == "Utilization Percentage"
and "win" in Computer

Something like this. Is that possible?
Thank you.

A: Based on given information in the question and based on what I understand, the requirement is to filter based on Computer names starting with either "window" or "lin".
If that is the case then you can accomplish the requirement with startswith string operator.
Query would look something like:
Perf
| where CounterName == @"% Processor Time" and InstanceName == "_Total"
| where Computer startswith "window" or Computer startswith "lin"

or
InsightsMetrics
| where Name == "UtilizationPercentage"
| where Computer startswith "window" or Computer startswith "lin"

Similarly, based on the requirement, you may leverage other string operators like "in", "has", "endswith", etc. string operators or any other operators or functions as appropriate. For more information w.r.t it, please refer Kusto Query Language (KQL) documents.

A: If i understand the description correctly, this  could work.
It:

*

*splits the original comma separated string using split()

*expands those using mv-apply

*filters out values that don't contain win

*aggregates the remaining values into a new (filtered) comma separated string

datatable(Computers:string, id:int)
[
    "window432, linus909, windows322, linux432", 1,
    "window451, linux459, windows444, linux234", 2,
    "android222, ios222, linux333"             , 3
]
| mv-apply Computer = split(Computers, ", ") on (
    where Computer contains "win"
    | summarize Computers = strcat_array(make_list(Computer), ", ")
)
| where isnotempty(Computers)

input:
| Computers                                 | id |
|-------------------------------------------|----|
| window432, linus909, windows322, linux432 | 1  |
| window451, linux459, windows444, linux234 | 2  |
| android222, ios222, linux333              | 3  |

output:
| id | Computers             |
|----|-----------------------|
| 1  | window432, windows322 |
| 2  | window451, windows444 |


text:
Q: JavaFX - Getting the index when clicking something inside a 2d Array I've built a 2d array of ImageViews, and I want to be able to print out the indices of the ImageView when I click it (and use that information to change the pictures).
I've got the following code right now, but I don't know how to get it to print the x and y values of its location in the 2d array.
ImageView[][] mainGrid = new ImageView[8][8];

...
for (int x = 0; x < 8; x++) {
    for (int y = 0; y < 8; y++) {
        mainGrid[x][y] = new ImageView(image);
        mainGrid[x][y].setOnMouseClicked(createMouseHandler());
    }
}

...
private EventHandler<? super MouseEvent> createMouseHandler() {
    return event -> {
        System.out.println("Clicked");
    }
}

Any help is greatly appreciated! Thank you!

A: The most general solution to this problem is to use the getProperties() method of the Node class. You can use that to store any user information in a node you like and then later retrieve that if you need it. In your case store the indices and then retrieve them in your mouse handler.


text:
Q: Magento 2 After Migration Configurable Product Price blank I have Migrated Magento 1.9.1.0 website in Magento 2.2.4,all data is migrated successfully.
I have an issue when checking products in admin->catalog->product and compared price with Magento 1 ,configurable products have blank price and not editable

while in Magento 1 its price is 79.95 and special price is 57.98.Variants products price are same as in Magento 1 ,please check below image

but clicking on advanced pricing,its display blank

my issue is same as below referenced but solution is not here.
https://github.com/magento/data-migration-tool/issues/281
I don't have idea how to resolve that issue.Special price are not display as well as config product price are displaying wrong in front-end.
Please help me if anyone have same problem.


text:
Q: How can I set background colour for top section in iPhoneX I just realise that my app is not working for iphoneX's design. I have a UIVIew (containing textfield and button) tends to be like navigation bar so it does support for iPhone 8 and 8 plus. However, the iPhoneX has blank white for the top section. Vice versa, if I set the Uiview to act like navigation bar, then the iphone8 and 8plus will have higher gap between the textfield and top layout. May I know how can I set the constraint that fits for all version or other way to add for the top section and it also changed when landscape mode. Many thanks!
screenshot

A: If you are using Interface Builder you may want to update your constraints and their settings.
if #available(iOS 11.0, *) {
     if UIApplication.shared.keyWindow!.safeAreaInsets.top > CGFloat(0.0) {
         topConstraint.constant += 24
     }
 }

or


text:
Q: PHP include doesnt work on files other than index So here is my problem:
I have an index.php in root directory in xampp's htdocs. The purpose of that is to login an user. After he loggs in, he is redirected to the game/index.php, where i have two includes:
<?php include('/game/components/language_declaration.php');
        include('/game/components/currency/userdata_func.php');
  ?>

Here is the directory list:
index.php (which redirects to index below)
---/game/index.php (includes work)
---/game/units.php (the same includes dont work)
---/game/components/language_declaration.php
---/game/components/currency/userdata_func.php

There is a link in this index which points to units.php. And there are the same includes in units.php, except the fact that they dont work. This is the error that i get:
Warning: include(/game/components/language_declaration.php): failed to open stream: No such file or directory in E:\xampp\htdocs\game\units.php on line 7

Warning: include(): Failed opening '/game/components/language_declaration.php' for inclusion (include_path='.;\xampp\php\PEAR') in E:\xampp\htdocs\game\units.php on line 7

Warning: include(/game/components/currency/userdata_func.php): failed to open stream: No such file or directory in E:\xampp\htdocs\game\units.php on line 8

Warning: include(): Failed opening '/game/components/currency/userdata_func.php' for inclusion (include_path='.;\xampp\php\PEAR') in E:\xampp\htdocs\game\units.php on line 8

I have read about 20 posts about this problem, every single one advised to change the path, I have tried to add dots, slashes and so one, even defining the root directory. None worked. Could you help me please?

A: Your include statements should be like this:
---/game/index.php
<?php
    include('components/language_declaration.php');
    include('components/currency/userdata_func.php');
?>

---/game/units.php
<?php
    include('components/language_declaration.php');
    include('components/currency/userdata_func.php');
?>


text:
Q: how to call a private function from another class if the instance of the object is already there in kotlin? i want to call this function from another class - OneOffPaymentService
fun toPaymentRequestHistoryEvent(): PaymentRequestHistoryEvent {
return PaymentRequestHistoryEvent(
id = this.id,
userId = this.userId,
paymentDate = this.paymentDate,
type = this.type,
amount = this.amount
)
}
i tried to call this from another class OneOffPaymentService and WithdrawalService

A: i did this
checkPartialWithdrawalConditions(userId, accountId, amountToWithdraw)
val avaloqRequest = PartialWithdrawalAvaloqRequest(amountToWithdraw, refData.withdrawalDescription())
avaloqPaymentClient.makePartialWithdrawal(userId, accountId, avaloqRequest)
paymentRequestRecorder.recordPartialWithdrawal(userId, amount, LocalDate.now(clock))
.also { analyticsSqsPublisher.publishPaymentHistoryEvent(it.toPaymentRequestHistoryEvent()) }


text:
Q: Приостановить отправку сообщений пока пользователь не нажмет InlineKeyboardButton Пользователь вводит множество значений, и чтобы не отправлять сразу тонну сообщений нужно подтверждать отправку каждого следующего нажатием inline кнопки. Код рабочий, убрал все лишнее чтобы был лучше понятен сценарий. Комментариями обозначил основные шаги и где требуется подтверждение от пользователя. Есть какой-то способ приостановить отправку сообщений в цикле и возобновить только при нажатии inline кнопки?
import os

from aiogram.dispatcher import FSMContext
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import StatesGroup, State

bot = Bot(token=os.environ["TOKEN"])
dispatcher = Dispatcher(bot, storage=MemoryStorage())

class Searches(StatesGroup):
    by_id = State()

@dispatcher.message_handler(state='*', commands='cancel')
async def cancel_state(message: types.Message, state: FSMContext):
    if await state.get_state():
        await state.finish()
        await message.reply("Поиск был отменён.")

@dispatcher.message_handler(commands="search")
async def answer_search_message(message: types.Message):
    find_by_id_button = types.InlineKeyboardButton("по ID", callback_data="by_id")
    keyboard = types.InlineKeyboardMarkup().row(find_by_id_button)
    await message.answer("Выбери тип поиска", parse_mode="HTML", reply_markup=keyboard)

@dispatcher.callback_query_handler(text="by_id")
async def callback_id(callback: types.CallbackQuery):
    await callback.message.answer("Введи ID, разделяя их запятой")
    await Searches.by_id.set()

@dispatcher.message_handler(state=Searches.by_id)
async def find_by_id(message: types.Message, state: FSMContext):
    ids_from_message = [item for item in range(5)]  # получаю список id из сообщения
    for index, item in enumerate(ids_from_message):
        photo, caption, url = ("https://www.google.ru/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png", "текст документа", "https://www.example.org/")  # получаю по id какие-то данные
        button_to_site = types.InlineKeyboardButton("Подробнее на сайте", url)
        keyboard = types.InlineKeyboardMarkup().row(button_to_site)
        if len(ids_from_message) > index + 1:  # если это не последний id, то показываю кнопку "Следующий результат"
            keyboard.add(types.InlineKeyboardButton("Следующий результат", callback_data="show_next"))
            await message.answer_photo(photo=photo, caption=caption, parse_mode="HTML", reply_markup=keyboard)
            # тормознуть цикл тут, ожидая нажатия кнопки "Следующий результат"
        else:
            await message.answer_photo(photo=photo, caption=caption, parse_mode="HTML", reply_markup=keyboard)
            await state.finish()

executor.start_polling(dispatcher)

A: Вот мой вариант решния этой проблемы. Суть его в том, что можно сохранить некие данные в используемое хранилище (в данном примере локальное). И потом по чуть-чуть их отправлять пользователю, когда тот нажимает кнопку.
import os

from aiogram.dispatcher import FSMContext
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import StatesGroup, State

def get_record_by_id(doc_id):
    # тут как-то обработался id и что-то вернул
    return "https://www.google.ru/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png", "текст документа", "https://www.example.org/"

bot = Bot(token=os.environ["TOKEN"])
storage = MemoryStorage()
dispatcher = Dispatcher(bot, storage=storage)

class Searches(StatesGroup):
    by_id = State()

@dispatcher.message_handler(state='*', commands='cancel')
async def cancel_state(message: types.Message, state: FSMContext):
    if await state.get_state():
        await state.finish()
        await message.reply("Поиск был отменён.")

@dispatcher.message_handler(commands="search")
async def answer_search_message(message: types.Message):
    find_by_id_button = types.InlineKeyboardButton("по ID", callback_data="by_id")
    keyboard = types.InlineKeyboardMarkup().row(find_by_id_button)
    await message.answer("Выбери тип поиска", parse_mode="HTML", reply_markup=keyboard)

@dispatcher.callback_query_handler(text="by_id")
async def callback_id(callback: types.CallbackQuery):
    await callback.message.answer("Введи ID, разделяя их запятой")
    await Searches.by_id.set()
    await callback.answer()

@dispatcher.message_handler(state=Searches.by_id)
async def find_by_id(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    ids_from_message = [item for item in range(5)]
    photo, caption, url = get_record_by_id(ids_from_message[0])
    button_to_site = types.InlineKeyboardButton("Подробнее на сайте", url)
    keyboard = types.InlineKeyboardMarkup().row(button_to_site)
    if len(ids_from_message) > 1:
        del ids_from_message[0]
        await storage.set_data(user=user_id, data={"ids_to_send": ids_from_message})
        keyboard.add(types.InlineKeyboardButton("Следующий результат", callback_data="show_next"))
        await message.answer_photo(photo=photo, caption=caption, parse_mode="HTML", reply_markup=keyboard)
    else:
        await message.answer_photo(photo=photo, caption=caption, parse_mode="HTML", reply_markup=keyboard)
        await state.finish()

@dispatcher.callback_query_handler(state=Searches.by_id, text="show_next")
async def callback_id(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    chat_id = callback.message.chat.id
    data = await storage.get_data(user=user_id)
    photo, caption, url = get_record_by_id(data["ids_to_send"][0])
    button_to_site = types.InlineKeyboardButton("Подробнее на сайте", url)
    keyboard = types.InlineKeyboardMarkup().row(button_to_site)
    if len(data["ids_to_send"]) > 1:
        del data["ids_to_send"][0]
        await storage.set_data(user=user_id, data={"ids_to_send": data["ids_to_send"]})
        keyboard.add(types.InlineKeyboardButton("Следующий результат", callback_data="show_next"))
        await bot.send_photo(chat_id=chat_id, photo=photo, caption=caption, parse_mode="HTML", reply_markup=keyboard)
    else:
        await bot.send_photo(chat_id=chat_id, photo=photo, caption=caption, parse_mode="HTML", reply_markup=keyboard)
        await state.finish()
    await callback.answer()

executor.start_polling(dispatcher)


text:
Q: How to check whether device set vibration mode or not in iOS programatically? I am making a VoIP application for iOS. For incoming calls, I have set some custom ringtones. It's working fine, but I want to check whether the device settings are set to Vibration mode or not programmatically.
I have searched on the web regarding this issue, but I've only found answers for silent mode detection. Instead, I want to check whether the device is in vibration mode or not.
When an incoming call comes to my app, I want to use vibration mode if the device settings are set to vibration mode.
Could any one help me?

A: At first look it seems like none of the Audio Session properties allow you to read the value of this setting. However an alternative, albeit not exactly what you're looking for, is to check if the ringer is set to on-or-off and provide at least a semi-expected vibration experience to your user.
Ronak Chaniyara pointed you to the right answer here, however that is deprecated in iOS 7.0. Instead use AVAudiSession -setCategory to set the proper category of your audio. If you expect your audio to be muted by the silent switch or screen lock use AVAudioSessionCategorySoloAmbient otherwise use AVAudioSessionCategoryPlayback.
More details on AVAudioSession, it's settings and properties can be found here.


text:
Q: Object[] cannot be cast to Void[] in AsyncTask I'm getting this error inside an extended asynctask, but i'm really sure that Object[] IS a Void[].
This is my custom AsyncTask:
public abstract class RepeatableAsyncTask<A, B, C> extends AsyncTask<A, B, C> {
private static final String TAG = "RepeatableAsyncTask";
public static final int DEFAULT_MAX_RETRY = 5;

private int mMaxRetries = DEFAULT_MAX_RETRY;
private Exception mException = null;

/**
 * Default constructor
 */
public RepeatableAsyncTask() {
    super();
}

/**
 * Constructs an AsyncTask that will repeate itself for max Retries
 * @param retries Max Retries.
 */
public RepeatableAsyncTask(int retries) {
    super();
    mMaxRetries = retries;
}

/**
 * Will be repeated for max retries while the result is null or an exception is thrown.
 * @param inputs Same as AsyncTask's
 * @return Same as AsyncTask's
 */
protected abstract C repeatInBackground(A...inputs);

@Override
protected final C doInBackground(A...inputs) {
    int tries = 0;
    C result = null;

    /* This is the main loop, repeatInBackground will be repeated until result will not be null */
    while(tries++ < mMaxRetries && result == null) {
        try {
            result = repeatInBackground(inputs);
        } catch (Exception exception) {
            /* You might want to log the exception everytime, do it here. */
            mException = exception;
        }
    }
    return result;
}

/**
 * Like onPostExecute but will return an eventual Exception
 * @param c Result same as AsyncTask
 * @param exception Exception thrown in the loop, even if the result is not null.
 */
protected abstract void onPostExecute(C c, Exception exception);

@Override
protected final void onPostExecute(C c) {
    super.onPostExecute(c);
    onPostExecute(c, mException);
}

And this is the SubClass that gives the problem:
public class ListPalinasAsynkTask extends RepeatableAsyncTask<Void, Void, List<Palina>>{
    private static final String TAG = "ListPalinasAsynkTask";
    private static final boolean D = SystemConstants.ACTIVE_DEBUG;

    private ApiRequest.ListPalinasCallback mCallback;

    public ListPalinasAsynkTask(ApiRequest.ListPalinasCallback callback) {
        if(D) Log.d(TAG, "Called: ListPalinasAsynkTask([callback])");
        mCallback = callback;
    }

    @Override
    protected List<Palina> repeatInBackground(Void... voids) {
        /* Here i send request to get palinas */
        return Api.getPalinasNearMe();
    }

    @Override
    protected void onPostExecute(List<Palina> palinas, Exception exception) {
        if(exception != null)
            Logging.e(TAG, "Received exception in Asynk Task", exception);
        if(palinas != null)
            mCallback.result(palinas);
        else
            mCallback.result(new ArrayList<Palina>());
    }
}

Finally, this is the error:
E/ListPalinasAsynkTask﹕ Received exception in Asynk Task
    java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Void[]
            at ListPalinasAsynkTask.repeatInBackground(ListPalinasAsynkTask.java:19)
            at RepeatableAsyncTask.doInBackground(RepeatableAsyncTask.java:43)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)

I can't explain this exception because i'm giving Void as a parameter! That should not be an Object.
Do you have solutions?
Edit:
ListPalinasAsyncTask.java:19 refers to:
public class ListPalinasAsynkTask extends RepeatableAsyncTask<Void, Void, List<Palina>> {

RepeatableAsyncTask.java:43:
result = repeatInBackground(inputs);

EDIT 2:
I'm calling execute this way:
AsyncTask mAsyncTask = new ListPalinasAsynkTask(callback);
....
mAsyncTask.execute();

A: The solution is much simpler as I see it.
Just create the subclass object in this way:
AsyncTask<Void, Void, List<Palina> mAsyncTask = new ListPalinasAsynkTask(callback);
....
mAsyncTask.execute();

A: Solution found:
the problem was this:
AsyncTask mAsyncTask = new ListPalinasAsynkTask(callback);
....
mAsyncTask.execute();

I'm using generic AsyncTask to call execute, that class would pass Void as a parameter and will never call .execute() on ListPalinasAsynkTask, instead it will call ListPalinasAsynkTask.execute(Void). That gives the error.
Solutions:

*

*Use ListPalinasAsynkTask instead of generic AsyncTask

*Better one: Create a new class VoidRepeatableAsyncTask and make other Void AsyncTasks extend that one.

Like this:
public abstract class VoidRepeatableAsyncTask<T> extends RepeatableAsyncTask<Void, Void, T> {
    public void execute() {
        super.execute();
    }
}

Then you can easily use something like this to call execute:
VoidRepeatableAsyncTask mAsyncTask = new ListPalinasAsynkTask(callback);
....
mAsyncTask.execute();

This will call the no-parameters execute method of AsyncTask.

A: An alternative way with which I solved it is to pass Object in parameters, even if you don't use the parameters.
new AsyncTask<Object, Void, MergeAdapter>()

and the override:
@Override
protected ReturnClass doInBackground(Object... params) {
    //...
}

The above applies (in my case) if you want to pass different types of AsyncTasks to a method and of course you do not care about the parameters.

A: Try using:
result = repeatInBackground((Void) inputs);

instead of
result = repeatInBackground(inputs);

A: If this problem is occurring then you might have created a Derived class object and added its the base class variable (AsyncTask). So this error is occurring.
AsyncTask mAsyncTask = new ListPalinasAsynkTask(callback);
Lint also gives a warning when you do like this "Unchecked call to execute. Params ...."
The solution is
ListPalinasAsynkTask mAsyncTask = new ListPalinasAsynkTask(callback);
Then call execute on it. It will work fine


text:
Q: how to save the state of radio buttons in htmlunit I am using htmlunit to select radio button, and after clicking this button i checked if it is selected and got true which is fine.
my problem is when I leave the page and then back to it the radio button is not checkd and the default one will be the checked one !
does any one has idea about this issue ?

A: If somebody needs solution to this, you need to save the state to HtmlPage. When you want to resume to earlier radio button selection state, can achieve that using following code
HtmlPage selectionsHtmlPage = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();

in future, at any point when you want to start over from the selection again,
webClient.getCurrentWindow().setEnclosedPage(selectionsHtmlPage);

This method is just a way to do that operation only when doing this does not affect/break the ideal expected workflow of the web application.


text:
Q: Making GCP Load-balancer HTTP logs integrate with Cloud Trace (in GCP Logs Explorer)? Cloud Trace and Cloud Logging integrate quite nicely in most cases, described in https://cloud.google.com/trace/docs/trace-log-integration
Unfortunately, this doesn't seem to include the HTTP request logs generated by a Load Balancer when request logging is enabled.
The LB logs show the traces icon, and are correctly associated with an overall trace in the Cloud Trace system, but the context menu 'show trace details' is greyed out for those log items.
A similar problem arose with my application level logging/tracing, and was solved by setting the traceSampled attribute on the LogEntry, but this can't work for LB logs, since I'm not in control of their generation.
In this instance I'm tracing 100% of requests since the service is M2M and fairly low volume, but in the general case it makes sense that the LB can't know if something is actually generating traces without being told.
I can't find any good references in the docs, but in theory a response header indicating it was sampled could be observed by the LB and cause it to issue the appropriate log.
Any ideas if such a feature exists, in this form or any other?
(Last-ditch workaround might be to use Logs Router to feed LB logs into a pubsub queue (and exclude them from normal logging sinks), and resubmit them to the normal sink(s) with fields appropriately set by some Cloud Function or other pubsub consumer, but that seems like a lot of work and complexity for this purpose)

A: There is currently a Feature Request created for this, you can follow the status in the following link 1.
As a workaround, you could implement target proxies along with your Load Balancer, according to the documentation for a Global external HTTP(S) load balancer:

The proxies set HTTP request/response headers as follows:

*

*Via: 1.1 google (requests and responses)

*X-Forwarded-Proto: [http |    https] (requests only)

*X-Cloud-Trace-Context: <trace-id>/<span-id>;<trace-options> (requests only) Contains parameters for Cloud Trace.

*X-Forwarded-For:    [<supplied-value>,]<client-ip>,<load-balancer-ip>
(see    X-Forwarded-For header) (requests only)

You can find the complete documentation about external HTTP(S) load balancers and target proxies here 2.
And finally, take a look at the documentation on how to use and configure target proxies here 3.


text:
Q: How can my JavaScript assert library return a pass? I am working on a custom Javascript assert library, primarily for use in test runners like Mocha.
The library works fine when the test fails, by throwing an Error. However, I can't figure out how to make the library return a "pass", when there's no Error to throw.
I have tried reading through the source of other libraries like Should and Chai, but haven't been able to locate this aspect.
Here is my assert library, my-assert-lib.js:
module.exports = function(input){
    var methods = {
        compare: function(comparison){
            if(input != comparison){
                throw new Error("The comparison string didn't match")
            }
            else{
                return
            }
        }

    }
    return methods
}

Here is my test.js, which I'm executing with Mocha:
var myAssertLib = require("./my-assert-lib.js")("correct");

describe("The comparison string", function(){
    it('should match the library input', function(doc) {
        myAssertLib.compare("incorrect")
    });

    it('should match the library input', function(doc) {
        myAssertLib.compare("correct")
    });
})

I get these results:
  0 passing (2s)
  2 failing

  1) The comparison string
       should match the library input:
     Error: The comparison string didn't match
      at Object.compare (my-assert-lib.js:5:23)
      at Context.<anonymous> (test.js:10:21)

  2) The comparison string
       should match the library input:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

The first test exits immediately, as it should. However, the second test times out. What does my-assert-lib.js need to do when there's nothing to throw and the test runner should continue?

A: I can't say why, but mocha is expecting you to call the done function.

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

Doing so yields one pass and one fail, as expected.
describe("The comparison string", function(){
    it('should match the library input', function(done) {
        myAssertLib.compare("incorrect")
        done()
    })
    it('should match the library input', function(done) {
        myAssertLib.compare("correct")
        done()
    })
})

>   The comparison string
>     1) should match the library input
>     ✓ should match the library input
>
>
>   1 passing (14ms)   1 failing
>
>   1) The comparison string
>        should match the library input:
>      Error: The comparison string didn't match
>       at Object.compare (assertLib.js:7:23)
>       at Context.<anonymous> (test.js:7:21)