text:
Q: OpenGL ES Stencil Buffer not working on specific devices I'm using OpenGL ES 2.0, and using a Stencil Buffer. Below is code from a simple Stencil Buffer Demo I made. The Stenciling is only works properly on one device.
Devices are as follows:
Android 4.2.2, PowerVR SGX 544MP (GPU), Allwinner A10 tablet. (Stencil Buffer works perfectly on this device)
Android 4.1.2, Adreno 225 (GPU), Galaxy S III Phone. (Stencil Buffer does not work, some flickering with ghost image of stencil rarely.
Android 4.2.2, Mali-400MP (GPU), Rockchip rk30sdk tablet. (In initial testing, the Stencil Buffer was not working, after many changes it now seems to be working, status is questionable. Specific change that remedied in-op Stencil Buffer unknown at this point)
Same latest .APK gave the above results.
Application 'OpenGL 3D Showcase' from 'Play Store' was run on all three devices and 'showcase' #18 'Stencil Buffer Shadows'[OGL 1.1] work perfectly with no error messages. Source code is provided with the App and has been reviewed to no-avail.
Below is my Stencil code:
public void onDrawFrame(GL10 glUnused) {
    // Clear the rendering surface.
     glClear( GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );

    multiplyMM(viewProjectionMatrix, 0, projectionMatrix, 0, viewMatrix, 0);

    invertM(invertedViewProjectionMatrix, 0, viewProjectionMatrix, 0);

    //Start using the stencil
    glEnable( GL_STENCIL_TEST );
    //Disable rendering to the color buffer
    glColorMask( false, false, false, false );

   //Place a 1 where rendered
   glStencilFunc( GL_ALWAYS, 1, 1 );

   //Replace where rendered
   glStencilOp( GL_REPLACE, GL_REPLACE, GL_REPLACE );

   glDisable(GL_DEPTH_TEST);

   glStencilMask(0xFF);//value used when writing to stencil buffer

    // draw stencil triangle
    rotateObjectInScene(0.0f, 0.0f, 0.0f);//x,y,z Object is rottated one full rotation ever 3 seconds within
    colorProgram.useProgram();
    colorProgram.setUniforms(modelViewProjectionMatrix, 0f, 0f, 1f);
    DemoTriangleStencilObj.bindData(colorProgram);
    DemoTriangleStencilObj.draw();

    //Reenable color
    glColorMask( true, true, true, true );
    //Where a 1 was not rendered
    glStencilFunc( GL_EQUAL, 1, 1 );//GL_EQUAL GL_NOTEQUAL
    //Keep the pixel
    glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );

    glStencilMask(0x00);//disable writing to stencil buffer by setting value used to 0.

    positionObjectInScene1(0.0f, 0.0f, 0.0f);//leave image/object fixed in center of screen
    textureProgram1.useProgram();
    textureProgram1.setUniforms(modelViewProjectionMatrix, texture_opengl);
    openglImageDemoObj.bindData(textureProgram1);
    openglImagerectanDemoObj.draw();

    //Finished using stencil
    glDisable( GL_STENCIL_TEST );

}

Init:
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

}

public void onSurfaceChanged(GL10 glUnused, int width, int height) {
    // Set the OpenGL viewport to fill the entire surface.
    glViewport(0, 0, width, height);

    // Landscape
    orthoM(projectionMatrix, 0, -1, 1, -1f, 1f, -1f, 20f);

    setLookAtM(viewMatrix, 0, 0f, 2.0f, 0.1f, 0.0f, 0f, 0f, 0f, 1f, 0f);

}

Init2:
All commented 'setEGLConfigChooser' calls have been tried.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    //Remove notification bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //setContentView(R.layout.activity_fist_open_glproject_aactivity);
    glSurfaceView = new GLSurfaceView(this);
    final TheSurfaceRenderer theSurfaceRenderer = new TheSurfaceRenderer(this);

    this.getApplicationContext();
    final ActivityManager activityManager =
            (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    final ConfigurationInfo configurationInfo =
            activityManager.getDeviceConfigurationInfo();
    //final boolean supportsEs2 = false;//configurationInfo.reqGlEsVersion >= 0x20000;
    final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;

    if (supportsEs2) {
        // Request an OpenGL ES 2.0 compatible context.
        glSurfaceView.setEGLContextClientVersion(2);

        //glSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);//when use emulator, may be needed.
        glSurfaceView.setEGLConfigChooser(new MultiSampleConfigChooser());
        //glSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 8);
        //glSurfaceView.setEGLConfigChooser(5,6,5,0,24,8);
        //glSurfaceView.setEGLConfigChooser(5,6,5,0,16,8);
        //glSurfaceView.setEGLConfigChooser(5,6,5,8,16,8);

        // Assign our renderer.
        //glSurfaceView.setRenderer(new AirHockeyRenderer(this));
        glSurfaceView.setRenderer(theSurfaceRenderer);
        rendererSet = true;
        //Toast.makeText(this, "Renderer started", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, "This device does not support OpenGL ES 2.0.",
        Toast.LENGTH_LONG).show();
        return;
    }

    setContentView(glSurfaceView);
}

Any ideas to track the issue? Any where else I'm likely to get help?(If need be, can contacting a MFG/Android/Google get me anywhere?)

A: In the code you provided, you set glStencilMask(0xFF) then later you do glStencilMask(0x00).  OpenGL is a state machine, so whatever you last set is the current value--even when you clear.  The default stencil mask value is 255 so your glClear works on the first frame.  But after that, the stencil mask is 0 (because you set it that way) and so the stencil buffer does NOT get cleared.  Do this at the top of your function:
public void onDrawFrame(GL10 glUnused) {
    // Clear the rendering surface.
    glStencilMask(0xFF);
    glClear( GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
    ...
}

The glStencilMask function sets the write mask--clearing is a write operation, so you should typically set all stencil bits to write-able when clearing.


text:
Q: Avoid or block all load balanced sites from being crawled We have an Umbraco site in a load balanced environment and we need to make sure only the actual URL gets crawled and not the different production URLs.
We only want example.com to be indexed while load balancers at production1.example.com and production2.example.com are not.
Do I add a disallow rule for those URLs to the robots.txt, or add a meta nofollow tag to the head? Or is there another way to have the load balancing URLs not indexed by crawlers?

A: Best solution: Don't make node-specific URLs publicly available (we usually use local ip/port to check a site on a specific node).
Since you have those domains, you may serve a different robots.txt depending on the domain (using URL rewriting).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to "type" random package return I'm building an API to allow for plugins in an application I'm working on. I'm using importlib.import_module to import the plugins. Clearly I have no idea what modules are going to be imported ahead of time. Is there a way to identify the return type as a generic module on the method I'm using to do the imports?
def import_plugin(plugin_name: str) -> <Some generic module type>:
    # conditional tests here...
    return importlib.import_module("plugins.{}".format(plugin_name))

A: The type of a module is given by types.ModuleType in the types module.
import types
type(types) is types.ModuleType
# => True

A: Python uses duck typing, so I recommend assuming it is a module, and if it is not let the user handle it. If you really want to get the type, use types.ModuleType as khelwood said.


text:
Q: Procesar petición POST con API Fetch Estoy tratando de ingresar un registro a mi base de datos con PHP, usando la API Fetch para evitar que la página se recargue, de este modo
let button = document.getElementById("ingreso")

button.addEventListener("click", function(e) {
    e.preventDefault()
    let nuevoUsuario = document.getElementById("nombre").value
    let newUser = {
        name: nuevoUsuario
    }
    fetch('alta.php', {
        method: 'post',
        body: JSON.stringify(newUser)
    })
})

Como pueden ver

*

*Obtengo el button al cual le hago clic

*le agrego un eventListener para estar a la escucha de cuando le den click

*Por dentro obtengo el valor del input, donde el usuario escribe el nombre

*declaro un objeto que contiene en la key el valor asignado de la variable nuevoUsuario

*Con la API fetch paso la URL

*como segundo argumento paso el method que es POST y en la key body el valor del objeto que es newUser
Cuando presiono el botón, desde la consola del navegador, en la pestaña de Netwrok visualizo lo siguiente
Status Code: 200 OK

Y el payload es:
{name: "alfa"}
name: "alfa"

ACTUALIZACIÓN
Ya corregí el error anterior, era un detalle con el método prepare() sin embargo ahora aunque se procesa la consulta cuando hago un SELECT  en mi tabla, cada registro que intento dar de alta me aparece como NULL

A: Te falta indicar el Content-type en la petición:
fetch('alta.php', {
  method: 'post',
  body: JSON.stringify( newUser ),
  headers:{
    'Content-Type': 'application/json'
  }
} );

Adicionalmente, desde PHP no puedes obtener tus datos mediante la superglobal $POST, tienes que obtenerlos desde el body:
$params = json_decode( file_get_contents( 'php://input' ), true );


text:
Q: PHP rtrim() or similar function for removing X amount of characters from string This should be pretty basic. I've searched all over the best matching function (as far as I can see from PHP Manual is rtrim)
I've got a string. I want to remove X-amount of characters from, specifically the first 4 characters from the string.
EXAMPLE:

Fri, Dec 1, 2017
Sat, Dec 2, 2017
Sat, Dec 2, 2017

I would like to remove the first 4 characters from the left including white space after comma in order for me to have a date I can work with without day of week.
Now according to manual and W3Schools rtrim() enables you to do the above. However as I understand it, you have to put in the characters / text you want to be trimmed from string.
My problem is the days of the week will alternate from MON - SUN thus I can not put specific characters.
I'm trying to trim with index numbers starting from left 0-4
So at the end:

Fri, Dec 1, 2017

Should read

Dec 1, 2017

A: Try;
substr("Fri, Dec 1, 2017", 5);


text:
Q: I can't enable binlog in MySQL I am trying to enable binary log in order to create master slave for my DB.
MySQL version is 5.1.41-3ubuntu12.10-log
I have added this to my.cnf

log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days  = 1
max_binlog_size   = 100M

and

$ ls -l /var/log/mysql/mysql-bin.log
-rw-r--r-- 1 mysql root 0 2011-07-06 17:17 /var/log/mysql/mysql-bin.log

Now when I try to stop/start MySQL the starting process goes forever and I was forced to comment those entries in my.cnf to start MySQL again.
Anybody faced such problem? Any idea is highly appreciated.

A: Do you have a host_name-bin.index file created? If not, specify log-bin-index as well.

A: Thanks guys for your help
it was permission of the log directory itself. i have changed it to be

drwx------ 7 mysql mysql  4096 2011-07-06 20:06 mysql

it was

drwx------ 7 root root  4096 2011-07-06 20:06 mysql


text:
Q: Run shell script downloaded from web I have a .sh script (wget-20121105144134.sh) which I downloaded from the web. The script contains codes to download huge climate data files.
Can you tell me how to run this file on Linux? It is easy for me to run a file which exist in my directory. The file above has been downloaded from the web and how can I add to my current directory or run directly on terminal?
Regards,
Elv.

A: You need to make it executable.  you can use chmod +x filename
or you can right click and select the make executable check box.
Then you can run it by clicking it or even in the terminal with sh filename.sh or just ./filename.sh

A: You can probably just right click the file, select Properties > Rights and tick the box called something like "Allow running this file as an executable". After that, you just double click it.


text:
Q: How to reference a generic parameter recursively? I have solved a Y-combinator problem. Just now I found that I cannot reference a generic parameter recursively.
Y = λf.(λx.f (x x)) (λx.f (x x))

for example:
IntUnaryOperator fact = Y(rec -> n -> n == 0 ? 1 : n * rec.applyAsInt(n - 1));

IntUnaryOperator Y(Function<IntUnaryOperator, IntUnaryOperator> f) {
    return g(g -> f.apply(x -> g.apply(g).applyAsInt(x)));
}

IntUnaryOperator g(G g) {
    return g.apply(g);
}

//        v--- I want to remove the middle-interface `G`
interface G extends Function<G, IntUnaryOperator> {/**/}

Q:  How can I use generic parameter on the method g to  avoid introducing an additional interface G, and the generic parameter should avoiding the UNCHECKED warnings?
Thanks in advance.

A: You can declare a generic method with a recursive type definition
<G extends Function<G, IntUnaryOperator>> IntUnaryOperator g(G g) {
    return g.apply(g);
}

What doesn't work, is to invoke this method with a lambda expression, assigning the lambda expression to G. The specification says

15.27.3. Type of a Lambda Expression
A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) …

and G is not a functional interface, but a type parameter, and there is no way to infer an actual interface type for G here.
That still works, when you use the actual interface G for the lambda expression:
IntUnaryOperator Y(Function<IntUnaryOperator, IntUnaryOperator> f) {
    return g((G)g -> f.apply(x -> g.apply(g).applyAsInt(x)));
}

// renamed the type parameter from G to F to avoid confusion
<F extends Function<F, IntUnaryOperator>> IntUnaryOperator g(F f) {
    return f.apply(f);
}

// can't get rid of this interface
interface G extends Function<G, IntUnaryOperator> {/**/}

or
IntUnaryOperator fact = Y(rec -> n -> n == 0 ? 1 : n * rec.applyAsInt(n - 1));

IntUnaryOperator Y(Function<IntUnaryOperator, IntUnaryOperator> f) {
    return this.<G>g(g -> f.apply(x -> g.apply(g).applyAsInt(x)));
}

// renamed the type parameter from G to F to avoid confusion
<F extends Function<F, IntUnaryOperator>> IntUnaryOperator g(F f) {
    return f.apply(f);
}

// can't get rid of this interface
interface G extends Function<G, IntUnaryOperator> {/**/}

So the method g is generic with no dependency to the interface G, but the interface is still required to be used as target type for the lambda expression.


text:
Q: Umbraco 8 website and Azure CDN (caching for page does not work) I am working on a client's website where I need to setup CDN using DNS. I using Azure CDN (Microsoft CDN) and I did it on www prefix, so when you request https://www.taxory.com it is actually loaded from CDN.
It all works fine for images, scripts, and styles. But the actual page does not load from CDN. I can't figure out if that is something related to Umbraco or some configuration in web.config or in Azure CDN.
As you see on the screenshot I have "TCP_HIT" for all my resources and the only one "TCP_MISS" is the actual Umbraco page.
Any idea how to fix it?

A: You need to change the cache-control settings of the www.tasory.com page. It should not be set to private or nocache.


text:
Q: Adding New Row Restriction in Kendo Grid MVC I have a Kendo grid and a Save button on top of the page. When I click on "Add New Record" toolbar, a new row is added in the grid (client side). When I click on save button, I get the updated viewmodel in my controller's action method which in turns add/update data in the database.
Now, I want to restrict adding a row in the grid if the grid has already 5 rows in it which means user will not be  able to add a new row if the grid reaches its limit (which is 5 rows).
Can anyone of you please give me a sample client side script(jquery) that will restrict user to add new row in the grid?
Thank you very much!!!!!!!
Index.cshtml
@using (Html.BeginForm("Save", "UDF", FormMethod.Post))
{

<input class="button" type="submit" name="save" value="Save"/>
@(Html.Kendo().Grid(Model.List1)
                     .Name("List1")
                     .HtmlAttributes(new { style = "width:auto;height:100%" })
                     .ToolBar(toolbar => toolbar.Create().Text("Add New Record"))
                     .Editable(editable => editable.Mode(GridEditMode.InCell).CreateAt(GridInsertRowPosition.Top))
                     .Columns(columns =>
                         {
                             columns.Bound(p => p.Title)
                                     .ClientTemplate("#= Title #" +
                                        "<input type='hidden' name='DateFields[#= index(data)#].Title' value='#= Title #' />")
                                     .Title("Title").HtmlAttributes(new { style = "width:30%" });
                             columns.Bound(p => p.MaxPrecision).Title("Decimal Places")
                                     .ClientTemplate("#= MaxPrecision #" +
                                            "<input type='hidden' name='DateFields[#= index(data)#].MaxPrecision' value='#= MaxPrecision #' />");
                             columns.Bound(p => p.IsObsolete).Title("Obsolete")
                                 .ClientTemplate("#= IsObsolete #" +
                                            "<input type='hidden' name='DateFields[#= index(data)#].IsObsolete' value='#= IsObsolete #' />");
                         })
                    .DataSource(datasource => datasource
                        .Ajax()
                        .Model(model =>
                                {
                                    {
                                        model.Id(p => p.Title);
                                        model.Field(p => p.Title).Editable(true);
                                        model.Field(p => p.MaxPrecision).Editable(true);
                                        model.Field(p => p.IsObsolete).Editable(true);
                                    }
                                }
                            )

                        )

                    )

}

A: You can use the toolbar template, like the one demonstrated here.
The template can look something like this:
 <button class="k-button" id="myAdd">My Custom Add</button>

Once the Grid is initialized you can attach click handler which adds the new row based on your condition.
$('#myAdd).click(function(){
   var gr = $('#gridName').data('kendoGrid');
   if(gr.dataSource.data().length<5){
       gr.addRow();
   }
})

The methods used above are all covered in the documentaion.


text:
Q: How to draw attached functions in TikZ How to draw attached functions in TikZ
\begin{tikzpicture}[line width=0.2mm,font=\scriptsize]
\draw[-latex] (-1.5,0) -- (3,0);
\draw[-latex] (0,-1) -- (0,3);
\draw[dashed] (0,2) node[left]{$L$} -| (2,0)node[below]{$a$};
\filldraw (2,2) circle (.05cm);

\begin{scope}[xshift=5.5cm]
\draw[-latex] (-1.5,0) -- (3,0);
\draw[-latex] (0,-1) -- (0,3);
\draw[dashed] (0,2) node[left]{$L$} -| (2,0)node[below]{$a$};
\draw[fill=white] (2,2) circle (.05cm);
\filldraw (2,1.5) circle (.05cm);
\end{scope}

\begin{scope}[xshift=11cm]
\draw[-latex] (-1.5,0) -- (3,0);
\draw[-latex] (0,-1) -- (0,3);
\draw[dashed] (0,1.5) node[left]{$L$} -| (2,0)node[below]{$a$};
\draw[fill=white] (2,1.5) circle (.05cm);
\end{scope}
\end{tikzpicture}

A: One option is to digitize the curves to produce a set of co-ordinates for each function. I used Datathief. You can edit the coordinates to better represent the desired functions. I traced the curves, so they are "as drawn" by the OP.
Then you can do this:
\documentclass{article}
%Adapted from https://tex.stackexchange.com/a/582126/
\usepackage{tikz}
\usetikzlibrary{calc,arrows,hobby}
\begin{document}

\tikzset{
    axis/.style={very thick, ->, >=stealth'},
    important line/.style={thick},
    dashed line/.style={dashed, thick},
    every node/.style={color=black,},
    use Hobby shortcut
}

\begin{tikzpicture}[scale=1.5]
\draw[axis] (-1.5,0)  -- (3,0) node(xline)[right] {$x$};
\draw[axis] (0,-1) -- (0,3) node(yline)[above] {$y$};
\draw[dashed] (0,2) node[left]{$L$} -| (2.25,0)node[below]{$a$};
\draw[orange, ultra thick] (-1.2284, -1.1983) .. (-1.2361, -0.9178) .. (-1.2238, -0.6509) .. (-1.1841, -0.3265) .. (-1.152, -0.0731) .. (-1.0925, 0.1518) .. (-1.0433, 0.3444) .. (-0.9792, 0.5933) .. (-0.8953, 0.8286) .. (-0.8034, 1.0413) .. (-0.7031, 1.2236) .. (-0.5702, 1.3937) .. (-0.4181, 1.558) .. (-0.2403, 1.7172) .. (-0.0467, 1.8311) .. (0.1509, 1.8907) .. (0.345, 1.9109) .. (0.478, 1.8154) .. (0.5706, 1.6688) .. (0.633, 1.5034) .. (0.7085, 1.3316) .. (0.8199, 1.187) .. (0.9546, 1.0682) .. (1.0929, 0.9888) .. (1.2397, 0.9651) .. (1.4025, 0.982) .. (1.5967, 1.0882) .. (1.7516, 1.2137) .. (1.8771, 1.3987) .. (2.0036, 1.5681) .. (2.0858, 1.7407) .. (2.1674, 1.9211) .. (2.2547, 2.1099) .. (2.3403, 2.3219) .. (2.4031, 2.5003) .. (2.4733, 2.6639) .. (2.5733, 2.9399);
\filldraw (2.25,2) circle (.05cm);
\end{tikzpicture}\hspace{1.5cm}%
\begin{tikzpicture}[scale=1.5]
\draw[axis] (-1.0,0)  -- (3,0) node(xline)[right] {$x$};
\draw[axis] (0,-1) -- (0,3) node(yline)[above] {$y$};
\draw[dashed] (0,1.5) node[left]{$L$} -| (1.10,0)node[below]{$a$};
\draw[orange, ultra thick] (-0.8356, 0.6491) .. (-0.826, 0.762) .. (-0.8034, 0.8632) .. (-0.769, 0.9373) .. (-0.7316, 1.0162) .. (-0.6842, 1.1044) .. (-0.6198, 1.1804) .. (-0.5514, 1.23) ..
(-0.4668, 1.2728) .. (-0.3854, 1.3107) .. (-0.303, 1.3174) .. (-0.2168, 1.3237) .. (-0.1126, 1.2867) .. (-0.0206, 1.2043) .. (0.0683, 1.117) .. (0.1518, 1.0407) .. (0.2429, 0.9636)
.. (0.335, 0.8812) .. (0.4161, 0.8466) .. (0.5, 0.8428) .. (0.573, 0.8868) .. (0.615, 0.986) .. (0.6417, 1.0608) .. (0.689, 1.149) .. (0.776, 1.176) .. (0.8629, 1.2029) .. (0.9243, 1.2482)
 .. (0.9788, 1.289) .. (1.014, 1.3577) .. (1.0776, 1.439) .. (1.1203, 1.5588) .. (1.143, 1.66) .. (1.1989, 1.7421) .. (1.2549, 1.7983) .. (1.3326, 1.8107) .. (1.4136, 1.7761)
 .. (1.4656, 1.6824) .. (1.5152, 1.5787) .. (1.5643, 1.4802) .. (1.6354, 1.4104) .. (1.7008, 1.4293) .. (1.7568, 1.4855) .. (1.7795, 1.5607) .. (1.7993, 1.6571) .. (1.8051, 1.7445)
  .. (1.807, 1.8324) .. (1.8189, 1.9296) .. (1.8401, 2.0154) .. (1.8645, 2.0801) .. (1.9013, 2.1384) .. (1.9588, 2.184) .. (2.0196, 2.2086) .. (2.0929, 2.1749) .. (2.1748, 2.1091)
  .. (2.2, 1.9924) .. (2.2174, 1.8765) .. (2.2311, 1.7351) .. (2.2501, 1.6088) .. (2.3038, 1.4787) .. (2.3535, 1.3749) .. (2.4147, 1.2958) .. (2.4821, 1.2005) .. (2.5686, 1.1291) ;
\filldraw (1.10,1.5) circle (.05cm);
\end{tikzpicture}

\end{document}

To get this:


text:
Q: ID3 tagging of remotely stored files Is it possible to change ID3 tags of files that are stored in the cloud (Google Drive, One Drive, Drop Box, etc)?
Ideally, I want to use a Windows MP3 tagging program (like MP3Tag, or similar) to edit ID3 tags of my music/podcast collection on Google drive or One Drive.
Alternatively, an online service like rollApp could do too. But, AFAIK it is only implemented with limited functionality for free users in 4Shared and as such is not of much use.


text:
Q: ImportXML not expanded as would overwrite data on this report I have an IMPORTXML function in Column B which is crawling a URL for the closing date specifically. URLS on column A
It mostly works fine, but on a couple of instance it will retrieve a #REF!, and the reason is stated as "Array result was not expanded because it would overwrite data in B58."
This is happening in Cell B57 currently
anyone know how I can fix this?
Thank you

A: use limit like:
=QUERY(FLATTEN(IMPORTXML(A59, "//*[@id]")),
 "where lower(Col1) starts with 'closing date' limit 1", )


text:
Q: Validate a domain name with GET parameters using a REGEX I am trying to validate if a domain does have GET parameters with preg_match and and a REGEX, which i require it to have for my purposes.
What I have got working is validating a domain without GET parameters like so:
if (preg_match("/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}$/", 'domain.com')) {
        echo 'true';
} else {
        echo 'false';
}

I get true for this test.
So far so good. What I am having trouble with is adding in the GET parameters, Amongst a number of REGEX's I have tried with still no luck is the following:
if (preg_match("/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}([/?].*)?$/", 'domain.com?test=test')) {
        echo 'true';
} else {
        echo 'false';
}

Here i get false returned and hence am not able to validate a domain with GET parameters which are required.
Any assistance will be much appreciated ^^
Regards

A: This code is not tested, but I think it should work:
$pattern = "([a-z0-9-.]*)\.([a-z]{2,3})"; //Host
$pattern .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; //Get requests
if (preg_match($pattern, 'domain.com?test=test')) {
        echo 'true';
} else {
        echo 'false';
}

A: What is the advantage of using a REGEX?
Why not just
<?php
$xGETS = count($_GET);
if(!$xGETS)
{
    echo 'false';
} else {
    echo 'true';
}

// PHP 5.2+

$xGETS = filter_var('http://domain.com?test=test', FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED);
if(!$xGETS)
{
    echo 'false';
} else {
    echo 'true';
}

A: Your first regular expression will reject some valid domain names (e.g. from the museum and travel TLDs and domain names that include upper case letters) and will recognize some invalid domain names (e.g. where a label or the whole domain name is too long).
If this is fine with you, you might just as well search for the first question mark and treat the prefix as domain name and the suffix as "GET parameters" (actually called query string).
If this is not fine with you, a simple regular expression will not suffice to validate domain names, because of the length constraints of domain names and labels.


text:
Q: regex to match a number followed by spaces I'm looking to use reg-ex to split the following string
1 hi my name is John. 2 I live at house 32. 3 I see stars.

to
[hi my name is John,  I live at house 32. , I see stars]

Note that am trying to split on digit followed by a space

A: Split on /(^|\b\s+)\d+\s+/g.
Explanation:

*

*(^|\b\s+) A collection of either ^ or \b\s+)

*

*^ Start of the string OR

*\b\s+ a word boundary  followed by a space/tab repeated 1 or more times

*\d+ A digit between 0 and 9 repeated 1 or more times (so it'd match 1, 12, 123, etc.)

*\s+ A space/tab repeated 1 or more times
Edit:
(^|\.\s+)\d+\s+ might work better for you.

A: Maybe this will do: [0-9]{1}[\ ]

A: Split on:
/\d+ /

Only the first match will be empty because it's the match just before the first number: 1, so you gotta ignore that one.


text:
Q: Exercise in Spivak's Calculus of Manifolds My question is regarding Exercise 1-22, which states:
If U is open and C $\subset$ U is compact, show that there is a compact set D such that C $\subset$ interior D and D $\subset$ U.
I could prove this result assuming U is a subset of Euclidean space. Is my assumption correct? Is this true for general spaces?

A: It holds for every locally compact $T_2$ topological space $(X,\mathcal{T})$ that

If $S \subseteq T \subseteq X$ with $S$ compact and $T$ open, there exists a pre-compact open $V$ with $S \subseteq V \subseteq V^- \subseteq T$.

This is a immediate consequence that $(X,\mathcal{T})$ has a compact local basis. Indeed, for each $x \in S$, there exists a compact neighbourhood $U(x) \ni x$ with $U(x) \subseteq T$. Then $\left(U(x)^\circ\right)_{x \in S}$ forms an open cover of $S$ for which there is a finite sub-cover $(U_j^\circ)_{j=0}^{m-1}$. Define $V = \bigcup_{j=0}^{m-1} U_j^\circ$. Then $S\subseteq V$, and $V^- \subseteq \bigcup_{j=0}^{m-1} U_j$ is a subset of a compact set, and hence compact. Therefore $V$ is pre-compact.


text: Q: In OpenMP is there a way to know if we are inside an omp single region? Is there a way in OpenMP (4.5 and later) to know if we are inside an "omp single" region? For example there is the "omp_in_parallel()" function which checks if we are inside a parallel region. Is there a way to know if we are inside an "omp single" region?


text:
Q: Referral System in IOS? I implement referral system in Android like this way.
https://play.google.com/store/apps/details?id=com.app.poster&referrer=50380

So in my application i get referrer code and use it but i cannot find any way in ios like this.
Can you please tell me anyway so when user click on Specific Link he redirect to AppStore and install application and after install application app get referrer code.
Or any supposed way to do this.
Thanks in advance.

A: You need to use deep links for that and then can achieve the required results. There are multiple tutorials on how to implement Dee-links. You can use Branch.io for that. Here is a tutorial on How to implement deep link using Branch:- https://medium.com/flawless-app-stories/ios-universal-links-and-app-referrals-using-branchio-integration-31dd474be20


text:
Q: What does " A " next to file name in VS Code mean? After typing to my code's terminal git add recoverd_home_pg.dart I see the mark A right after the file name on the VS Code, What does that A mean?

A: It means it is a new file added (A) to your GIT project (or other source control system) but not committed yet. The (M) for the other file means modified so we know this file already are part of the GIT project but have been modified with changes yet to be committed.

A: A is for added to git repo (a new file that has been added to the repository)

A: A -> Added
M -> Modified
D -> Deleted
U -> Untracked
C -> Conflict
R -> Renamed


text:
Q: How do I filter a dataframe by a datetime64 column in pandas using minutes and seconds? I've converted the time column with type 'str' to datetime64:
try:
    heart_rate_seconds['time'] = pd.to_datetime(heart_rate_seconds['time'], format = "%m/%d/%Y %I:%M:%S %p")
except:
    heart_rate_seconds['time'] = pd.to_datetime(heart_rate_seconds['time'], format = "%Y/%m/%d %H:%M:%S")

How do filter the dataframe so that it only contains rows where the time column has minutes and seconds equal to zero?
This is what I've tried:

type(heart_rate_seconds['time'][0])

This displays pandas._libs.tslibs.timestamps.Timestamp

test = heart_rate_seconds['time'][1].second
test

This works

heart_rate_hourly = heart_rate_seconds.loc[heart_rate_seconds['time'].dt.second() == 0
and heart_rate_seconds['time'].dt.minute() == 0]

This gets an error: TypeError: 'Series' object is not callable

heart_rate_hourly = heart_rate_seconds[heart_rate_seconds['time'].dt.strftime("%M") == 0
and heart_rate_seconds['time'].dt.strftime("%S") == 0]

This gets an error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

on_the_hour = []
for time in heart_rate_seconds['time']:
    if time.second == 0 and time.minute == 0:
        on_the_hour.append(time)
on_the_hour[:5]

This works

on_the_hour = []
for row in heart_rate_seconds:
    time = row[1]
    if time.second == 0 and time.minute == 0:
        on_the_hour.append(time)
on_the_hour[:5]

This doesn't work - AttributeError: 'str' object has no attribute 'second'
Thanks

A: you can use the dt accessor to create masks for certain properties. Ex:
import pandas as pd

df = pd.DataFrame({'time': ['01/03/2021 03:30:00 AM', '2021/02/04 13:00:00'],
                   'values': [0, 1]})

# note that pandas automatically infers the format correctly:
df['time'] = pd.to_datetime(df['time'])

# a mask where min and sec are zero:
m = (df['time'].dt.minute == 0) & (df['time'].dt.second == 0)

print(df[m])
#                  time  values
# 1 2021-02-04 13:00:00       1

Note that you do not have to assign the conditionals to a variable to be able to use them - and of course you can also use them within loc.


text:
Q: Yii restful API, how to modify return results from model I followed this tutorial to set up my back end server based on Yii framework and then this tutorial to set up my API and everything is working as it should.
But I am not sure how to accomplish the next step:
My return array right now is pulling records that look like this:
{
 "id": 1,
 "user_id": 1,
 "description": "This is a summary of article 1",
 "status": 2,
 "type": 1,
 "created_at": 1426210780,
 "updated_at": 1426365319
}

The value for 'type' is '1' in the db, but I want to store all the possible values of 'type' in another table like this:
 1 : Red
 2 : Blue
 3 : Green

And then I want the JSON returned via my API to contain "type":'red' instead of "type":1. I assume I need to override something in my Model, but I can't figure out what to override or with what.
I'm happy to read through tutorials or documentation but I'm such a beginner at this that I'm not sure what terms to search for. Thanks for your help!

A: Have a look at models and their relationships to other models, this will allow you to get the information you need.
http://www.yiiframework.com/doc/guide/1.1/en/database.arr
Once the relationship is working correctly you should be able to get the colour from the original model.
Although this is from a earlier version of Yii it may help you understand how the models will interact as well
http://www.yiiframework.com/wiki/285/accessing-data-in-a-join-table-with-the-related-models/

A: @Burrito's response provided documentation but I want to give the full solution for other searchers:
First, I needed to set up a model for 'Type'.
Second, I needed to declare the relationship between 'Report' (my main model) and 'Type' like this (in my Report model):
public function getType()
{
    return $this->hasOne(Type::className(), ['id' => 'type']);
}

(I'm not sure if that step is necessary, but the documentation makes it seem necessary.)
Third, I created getTypeName (in Report model), to get the name of the type based on the ID:
public function getTypeName($type = null)
{
    return Type::findOne($type)->name;
}

Lastly, in my apiController, I modified the function that I am using to get all records to include a loop for each record that called getTypeName:
protected function findAllReports()
{
    // get all reports
    $reports = Report::find()
                ->asArray()
                ->all();

    if( $reports ){
        $i = 0;
        // loop through each report
        foreach($reports as $report){
            $model = new Report();
            // add a new key/value pair to each report array, populate with getTypeName and pass the type ID to it as a parameter
            $reports[$i]['typeName'] = $model->getTypeName($reports[$i]['type']);
            $i++;
        }
        return $reports;
    } else {
       // error or no results
    }
}

For reference, the other routine needed here is the action that the API hits, which calls findAllReports():
public function actionList()
{
    $reports=$this->findAllReports();
    $this->setHeader(200);
    echo json_encode(array('status'=>1,'data'=>$reports),JSON_PRETTY_PRINT);
}

Finally, now if I called [url]/api/list, I get an array of reports, including the typeName.


text:
Q: Charger turns off when laptop have battery in it My E6430 laptop works fine with only charger or only battery. But when I plug charger after inserting the battery the charger turns OFF. But my laptop stay ON on battery. So, I cannot charge my battery.
I have tried the following things:

*

*Used different charger.

*Power button method for static discharge.

*Resetting the BIOS.

A:
laptop works fine with only charger or only battery  ...  Used
different charger.

You need to get the laptop serviced. There is most likely a fault in the charging circuit (inside the laptop) that is causing this issue.

I cannot charge my battery.

Some laptops have charging threshold management software, but this does not appear to be your issue because even with threshold management (I have that here) charging and having a battery installed do not usually conflict as is happening here.


text:
Q: I need to delete an MKLINK /J in Windows 10 18242.1000.180914-1435.RS_PRERELEASE_CLIENTPRO_OEMRET_x64FRE_ES-ES yesterday (Madrid`s time) I've created, using Admin elevated Command Prompt the following two junctions (they´re of course in castilian), in order to try to install the new Office 2019 C2R on P: instead than to C:.
It failed: Office does fails at installing uncompleting install.
Commands used:
MKLINK /J "C:\Program Files\Microsoft Office 15" "P:\Archivos de programa\Ofimática\MS Oficina 2019"

MKLINK /J "C:\Program Files\Microsoft Office" "P:\Archivos de programa\Ofimática\MS Oficina 2019"

Now I'm trying all the way to remove the junction; I also entered, from the Admin elevated Command Prompt the P:\Archivos de programa\Ofimática directory, but both RD and rmdir return me a reply that ¨The system cant find the speficied file¨ when its still visible in Windows Explorer (refreshed with F5).
Whats is supposed have I to do to eliminate that MKLINK /J command I gave?
Any real working trick is welcome.

A: I believe the main issue here lies in the wording

"in order to try to install the new Office 2019 C2R on P: instead than
  to C:"

As LPChip correctly points out (implicitly, I'm afraid) you have created the link on C: not on P: as you desired. The mklink command on windows behaves rather 'backwards' compared to the instinctive notion of "source" "destination" one is used to. (And in Linux' ln command.)

*

*On windows it's mklink /J linkto linksource

*On Linux (*ux?) it's ln -s linksource linkto
Which is the intuitive one (opinion?). I here treat JUNCTION like symbolic links, which should be good enough in this setting.
My guess to what happened here is that you created an invalid (pointer created but nothing to resolv to) JUNCTION (or symlink if you want to call it that) that later got populated on Office Install so that it got resolvable (populated).
With this in mind you may even want to try reinstalling Office this way, although it may be safer to use the Registry modification of the ProgramFilesDir entries. I HATE it when apps don't give the option of choosing the install location. "Let's fill up your SSD" kind of (lack of) thinking. (Rantmode off.)


text:
Q: Proving spanning trees contain all pendant edges. Illustrate and prove that each spanning tree of a connected graph G contains all the pendant edges of G.
I already know how to illustrate, however can't prove. It says I need to use contradiction. Please help.

A: Take some vertex $x$ that has only one neighbor $y$ in $G$, and let $T$ be a spanning tree of $G$.  Recall that $V(T) = V(G)$ and $E(T) \subseteq E(G)$, by definition.  In particular, $x \in V(T)$.
Suppose now that the edge $xy$ does not belong to $T$.  Since $T$ is connected, $x$ must have at least one neighbor $w$ on $T$, and so $xw \in E(T)$.
Can you finish the rest?


text:
Q: What causes electromagnetic waves to propagate in free space? In free space, $\rho=0$ and $J=0$, so there are no electromagnetic sources/sinks. Maxwell's equations thus reduce to:
$\nabla\cdot E = 0$
$\nabla\cdot B = 0$
$\nabla\times E = -\frac{\partial B}{\partial t}$
$\nabla\times B = \mu_0\epsilon_0 \frac{\partial E}{\partial t} $
Suppose I was writing a simple simulation to visualize the electromagnetic field in free space. I have seen people talk about waves propagating in free space, and I know that there is no such thing as electromagnetic waves being created from nothing -- it is usually assumed that such electromagnetic waves propagating in free space are plane waves that originated in a charged source extremely far away.
However, when I actually implement the "oscillation" in the EM field, where does that oscillation come from -- speaking practically from a coding point of view? Do you just hardwire, e.g., a sinusoidal source at the location you are interested in probing the EM field?
And if there were no such "magical" waves propagating in free space, would the EM field just remain smooth, without any oscillations, vibrations, sinusoids, etc.? In other words, can you have a completely stationary electromagnetic field, or would the last two of Maxwell's equations above prevent such stationary EM fields? But then what, in free space, would cause the initial change in the electric or magnetic field to get the oscillations going?
To put it one last way: suppose I wrote a simulation involving the 4 Maxwell's equations above (free space). Would the EM field be stationary for all time, and the only way a propagating wave would appear is if I perturbed, say, the electric field which activated a never-ending loop of the curl equations? So if the initial values of E and B were both 0 in my simulation, then they would stay 0 for all time. But if one or both initial values of E and B were non-zero, then the curl equations would be "activated" and result in a never-ending loop of oscillations?

A: I think the answer is simply: "Yes".
What you should keep in mind is energy conservation: As long as there are no sources, the total energy of the electromagnetic field is conserved.

But then what, in free space, would cause the initial change in the electric or magnetic field to get the oscillations going?

A source, which is possibly localized somewhere and not necessarily non-zero at all times.

A: The question "What causes electromagnetic waves to propagate in free space?" is essentially the same as asking why do electromagnetic waves exist. For that matter, why do electrons exist or why does anything exist at all? Rather than digressing into philosophy, let us focus on physics. We should remind ourselves about how profound the concept of a field is. This concept originates from Michael Faraday. A field assigns a number or tensor to each point in space. In other words, a field is a property of space itself. When a field has the lowest possible value, we call it a vacuum. Empty space is not nothingness. "Empty" space has structure. In fact, very rich structure. In the case of electromagnetic fields, this structure is described by Maxwell's equations. An electromagnetic wave is literally a property of space (with time dependence). Let us suppose that the fields of electromagnetism are disturbed. A disturbance could, for instance, be caused by an electron colliding with an atom. The fields (more properly, a single field called $A_\mu$) has a precise response to this event. A disturbance of the field propagates outward at the speed of light from the location of the event. The disturbance is described by Maxwell's equations. In other words, space itself has a structure that we perceive as an electromagnetic wave. Once the electromagnetic wave is created, there is no need for sources.
This is more or less a simplified viewpoint of modern physics. All fundamental particles are quantized excitations of different fields. The electron is a quantized excitation of the electron field. A quark is a quantized excitation of a quark field and so forth for all the other particles. Different fields correspond to different properties of space. All matter, energy and fundamental forces are quite literally properties of space itself. All of physical existence is derived from space. Fields are indeed profound!


text:
Q: Excel: Separate text in cell I am trying to seperate a field into two by finding the values that are in the left of an asterisk and then what's on the right.
For example
Cell C1 is 0A*33 then C2 should be 0A and C3 should be 33.
I have the following formulas in cells C2 and C3:
=LEFT(C1,SEARCH("~*",C1,1)-1)
=RIGHT(C1,LEN(A3)-SEARCH("~*",C1,1))
These formulas work great as long as there is a asterisk in the cell, if not it results in a #VALUE! error.
I have even tried (For the left side) =LEFT(C1,IF(ISERROR(SEARCH("~*",C1,1)-1),C1,SEARCH("~*",C1,1)-1)) with the same outcome.
If the cell does not have an asterisk it must return the whole value in C2 and nothing in cell C3.

A: Have you tried:
In C2:
=IF(ISERROR(FIND("*",C1)),C1,LEFT(C1,FIND("*",C1)-1))

In C3:
=IF(ISERROR(FIND("*",C1)),"",RIGHT(C1,LEN(C1)-FIND("*",C1)))

You could use the same idea with SEARCH, but FIND works fine in this case:
In C2:
=IF(ISERROR(SEARCH("~*",C1,1)),C1,LEFT(C1,SEARCH("~*",C1,1)-1))

In C3:
=IF(ISERROR(SEARCH("~*",C1,1)),"",RIGHT(C1,LEN(C1)-SEARCH("~*",C1,1)))

A: =LEFT(C1,FIND("*",C1&"*")-1)
=MID(C1,FIND("*",C1&"*")+1,255)


text:
Q: In Excel, how to scan for Duplicate in Column A. Place info in another sheet Here is my issue.  I have a WorkSheet Named Cost Data
In Column A which is named HEITEM
I have for example
7658798
7513807
789456
7513807
Note:7513807 is a duplicate
In Columns B - AG I have data needed for those in Column A that is a duplicate.
My question would be. How do I Scan the worksheet named Cost Data and move all instances of a duplicate in Column A to a new worksheet while showing all relevant data in Cells to the right?

A: The easiest way would be to add in a new column before column A (move all columns to the right) and in your new column put in cell A2 (assuming you have a header row) the formula:
=COUNTIF(B:B,B2)

And drag it down fo rthe entire column.
You can then filter this new column A for all values not equal to 1 and then Copy / Paste it to your new workbook and remove duplicates (Data Ribbon > Remove Duplicates).
Of course there are countless other ways to do this, but this seems like a simple solution.
Hope this makes snese.


text:
Q: Does Excel have a built in method for parsing formulas? (ie: to obtain a list of included RANGE references) For a given Excel formula in a cell, I'd like to be able to parse the formula in order to get a list of Excel Range references contained within the formula.
For example, if I have a cell with this formula:
= A + 25 + B

....I would like to be able to get an array of excel ranges contained within the formula, so in this case, it would contain [A] and [B]
"Why do you even want to do this"?, I can hear you asking:
Just one example of why I want to do this is to look up "labels" for ranges in formulas.....so, as opposed to just doing a CTRL+~ to view the formulas in my sheet, I'd like the option of programatically accessing the range references within the formula in order to do a lookup of the label beside the target range.
So, in my above example, I could then write formulas something like:
=Offset(CellFormulaRanges('TheAddressMyFormulaIsIn',1),0,-1)
=Offset(CellFormulaRanges('TheAddressMyFormulaIsIn',2),0,-1)

...which would give me the the label to the left of the 1st and 2nd ranges within the formula.
Doing this would have to call upon some functionality already within Excel itself, as hand writing a formula parser is a complicated task:
http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html

A: Thanks to @TimWilliams and @brettdj for pointing me in the right direction to previous discussions on this topic, I can confidently say:
NO, EXCEL DOES NOT HAVE A METHOD FOR PARSING.
However, for my fairly minimal purposes, I've come up with something that works, works with cross worksheet references, and can be called from a UDF.
However, it is extremely brittle, and there are multitudes of perfectly legitimate formulas that I'm certain it wouldn't handle properly.
The code is a mess and could be greatly improved but I just wanted to throw it up on here as I'm moving onto to something else for the time being....
EDIT
Also found this, which looks very interesting:
http://www.dailydoseofexcel.com/archives/2009/12/05/formula-tokenizer/
Public Function CellPrecedents(cell As Range) As Variant()
    Dim resultRanges As New Collection
    If cell.Cells.count <> 1 Then GoTo exit_CellPrecedents
    If cell.HasFormula = False Then GoTo exit_CellPrecedents

    Dim formula As String
    formula = Mid(cell.formula, 2, Len(cell.formula) - 1)

    If IsRange(formula) Then
        resultRanges.Add Range(formula), 1
    Else
        Dim elements() As String
        'Debug.Print formula & " --> "
        formula = Replace(formula, "(", "")
        formula = Replace(formula, ")", "")
        'Debug.Print formula & " --> "
        elements() = SplitMultiDelims(formula, "+-*/\^")
        Dim n As Long, count As Integer
        For n = LBound(elements) To UBound(elements)
            If IsRange(elements(n)) Then
                'ACTUALLY JUST DO A REDIM PRESERVE HERE!!!!
                count = count + 1
                'resultRanges.Add Range(Trim(elements(n)))  '<---  Do **NOT** store as a range, as that gets automatically Eval()'d
                resultRanges.Add Trim(elements(n))
            End If
        Next
    End If

    Dim resultRangeArray() As Variant
    ReDim resultRangeArray(resultRanges.count)
    Dim i As Integer
    For i = 1 To resultRanges.count
        resultRangeArray(i) = CStr(resultRanges(i))  '// have to store as a string so Eval() doesn't get invoked (I think??)
    Next

    CellPrecedents = resultRangeArray

exit_CellPrecedents:
    Exit Function
End Function

Public Function IsRange(var As Variant) As Boolean
    On Error Resume Next
    Dim rng As Range: Set rng = Range(var)
    If err.Number = 0 Then IsRange = True
End Function

(just google SplitMultiDelims for that function)

A: Tbone, One other option that is not directly what you asked for but could work as alternative solution.
Rather than using a formula to try and find the corrosponding label, Try adjusting your formulas to work for you. Here are a couple of options depending on what the formula you were trying to parse is.
1. If your formula is a lookup you could just offset to look to the left.
2. Alternatively you could use the "Indirect" function in both formulas to ensure they are referencing the correct location.

A: In short, I think you want to do subpart of : Use VBA to generate code to reproduce basic calculations on an Excel worksheet, and using a function to return n'th DirectPrecedents collection element address or name.
source: http://www.vb-helper.com/howto_vba_excel_formulas.html
This use case however has been deprecated. As of Excel 2007 tables allow a much better solution.


text:
Q: Как динамично отображать директивы на angularJS? <body>
<login-content></login-content>
<main-content></main-content>
</body>

сейчас тупо присутствуют на странице оба html-шаблона, но как сделать так, чтобы можно было по клику подгружать, например , заменив и чтобы angular сразу все распарсил и без ошибки отработал?


text:
Q: Not recognized valid date date time Need to convert 08-13-2022 10:27 PM to 08/12/2022.
This is my code:
 DateTime date = DateTime.Parse(String.Format("MM/dd/yyyy", row["POSTING_DATE"]));
 row["POSTING_DATE"] = Convert.ToDateTime(date);

But I get this error:

not recognized valid date date time

A: You can use the DateTime.ParseExact method as follows:
string POSTING_DATE = "08-13-2022 10:27 PM";
DateTime date = DateTime.ParseExact(POSTING_DATE, "MM-dd-yyyy hh:mm tt",  System.Globalization.CultureInfo.InvariantCulture);
POSTING_DATE = date.ToString("MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(POSTING_DATE);//prints 08/13/2022


text:
Q: How to create new 'folder' in s3 from browser Basically I have a PHP crud system. When I add a new php record, I would also like to make API post to bucket to create a new folder and somehow associate that new folder to that record. This way, when I search that record I can then list objects for that record from that specific folder. How do I create this folder?

A: You don't need to create a folder.
Folders do not actually exist in Amazon S3. Instead, the filename (Key) of an object contains the full path, including the filename of the object.
This means you could copy a file like this, even if the folders do not exist:
aws s3 cp foo.txt s3://my-bucket/one/two/foo.txt

To make things "appear" like a normal filesystem, the Amazon S3 management console will show one and two as folders, but they don't actually exist. In fact, if you to run this command:
aws s3 rm s3://my-bucket/one/two/foo.txt

This would not only delete the object, but the "folders" would also disappear, since they never existed in the first place.
The management console also makes it possible to "create" a folder, but it really just creates a zero-length object with the name (including full path) of the folder. This allows an "empty folder" to appear in the console (even though it doesn't exist).
So, if your application wishes to associate a "folder" with a record, it merely needs to associate the path with the record. There is on need to actually create the folder. Then, create files with that path as a prefix and they will appear to be in the folder but the reality is their filename (Key) includes both the path and the filename.
Your application can call S3 and ask for a list of objects for a given prefix, and only the objects in that "folder" (prefix) will be returned.


text:
Q: Google Composer - Airflow: My tasks are not scheduled I am using Airflow and Cloud Composer and as I have some issues with Airflow Scheduler (it is slow or stops)
Version: composer-1.10.4-airflow-1.10.6
I launched a "huge" collect (because I will sometimes need it) with airflow to test the scalability of my pipelines.
The result is that my scheduler apparently only schedule the DAGs with few tasks, and the tasks of the big DAGs are not scheduled. Do you have insights or advices about that?
Here are information about my current configuration:
Cluster config:

*

*10 Cluster nodes, 20 vCPUs, 160Go Memory

airflow config:
core

*

*store_serialized_dags: True

*dag_concurrency: 160

*store_dag_code: True

*min_file_process_interval: 30

*max_active_runs_per_dag: 1

*dagbag_import_timeout: 900

*min_serialized_dag_update_interval: 30

*parallelism: 160

scheduler

*

*processor_poll_interval: 1

*max_threads: 8

*dag_dir_list_interval: 30

celery

*

*worker_concurrency: 16

webserver

*

*default_dag_run_display_number: 5

*workers: 2

*worker_refresh_interval: 120

airflow scheduler DagBag parsing (airflow list_dags -r):
DagBag loading stats for /home/airflow/gcs/dags
Number of DAGs: 27
Total task number: 32229
DagBag parsing time: 22.468404
---------------+--------------------+---------+----------+-----------------------

file           | duration           | dag_num | task_num | dags

---------------+--------------------+---------+----------+-----------------------

/folder__dags/dag1  | 1.83547                       |       1 |     1554 | dag1

/folder__dags/dag2  | 1.717692                     |       1 |     3872 | dag2

/folder__dags/dag3  | 1.53                             |       1 |     3872 | dag3

/folder__dags/dag4  | 1.391314                     |       1 |      210 | dag4

/folder__dags/dag5  | 1.267788                     |       1 |     3872 | dag5

/folder__dags/dag6  | 1.250022                     |       1 |     1554 | dag6

/folder__dags/dag7  | 1.0973419999999998           |       1 |     2904 | dag7

/folder__dags/dag8  | 1.081566                     |       1 |     3146 | dag8

/folder__dags/dag9  | 1.019032                     |       1 |     3872 | dag9

/folder__dags/dag10 | 0.98541                      |       1 |     1554 | dag10

/folder__dags/dag11 | 0.959722                    |       1 |      160 | dag11

/folder__dags/dag12 | 0.868756                    |       1 |     2904 | dag12

/folder__dags/dag13 | 0.81513                      |       1 |      160 | dag13

/folder__dags/dag14 | 0.69578                      |       1 |       14 | dag14

/folder__dags/dag15 | 0.617646                    |       1 |      294 | dag15

/folder__dags/dag16 | 0.588876                    |       1 |      210 | dag16

/folder__dags/dag17 | 0.563712                    |       1 |      160 | dag17

/folder__dags/dag18 | 0.55615                      |       1 |      726 | dag18

/folder__dags/dag19 | 0.553248                    |       1 |      140 | dag19

/folder__dags/dag20 | 0.55149                      |       1 |      168 | dag20

/folder__dags/dag21 | 0.543682                    |       1 |      168 | dag21

/folder__dags/dag22 | 0.530684                    |       1 |      168 | dag22

/folder__dags/dag23 | 0.498442                    |       1 |      484 | dag23

/folder__dags/dag24 | 0.46574                      |       1 |       14 | dag24

/folder__dags/dag25 | 0.454656                    |       1 |       28 | dag25

/create_conf        | 0.022272                          |       1 |       20 | create_conf

/airflow_monitoring | 0.006782                       |       1 |        1 | airflow_monitoring

---------------+--------------------+---------+----------+------------------------

Thank you for your help

A: Airflow scheduler processes files in the DAGs directory in round-robin scheduling algorithm and this can cause long delays between tasks because the scheduler will not be able to enqueue a task whose dependencies recently completed until its round robin returns to the enclosing DAG's module. Multiple DAG objects can be defined in the same Python module, but this is generally discouraged from a fault isolation perspective. It may be necessary to define multiple DAGs per module.

*

*Sometimes the best approach is to restart the scheduler:

*

*Get cluster credentials as described in official documentation

*Run the following command to restart the scheduler:

kubectl get deployment airflow-scheduler -o yaml | kubectl replace --force -f -
Additionally, please restart the Airflow web server. Sometimes broken, invalid or resource intensive DAGs can cause webserver crashes, restarts or complete downtime. Once way to do so is remove or upgrade one of the PyPI packages from your environment.

*

*Exceeding API usage limits/quotas
To avoid exceeding API usage limits/quotas or avoid running too many simultaneous processes, you can define Airflow pools in the Airflow web UI and associate tasks with existing pools in your DAGs. Refer to the Airflow documentation.

*

*Check the logs in Logging section -> Cloud Composer Environment and look for any errors or warnings like: cannot import module, DagNotFound in DagModel.

Please, have a look to my earlier answer regarding memory. Referring to the official documentation:

DAG execution is RAM limited. Each task execution starts with two
  Airflow processes: task execution and monitoring. Currently, each node
  can take up to 6 concurrent tasks. More memory can be consumed,
  depending on the size of the DAG.

Moreover, I would like to share with you an interesting article on Medium, regarding calculations for resource requests.
I hope you find the above pieces of information useful.


text:
Q: kotlin - which/how a collection able to store multiple data type? I have two different data class, eg:
Guitar & Piano.
I wanna create a list to store both data class, eg: instruments,
so that I can add both dataclass into list by:
instruments.add(Guitar())
instruments.add(Piano())

I thinking about using:
val instruments = arrayListOf<Any>()

My question is it any better way to achieve this?

A: Kotlin does not support multi-typing. However, you can apply workarounds.
First, to help modeling your problem, you could create a super type (interface or abstract class) as suggested in comments, to extract common properties, or just have a "marker" interface. It allows to narrow accepted objects to a certain category, and improve control.
Anyhow, you can filter any list to get back only values of wanted type using filterIsInstance :
enum class InstrumentFamily {
    Strings, Keyboards, Winds, Percussions
}

abstract class Instrument(val family : InstrumentFamily)

data class Guitar(val stringCount : Int) : Instrument(InstrumentFamily.Strings)

data class Piano(val year: Int) : Instrument(InstrumentFamily.Keyboards)

fun main() {
    val mix = listOf(Guitar(6), Piano(1960), null, Guitar(7), Piano(2010))

    val guitars: List<Guitar> = mix.filterIsInstance<Guitar>()
    guitars.forEach { println(it) }

    val pianos : List<Piano> = mix.filterIsInstance<Piano>()
    pianos.forEach { println(it) }
}

However, beware that this operator will scan all list, so it can become slow if used with large lists or many times. So, don't rely on it too much.
Another workaround would be to create an index per type, and use sealed classes to ensure full control over possible types (but therefore, you'll lose extensibility capabilities).
Exemple :
import kotlin.reflect.KClass

enum class InstrumentFamily {
    Strings, Keyboards, Winds, Percussions
}

sealed class Instrument(val family : InstrumentFamily)

data class Guitar(val stringCount : Int) : Instrument(InstrumentFamily.Strings)

data class Piano(val year: Int) : Instrument(InstrumentFamily.Keyboards)

/** Custom mapping by value type */
class InstrumentContainer(private val valuesByType : MutableMap<KClass<out Instrument>, List<Instrument>> = mutableMapOf()) : Map<KClass<out Instrument>, List<Instrument>> by valuesByType {
    /** When receiving an instrument, store it in a sublist specialized for its type */
    fun add(instrument: Instrument) {
        valuesByType.merge(instrument::class, listOf(instrument)) { l1, l2 -> l1 + l2}
    }

    /** Retrieve all objects stored for a given subtype */
    inline fun <reified I :Instrument> get() = get(I::class) as List<out I>
}

fun main() {
    val mix = listOf(Guitar(6), Piano(1960), null, Guitar(7), Piano(2010))

    val container = InstrumentContainer()
    mix.forEach { if (it != null) container.add(it) }

    container.get<Guitar>().forEach { println(it) }
}


text:
Q: Best practice to include (standalone precompiled) graphics General understanding
I know that several people have asked about how to include plots and graphics (created by tikz and pstricks) into a latex document.

*

*What is the best way to include Matlab graphics?

*Including pictures in subdirectories with standalone package

*Is EPS or PDF the preferred figure format when typesetting in LaTeX?

*How can I use TikZ to make standalone (SVG) graphics?
Now it seems evident to ask how to handle a big number of figures.
At first it seems crucial to pre-compile graphics that should enter the document to reduce the final document's compilation time.
But there are many different ways to perform that issue and actually the package standalone seems the most auspicious.
By trying it, I recognized that all standalone tex-files have to be in the same folder to be compiled if changes were performed. Otherwise it would result in errors (Including pictures in subdirectories with standalone package).
Question
How do I now include graphics like the following MWE (adapted from matlab2tikz for including my macros), in order to have the same common formatting (e.g. font size and shape) for all text in my document including the figure labels?
MWE
\documentclass{article}
\input{Style/macros.tex}
\usepackage{standalone}
\standaloneconfig{mode=buildnew}

\usepackage{filecontents}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% File Style/macros.tex
\begin{filecontents*}{Style/macros.tex}
  \fontsize{10}{12}
\end{filecontents*}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% File Documents/test_standalone_slave.tex
\begin{filecontents*}{Documents/test_standalone_slave.tex}
  \documentclass{standalone}
  \input{../Style/macros.tex}
  \usepackage{tikz,pgfplots}
  \pgfplotsset{compat=newest}

  \begin{document}
  \begin{tikzpicture}
  \draw (0,0) circle (2);
  \end{tikzpicture}
  \end{document}
  \endinput
\end{filecontents*}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage{tikz,pgfplots}
\pgfplotsset{compat=newest}

\begin{document}
This is my MWE!
\includestandalone{Documents/test_standalone_slave}
\end{document}

A: If I were you, I would do the following:

*

*In order to make your common settings accessible for all figures, diagrams, documents, etc, put the settings into a single package, namely, mycommon.sty. Register this package globally so you can use it throughout your projects. If you don't know how to do this, see my answer here (click).

*If you want your diagram or figures  to be accessible for other projects,  put them in a separate directory that is higher than the project directories. For example,
<any directory>\Diagrams\
<any directory>\Diagrams\Projects\Project-01\
<any directory>\Diagrams\Projects\Project-02\

*To get a tight drawing for each diagram, use standalone document class as follows
\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{mycommon}
\begin{document}
% your drawing code goes here...
\end{document}

Also load your package for common settings.

*Compile each diagram with the appropriate compilers to get a PDF version. It will save a lot of your time when compiling the main input file of your projects.

*Import the PDF diagrams  from within the main input file of your projects. And compile the main input file with pdflatex (recommended because it is fully supported by microtype package). You may also load the mycommon package if necessary.
\includegraphics from graphicx will do the job of importing diagrams. You can set \graphicspath{{../../Diagrams/}} to shorten your path when invoking \includegraphics.


text:
Q: Laravel 8.x Tailwind Prefix Tailwind allows prefix to be set in tailwind.config.js.
Reference here.
I'm working on a Laravel project that uses Bootstrap and Tailwind simultaneously, managed by npm. I've set a prefix "tw-" for Tailwind to prevent classes colliding.
However, Laravel 8.x uses Tailwind by default unless set to use Bootstrap. Reference here.
Is there any way to let Laravel know about the Tailwind prefix that I set so that it uses the correct Tailwind class names?
Thanks in advance!

A: I wonder if it's truly necessary to use both tools for css.
Anyways I'm not entirely sure how you're loading the pagination, but you also have the ability to create your own (custom) pagination view.
By running the following code:
php artisan vendor:publish --tag=laravel-pagination

This command will place the views in your application's resources/views/vendor/pagination directory. The tailwind.blade.php file within this directory corresponds to the default pagination view. You may edit this file to modify the pagination HTML.
It might suite your needs a lot more to be able to have the pagination view file customized. Because with this you can recreate the pagination using Tailwind (or Bootstrap) classes.


text:
Q: Typescript: in operator not asserting type I have an object a that only contains a subset of the keys defined in type B. I then have a variable d of type B. I want to extract the value for key d from a in case it exists there.
const a = {x: 'c'}
type B = 'x' | 'y'

const example = (d: B) => {
  let e: string
  if (d in a) e = a[d]
}

But Typescript will complain with error 7027 on a[d]:

Element implicitly has an 'any' type because expression of type 'B' can't be used to index type '{ x: string; }'.
Property 'y' does not exist on type '{ x: string; }'

It seems that the compiler is blind to the check d in a.
Why? And what's the best way to solve this?


text:
Q: how to make expanding view with autolayout? (I don't know english well). I have a question: can you show an example of my problem. I want to make expanding list. i.e. i have a controller view and when I click on one of strings there appears a list with data of this strong under it, and other string shift below.

A: You can achieve this with an additional(!) constraint for the height, by which you can set the view's height to zero:

*

*Define this constraint in the storyboard (or code).

*Create an outlet property to the constraint. This must be a strong property because of deactivating a constraint will remove it from the corresponding views.

*Give this constraint the highest priority. Other constraints which influence the hight should have smaller priorities.

*You can now hide and show the view by activating and deactivating the constraint.

Animation of the change can be done with UIKit animations:
UIView *theView = self.view; // Must be a parent of the animated view

self.heightConstraint.active = isHidden;
[UIView animateWithDuration:0.25 animations:^{
    [theView layoutIfNeeded];
}


text:
Q: How to check if a key exists in an inner dictionary inside a dictionary in python? There is a python dictionary:
a = {b:{c:{"x":1, "y":2, "z":3}}}

I want to know if a[b][c]["z"] exists,
but yet I don't know if a[b][c] or a[b] exist either.
So, if I do:
if "z" in a[b][c]:

I may get a "key c doesn't exist in a[b]" or "key b doesn't exist in a" error.
How to properly check if z exists in a[b][c] in this case?

A: The python way is not to bother with the check at all.
try:

    value = a[b][c]["z"]
    # do something with value

except KeyError:
    print 'Sorry wrong key'

here any combination of a,b,"z" maybe missing from the dictionary but they will all be caught by the exception handler. OTH, the situation where the exact key exists will result in the rest of your code being executed.
You might also want to consider using defaultdict

The first argument provides the initial value for the default_factory
  attribute; it defaults to None. All remaining arguments are treated
  the same as if they were passed to the dict constructor, including
  keyword arguments.

This gives you the assurance that notation like a[b][c]["z"] will always execute with out errors and maybe useful in some situations, particularly where you are trying to avoid boilerplatish code.

A: IF you can't use an exception for some reason (eg. lambda func, list comprehension, generator expression etc)
value = a.get(b, {}).get(c, {}).get("z", None)

But normally you should prefer to use the exception handler

A: Why don't you use your own function, it gives you flexibility, Recursion!
def _finditem(obj, key):
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = _finditem(v, key)
            if item is not None:
                return item

Of course, that will fail if you have None values in any of your dictionaries. In that case, you could set up a sentinel object() for this function and return that in the case that you don't find anything -- Then you can check against the sentinel to know if you found something or not.


text:
Q: How to return a string (or JSON object) from a TypeScript function? The following TypeScript function will retrieve data from a web API and display it to the console from within the function, but when I try to return the data object (a string) I get an error.  I am trying to return the JSON data object by return data; but the compiler thinks I am not returning anything.  Please, what am I doing wrong?
async function main(url: string, query: string): Promise<string> {

  const axios = require('axios');
  axios.get(url, {params: {"query": query}})
  .then(function (response: any) {
    let data = JSON.stringify(response.data);
    console.log("data: " + data);
    return data;
  })
  .catch(function (error: any) {
    console.log(error);
    return "error";
  });

}

var url: string = 'https://api.subquery.network/sq/AcalaNetwork/karura-tokens';
var query = "{accountBalances (first: 5) {nodes{id accountId tokenId total}}}"
var res = main(url, query).catch(e => console.error(e)).finally(() => process.exit(0))
console.log("res:" + res);

Here is the output:
src/index.ts:1:50 - error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

1 async function main(url: string, query: string): Promise<string> {

In my example I am trying to return a string, but I am happy returning either a string or a JSON object. I just can't get either one to work.

A: One possible solution (a bit hacky) is to return the promise from your function, declare your res variable in the global scope and, in the promise callback, assign the value the promise resolves to res.
But the actual assignment will only happen after the promise resolves, so you might set a timeout to use the variable outside the promise callback.
For example:
function get_sq(url: string, query: string): Promise<any>{
  const axios = require('axios');
  return axios.get(url, {params: {"query": query}});
}

var url: string = 'https://api.subquery.network/sq/AcalaNetwork/karura-tokens';
var query = "{accountBalances (first: 5) {nodes{id accountId tokenId total}}}"
var res;

get_sq(url, query).then(function (response: any) {
  res = JSON.stringify(response.data);
}).catch(function (error: any) {
  res = error;
});

setTimeout(() => {console.log("res:" + res);}, 3000);

Another possibility (the more robust one) is to keep inside the promise callback and do what you want to do with res there.


text:
Q: Getting code back from APK file generated by Unity Before reporting as duplicate, please read the question!
Today I was decided to try get code from already compiled android application created in Unity engine. I found that in some apps is file Assembly-CSharp.dll (in /assets/bin/Data/Managed) where is practically all code, but in some apps there is only some symbols files. What are these files and how to get that code when there is no .dll files?


text:
Q: Recuperar Cookies em autenticação com Spring Security Como posso recuperar os cookies quando o usuário efetuar o login através do Spring Security e com a implementação da interface AuthenticationProvider? Se eu recuperar uma instância de HttpServletRequest a partir de uma classe com controladora tenho acesso aos Cookies, porém se fazer dessa forma retorna null o atributo com os Cookies:
Obs: Tenho os Cookies setados, são exibidos no DevTools do Chrome.
Código:
@Component
public class LoginAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        /* Aqui tento recuperar os cookies */
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        /* Aqui tento recuperar os cookies */

        String username =  authentication.getName().toString();
        String password = (String) authentication.getCredentials();

        if (! AuthenticationConvert.validaSchema(username)) {
            throw new SchemaNotFoundException();
        }

        SecurityContextHolder.getContext().setAuthentication(authentication);

        Usuario usuario = usuarioService.findUsuario(AuthenticationConvert.getLogin(authentication.getName().toString()));

        if (usuario == null)
            throw new UsernameNotFoundException("Usuário não encontrado.");

        if (! usuario.getSenha().equalsIgnoreCase(password))
            throw new BadCredentialsException("Senha incorreta.");

        return new UsernamePasswordAuthenticationToken(username, password, null);
    }

}

Imagem:

Existe outra maneira para recuperar os cookies a partir de uma autenticação? Qual?

A: É possivel recuperar com uma annotation, realizando binding atravez de um parametro.
public void metodo(@CookieValue("nome") String cookie) {

}

Para adicionar é preciso de um HttpServletResponse
public void metodo2(HttpServletResponse response) {
   Cookie cookie = new Cookie("chave", "valor");
   //configurações do cookie
   response.addCookie(cookie);
}

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-cookievalue
http://viralpatel.net/blogs/spring-mvc-cookie-example/


text:
Q: Setup a Oracle JDBC provider in Websphere 8.0.0.13 We are trying to set up a JNDI (oracle database) on a Websphere Application Server version 8.0.0.13. Running Java 1.6.0:
WebSphere Platform 8.0.0.13 [BASE 8.0.0.13 cf131705.01] running with process name pandora-vmNode01Cell\Aplicacion-node\server1 and process id 5230
Host Operating System is Linux, version 3.13.0-133-generic
Java version = 1.6.0, Java Compiler = j9jit26, Java VM name = IBM J9 VM

I downloaded the ojdbc6.jar from maven and oracle servers and we created a JDBC provider that uses that jar file. And We tried to configure the Datasource with that JDBC provider. But, when we test the connection this error appears:
The test connection operation failed for data source XXXXX_oracle on server
server1 at node Aplicacion-node with the following exception:
java.sql.SQLException: java.lang.UnsupportedClassVersionError: JVMCFRE003 bad
major version; class=oracle/jdbc/pool/OracleConnectionPoolDataSource,
offset=6. View JVM logs for further details.

What can be happening?
We are using the correct ojdbc file because the server is running the same SDK version.
Thank you in advance.

A: As you've said, the ojdbc6 jar should be compatible with Java 6, so maybe a different version Oracle JDBC driver is actually being used.  Is there a different copy of the Oracle JDBC driver present in the app or WebSphere configuration? If so that version, which may require higher than Java 6, could be loaded rather than the ojdbc6 driver you've configured.

*

*Check that there are no additional Oracle JDBC drivers packaged with your application.

*Check if there are other Oracle JDBC Providers configured in WebSphere using a newer JDBC driver. If so either modify your configuration so all of your providers are using the same version Oracle JDBC driver or you will need to Isolate your JDBC Providers.

Also, friendly reminder that both WebSphere 8.0 and Java 6 are out of support, so if possible you should migrate to a newer version of both.


text:
Q: Android MultiAutoCompleteTextView I need to show the list of friends when the user types a letter in Edittext like Twitter.I have tried with MultiAutoCompleteTextView and it works fine if the arraylist is loaded before user starts entering.But I need to make a server call to get the friends having the name starts with the types character.But after getting the api response the dropdown is not showing.How can I implement this.Please help me.

A: Thank you psknik.Solution is
CharSequence constraint = actv.getText();
        adapter.getFilter().filter(constraint);
        actv.showDropDown();


text:
Q: Having issues with Javascript dice game I'm trying to get one button to fire two functions. It's a basic dice based game: the player die on top works fine, but the computer die doesn't give a value.

function Welcome()
{
        alert("Welcome " + document.getElementById("fname").value + "!");
}

function oldEnough(age)
{
        if (age< 18)
        {alert("UNDER 18 LEAVE NOW");
        }
}

//player dice roll//
function rollDice() {
        var die1 = document.getElementById("die1");
        var die2 = document.getElementById("die2");
        var status = document.getElementById("status");
        //random number between 1 and 6(whole number)//
        var d1 = Math.floor(Math.random() * 6) + 1;
        var d2 = Math.floor(Math.random() * 6) + 1;
        var diceTotal = d1 + d2;
        //shows the random number value//

        die1.innerHTML = d1;
        die2.innerHTML = d2;
        status.innerHTML = "You Rolled "+diceTotal+".";
        if (d1 == d2){
                status.innerHTML +=" Doubles! Roll Again ";
        }
}

//computer dice roll//
function compDice() {
                var die3 = document.getElementById("die3")
                var die4 = document.getElementById("die4")
                var status2 = document.getElementById("status2")

                var d3 = Math.floor(Math.random() *6) +1;
                var d4 = Math.floor(Math.random() * 6) +1;
                var diceTotal = d3 + d4;

                die3.innerHTML = d3;
                die4.innerHTML = d4;
                status2.innerHTML = "Computer Rolled "+diceTotal+".";
}
div.dice{
        float:left;
        width:32px:
        background:#D6D6D6;
        border:#999 1px solid;
        padding:10px;
        font-size:24px;
        text-align:center;
        margin:5px;
}

div.die{
        float:left;
        width:32px:
        background:#D6D6D6;
        border:#999 1px solid;
        padding:10px;
        font-size:24px;
        text-align:center;
        margin:5px;
}
<form action="#" method="get">

Player Name:
<input id="fname" name="fname" type="text" size="20" maxlength="20" onblur="Welcome()" />

Age:
<input id="age" name="age" id="age" type="text" size="3" maxlength="3" onBlur="oldEnough(this.value)"/>

0

0

<button onclick="rollDice()";"compDice()">Roll Dice</button>

0

0

A: Change this:
<button onclick="rollDice()";"compDice()">Roll Dice</button>

to:
<button onclick="rollDice();compDice()">Roll Dice</button>


text:
Q: How to properly extract data from JSON.stringify I am learning AJAX and I am having some difficulties in getting the result when I use it in MVC example.
My code has the following parts:
1- MVC Controller: there is a method just return one value:
    [HttpPost]
    public JsonResult DemoAjaxMvc()
    {
        return Json(new { returnedData = "Hello" }, JsonRequestBehavior.AllowGet);
    }

2- The JavaScript part:
function testAjax(){
  $.ajax({
          type: "POST",
          url: "DemoAjaxMvc",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (data) {
              //
              alert(JSON.stringify(data));

              alert(data.length);

              alert(data[0].returnedData);
          },
          error: function (exception) {
              console.log(exception);
          }
      });
}

3- The View part:
<button type="button" onclick="testAjax()">Show Returned Data</button>

What I couldn't understand is that the code is actually able to read the data from alert(JSON.stringify(data)); but alert(data.length); always return undefined and the alert(data[0].returnedData); returns an error
How can I successfully extract the returnedData from the JSON.stringify(data)?
I found some questions with almost the same title as my question, but I could not understand them because they seem different and I am not yet familiar with how to read the code properly

A: You do not need the stringify.  dataType: 'json' is telling jQuery that the response should be JSON, and it will auto parse it into an object for you.  All you have to do at that point should be to access it like any normal object.
console.log(data.returnedData); //this according to your code should be "Hello"


text:
Q: Calculation of betweenness in iGraph I've seen some info suggesting that closeness in iGraph weighted graphs is calculated using the weights as costs, rather than strengths.
I'm wondering if this is also true for betweenness. i.e, if I have two paths between vertices, one of them (a) with edge weights summing to 100 and the other (b) to 200, betweenness will interpret path a as the least costly path and include this edge weight value in the numerator of the betweenness calculation.
If so, to obtain betweenness based on strength, I assume one would transform the weights to equal 1/weight?
I've tried to test this with a three node edge file as follows:
V1  V2 weight
1    2      1
1    3      4
2    3      1

Using the weights as supplied above, node 2 has a betweenness of 1, and others=0. This seems to indicate that the betweenness calculation is avoiding the path from 2->1->3 because it's viewing the high weights as a cost.
However, if I create a new weighting variable:
E(g)$weightI <- 1/E(g)$weight
And run betweenness:
b<-data.frame(betweenness(g, V(g), directed=FALSE, weights=E(g)$weightI)),
all the betweenness values are 0, which is unexpected and not especially helpful in sorting out my initial question

A: Indeed, igraph assumes that the weights of the edges in betweenness calculation are costs, not strengths. This is because (as far as I know) betweenness is defined in terms of shortest paths, and the "length" of a path in graph theory is the sum of the lengths (weights) of the edges involved. There is no clear definition of "betweenness based on strengths". You can try to transform your "strengths" to costs, but you can get different results depending on the transformation you choose as some transformation may indicate that one particular path is shorter in the transformed graph and some other transformation may indicate that some other path is shorter.


text:
Q: Utterly confused how browserify & browserify-shim are supposed to work Well i started simple to grasp whats going on:
So I have one plugin which depends on jQuery, figure from there, i'd build on that and simply add more. However the only thing I can get to work is jQuery by itself.
This is the error I get from the terminal:
[13:24:27] { [Error: Cannot find module 'jquery.mixitup.js' from '/Users/antonioortiz/Dropbox/developer_folder/browserify_app/app/_js']

Here is my setup:
package.json
"main": "./app/_js/app.js", //entry point for your app
"browserify": {
    "transform": [
        "browserify-shim", // Is this supposed to help with the non `node_module` pacakages?
         "debowerify"
    ]
},

"browser": { // This gives browserify the location of your plugin right?
    "mixitup": "./bower_components/mixitup/src/jquery.mixitup.js"
},

"browserify-shim": {
    "jQuery": "global:jQuery",
    "mixitup": {
        "depends": "jQuery",
        "exports": "mixitup"

    }

On a basic level the browserify-shim is supposed to accomplish fetching non 'node_modules' right? Does anyone mind setting the record straight, because for the life of me I can't configure this correctly. But more importantly, I'd love to know what is going on!
Thanks!
UPDATE
So it appears if you use
    var mixitup = require('./../bower_components/mixitup/build/jquery.mixitup.min.js'); in your app.js file it works. But then what is the point of the browserify-shim. I though it was supposed to allow you to use the shortened convention:
In my case, it would be:
var mixitup = require('jquery.mixitup.js');

UPDATE
Based on Nick's suggestions tried this, granted I didn't use proxyquireify. Anyone has another method. As I am still in the weeds...
"browser": {
        "jQuery": "global:jQuery",
        "mixitup": "/app/bower_components/mixitup/src/jquery.mixitup.js",
        "Mustache": "/app/bower_components/jquery-Mustache/jquery.mustache.js",
        "mustache": "mustache"
    }

But with no success...

Also getting a error message which seems more cryptic then the last:
{ [Error: ENOENT, lstat '/app']
  errno: 34,
  code: 'ENOENT',
  path: '/app',
  stream:

A: Browserify-shim makes allows you to export a module based on the mapping you provide. So in your example you should require your module via mixitup e.g. var mixitup = require('mixitup');. You are getting a module error because you are looking for a module called jquery.mixitup.js. More information on how node's module system works here.
You don't need the exports since browserify-shim exports the alias by default (docs):
"mixitup": {
  "depends": "jQuery"
}

You also don't need to use debowerify if you are using browserify-shim.


text:
Q: Cookie domain and path with jax-rs I'm using jax-rs and trying to add a cookie to my response.
The problem is that when adding a cookie the following way:
new NewCookie("cookie-name", "cookie-value");

the cookie is being attached only to the requests of the same path.
For example, if I add the cookie in the request "/myapp/users/login", I don't see that cookie when calling other requests. I think the explanation to this is that, for some reason, the path of the cookie is "/myapp/users" so when calling "myapp/someotherpath" the cookie is not being attached.
I tried using another constructor of NewCookie where I can set domain and path but couldn't make it work, can some one give me an example of setting domain and path that will attach the cookie to all requests? isn't this supposed to be the default behavior anyway?

A: To attach the cookie to all requests the domain and path should be:
domain = "";
path = "/"
So the cookie creation will look as follows:
NewCookie("cookie-name", "cookie-value", "/", "", "comment", 100, false);


text:
Q: Swift - Generic Functions The Goal
I want to call the instantiateViewControllerWithIdentifier method on a Storyboard to get a view controller. But I want to do it with generics for code reuse and simplicity.
The Non-Compiling Code
let viewController = StoryboardHelper.viewControllerFromStoryboard<ChooseProviderViewController>()

class func viewControllerFromStoryboard<T>() -> T {
        let storyboard = mainStoryboard()
        let viewController = storyboard.instantiateViewControllerWithIdentifier(resolveViewController(T)) as T

        return viewController
    }

private class func resolveViewController<T>() -> String {
        if T is ChooseProviderViewController {
            return chooseProviderViewControllerIdentifier;
        }

        return ""
    }

Now, the above code is what I have at the moment, and how I would like the API to be. It would be nice to say "StoryboardHelper, here is the type of the view controller I want, go get the view controller instance for me".
So, in the end, I would like some way to do this:
let instanceOfXViewController = StoryboardHelper.viewControllerFromStoryboard<XViewController>()

let instanceOfYViewController = StoryboardHelper.viewControllerFromStoryboard<YViewController>()

A: I have a answer for you but it will only work with Swift 1.2 (+), in 1.1 it will return a intance of the wrong (super) type. I changed it to a more general situation/naming but it is effectly the same problem. First since you only want to manage UIViewControllers you should restrict T. Like <T:UIViewController> . Secondly you should/can pass the Type as an argument and create an instance of it.
import Foundation

class Helper {
    class func instanceFromT<T:R>(T.Type) -> T {
        return T.self()
    }
}

class R {
    required init () {

    }
    func me() -> String {
        return "me is R"
    }
}

class B : R {
    override func me() -> String {
        return "me is B"
    }
}

class A : R {
    override func me() -> String {
        return "me is A"
    }
}

let my = Helper.instanceFromT(A.self)

println(my.me()) // "me is A"


text:
Q: Filter on two fields in ElasticSearch when one of the fields is only present sometimes Let's say we are looking for shoes with a max price of $100.
The shoes has a 'price' field, but can also have a 'discounted_price' fields.
As an example:
{
    "_index": "shoes",
    "_type": "shoe",
    "_id": "1",
    "_score": 1,
    "_source": {
        "price": 150,
        "discounted_price": 90
    }
}
{
    "_index": "shoes",
    "_type": "shoe",
    "_id": "2",
    "_score": 2,
    "_source": {
        "price": 100,
        "discounted_price": null
    }
}

How would you construct a query for a max price of $100, which would return both documents in this case?

A: You can try something like this:
POST /shoes/shoe/_search
{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "filter": [
              {
                "range": {
                  "discounted_price": {
                    "lte": 100
                  }
                }
              },
              {
                "exists": {
                  "field": "discounted_price"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "filter": [
              {
                "range": {
                  "price": {
                    "lte": 100
                  }
                }
              },
              {
                "missing": {
                  "field": "discounted_price"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

UPDATE:
For ES versions older than 2.0 you can use the following query instead:
POST /shoes/shoe/_search
{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "minimum_should_match": 1,
          "should": [
            {
              "bool": {
                "must": [
                  {
                    "range": {
                      "discounted_price": {
                        "lte": 100
                      }
                    }
                  },
                  {
                    "exists": {
                      "field": "discounted_price"
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "must": [
                  {
                    "range": {
                      "price": {
                        "lte": 100
                      }
                    }
                  },
                  {
                    "missing": {
                      "field": "discounted_price"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}


text:
Q: Is there any way to disable all extensions in magento I have several extensions on a magento site. I suspect one of them is causing a problem and I want to disable them all and then bring them back one at a time to find the problem. Is there any easier way to do this then going into app/etc/modules/* and disabling them individually?

A: Dont know if helps but the only massive disable that Magento offers is only of local codepoll (app/code/local)
while going through the section on Module loading, it is revealed that we can easily disable all modules living in the local (app/code/local) namespace by editing app/etc/local.xml and setting the disable_local_modules node to true:
You can do it in your local xml:
<config>
     <global>
    ...
         <disable_local_modules>true</disable_local_modules>
    ...
     </global>
    ...
</config>

A: Go to

Admin -> System -> Configuration

and in the left on the last menu

ADVANCED -> Advanced

and disable or enable extensions


text:
Q: always include current locale in url route in zend framework 2 (ZF2) How to include current locale like en, tr, ... in url. you can see like of this in symfony or Joomla.
when use enter to this url: http://test.com this automatically convert to http://test.com/en I want to include current locale in url and recognize it and change the website locale.

A: in your Module.php file :
public function onBootstrap(MvcEvent $e)
{
    $em = StaticEventManager::getInstance();
    $em->attach('Zend\Mvc\Application', MvcEvent::EVENT_ROUTE, array($this, 'onRoute'),
}

public function onRoute(MvcEvent $e)
{
    $routeLang = $e->getRouteMatch()->getParam('lang', false);
    if(!$routeLang)
        $e->getRouter()->setDefaultParam('lang', \Locale::getDefault());
}

and your main route config :
    'app' => array(
        'type' => 'Segment',
        'options' => array(
            'route' => '/[:lang]',
            'defaults' => array(
                'controller' => 'Application\Controller\Index',
                'action' => 'index',
            ),
            'constraints' => array(
                'lang' => '[a-z]{0,2}',
            ),
        ),
    ),

all the other routes should be a child of this route.


text:
Q: Metric to estimate measuring accuracy I need help/suggestions on which metric/approach to use.
I am trying to estimate pointing precision by measuring the offset of the experimentally measured values from the real, theoretical values, with multiple measurements but on different quantities although from the same source.
It means I have a list of deviations of exp measured values from the theoretical values. Pretty messy explanation, I know, I will try to explain it in an example.
Specifically, I have a picture of a night sky, and I am measuring offset (angular distance) from the star in the image (experimentally measured value) and its position in the star catalog (theoretical value). And I am doing it for every star in the image. So, if I have 100 stars in the image, I have 100 calculated deviations (angular distances) of the measured values from the real values. With that, I am trying to estimate pointing precision on the random point in the image, regardless if there is a star or not. I could take the average value of all (100) separations.
Or maybe the standard deviation of that separations? Mean of Rayleigh distribution?
What would be an appropriate metric to use? Could someone redirect me to a similar problem, if there is such? Or some material to read?


text:
Q: Magento 2 Raw SQL Query updates Date to UTC TimeZone Mysql TimeZone - Asia/kolkata
PHP TimeZone - Asia/Kolkata
Magento 2 Config - Asia/Kolkata
lets say I have following two rows in sales_order:

I have Following Query:

select count(*) from sales_order where date(created_at) = date('2019-04-28');

Result in Mysql WorkBench:
2
Result in Magento 2 Resource Model Class:
1
I used
$this->connection->fetchAll("select count(*) from sales_order where date(created_at) = date('2019-04-28')");

for fetching data in Resource Model.
I know this created_at is getting converted to UTC. I want my query results to be in Asia/Kolkata time zone. Any help would be appreciated.
Some things i already tried:

*

*Changing TimeZone in bootstrap.php from UTC to required timezone.

*setting PHP TimeZone just before executing my query.

I can fix this by running a loop on result set, but i want my query to do all the work.


text:
Q: Opening a file in read-only mode using nano I am new to Ubuntu. I know I can open a file using vim in read-only mode by pass the -R option:
vim -R <filename> //Gives warning if I try to write

However, if I do the same thing with nano, I am able to write files freely:
nano -R <filename>  //I can still write

What am I doing wrong? How can I open files in read-only mode using nano?

A: Nano does not use '-R' as a "read-only-" option and uses '-R' for something else.

-R, --restricted
Restricted  mode:  don't read or write to any file not specified
on the command line.  This means: don't read  or  write  history
files; don't allow suspending; don't allow spell checking; don't
allow a file to be appended to, prepended to, or saved  under  a
different  name  if  it  already  has one; and don't make backup
files.  Restricted mode can also be activated by  invoking  nano
with any name beginning with 'r' (e.g. "rnano").

it uses -v or --view:

-v, --view
Just view the file and disallow editing: read-only  mode.   This
mode  allows  the user to open also other files for viewing, un‐
less --restricted is given too.