text:
Q: GLSL shader integer parameter interpreted as float I have the following (somewhat old) GLSL shader.
/**
 * @file   YCbCr.glsl
 * @author gga
 * @date   Thu Jul  5 22:50:08 2007
 *
 * @brief    simple YCbCr texture with 3D lut shader
 *
 */

// Images
uniform sampler2D YImage;
uniform sampler2D UImage;
uniform sampler2D VImage;
uniform sampler3D lut;

// Standard controls
uniform float gain;
uniform float gamma;
uniform int   channel;

// Interlaced/Checkerboard controls (don't work)
uniform int mask;
uniform int mask_value;
uniform int height;
uniform int width;

// Normalization variables
uniform bool  premult;
uniform bool  unpremult;
uniform bool  enableNormalization;
uniform float normMin;
uniform float normSpan;

// YCbCr variables
uniform bool  coeffs;  // Use fed coefficients instead of builtin ones
uniform vec3  Koff;
uniform vec3  Kr;
uniform vec3  Kg;
uniform vec3  Kb;

// Lut variables
uniform bool  enableLut;
uniform bool  lutF;
uniform float lutMin;
uniform float lutMax;
uniform float lutM;
uniform float lutT;

void main()
{
  //
  // Sample luminance and chroma, convert to RGB.
  //
  vec4 c;
  vec3 pre;
  vec2 uv = gl_TexCoord[0];
  pre.r = texture2D(YImage, uv.st).r;  // Y
  pre.g = texture2D(UImage, uv.st).r;  // U
  pre.b = texture2D(VImage, uv.st).r;  // V

  if ( coeffs )
  {
    pre += Koff;

    c.r = dot(Kr, pre);
    c.g = dot(Kg, pre);
    c.b = dot(Kb, pre);
    c.a = 1.0;
  }
  else
  {
      vec3 yuv;

      yuv.r = 1.1643 * ( pre.r - 0.0625 );
      yuv.g = pre.g - 0.5;
      yuv.b = pre.b - 0.5;

      c.r = yuv.r + 1.5958 * yuv.b;
      c.g = yuv.r - 0.39173 * yuv.g - 0.81290 * yuv.b;
      c.b = yuv.r + 2.017 * yuv.g;
  }

  vec2 tc = gl_TexCoord[0].st;
  c.rgb = clamp( c.rgb, 0.0, 1.0 );
  c.a = 1.0;
  int x = 0;

  if ( mask == 1 )  // even odd rows
  {
      float f = tc.y * height;
      x = int( mod( f, 2 ) );
      if ( c.a == 0.0 ) c.a = 1.0;
  }
  else if ( mask == 2 ) // even odd columns
  {
      float f2 = tc.x * width;
      x = int( mod( f2, 2 ) );
      if ( c.a == 0.0 ) c.a = 1.0;
  }
  else if ( mask == 3 ) // checkerboard
  {
      float f = tc.y * height;
      float f2 = tc.x * width;
      x = int( mod( floor( f2 ) + floor( f ), 2 ) < 1 );
      if ( c.a == 0.0 ) c.a = 1.0;
  }

  if ( x == mask_value )
  {
      c.r = c.g = c.b = c.a = 0.0;
  }

  //
  // Apply normalization
  //
  if (enableNormalization)
    {
      c.rgb = (c.rgb - normMin) / normSpan;
    }

  //
  // Apply 3D color lookup table (in log space).
  //
  if (enableLut)
    {
      c.rgb = lutT + lutM * log( clamp(c.rgb, lutMin, lutMax) );
      c.rgb = exp( texture3D(lut, c.rgb).rgb );
    }

  if ( unpremult )
  {
    c.rgb /= c.a;
  }

  //
  // Apply gain
  //
  c.rgb *= gain;

  //
  // Apply video gamma correction.
  //
  c.r = pow( c.r, gamma );
  c.g = pow( c.g, gamma );
  c.b = pow( c.b, gamma );

  //
  // Apply channel selection
  //
  if ( channel == 1 )
    {
      c.rgb = c.rrr;
    }
  else if ( channel == 2 )
    {
      c.rgb = c.ggg;
    }
  else if ( channel == 3 )
    {
      c.rgb = c.bbb;
    }
  else if ( channel == 4 )
    {
      c.rgb = c.aaa;
    }
  else if ( channel == 5 )
    {
      c.r *= 0.5;
      c.r += c.a * 0.5;
    }
  else if ( channel == 6 )
    {
      c.rgb = vec3( (c.r + c.g + c.b) / 3.0 );
    }

  if ( premult )
  {
      c.rgb *= c.a;
  }

  gl_FragColor = c;
}

My problem is that 4 of the int parameters (mask, mask_value, height, width) are interpreted as float.  That is, if I call glUniform1i I get an error.  But if I call the parameters as glUniform1f it works.  Note that the channel parameter is correctly seen as integer.  This seems like a bug in the shader compiler.  Can someone help me work around it (maybe in the process making the shader more up to date)?
Here's the C++ code that sets the uniforms:
  void GLShader::setUniform( const GLint location, const GLint x  )
  {
      glUniform1i( location, x );
  }

  void GLShader::setUniform( const GLint location,
                 const int x, const int y )
  {
      glUniform2i( location, x, y );
  }

  void GLShader::setUniform( const GLint location,
                 const int x, const int y, const int z )
  {
      glUniform3i( location, x, y, z );
  }

  void GLShader::setUniform( const GLint location,
                 const int x, const int y,
                 const int z, const int w  )
  {
      glUniform4i( location, x, y, z, w );
  }

  void GLShader::setUniform( const char* uniform,
                 const int x )
  {
    if ( _program )
      {
    GLint location = glGetUniformLocation( _program, uniform );
    // location is valid here, not -1
    CHECK_GL;
    setUniform( location, x );
    CHECK_GL;
      }
    else if ( _frag_target == GL_FRAGMENT_PROGRAM_NV )
      {
    glProgramNamedParameter4fNV( _frag_shader, strlen(uniform),
                     (GLubyte *) uniform,
                     float(x), 0.f, 0.f, 0.f );
    CHECK_GL;
      }
    else if ( _frag_target == GL_FRAGMENT_PROGRAM_ARB )
      {
    GLint location = uniform_location( uniform );
    CHECK_GL;
    glProgramLocalParameter4fARB( _frag_target, location,
                      float(x), 0.f, 0.f, 0.f);
    CHECK_GL;
      }
  }

And the invocation to set the values (all vars are int).
    _shader->setUniform( "mask", _mask );
    CHECK_GL;
    _shader->setUniform( "mask_value", _mask_value );
    CHECK_GL;
    _shader->setUniform( "width", _width );
    CHECK_GL;
    _shader->setUniform( "height", _height );
    CHECK_GL;


text:
Q: Web service running on windows parallels accessible by same machine (mac) but not by colleagues on the intranet I just wrote a hello world application with Vaadin. The development was done on windows 10 running on parallels and I left the web service running on the windows virtual machine. I can access the service from a browser on windows through the url: localhost:8080/hello-world. I found out the IP address of the windows virtual machine with ifconfig and, if I type the url: ipaddress:8080/hello-world on a browser running on the mac, it works as well. However, my colleagues on the intranet cannot access the web application through the same url. What am I missing here? Is the service only visible to me? Are there any firewall issues? Setup problems with the parallels virtual machine?
Thanks very much in advance.

A: I just found the answer, but sidgate, thanks for your help. The bottomline is that I was running the windows virtual machine in shared mode. Apparently, if you do that, the windows virtual machine is in a subnet with your own mac, and the mac is the router. I switched to the bridge method with the default adapter and I then get an ip address on my intranet, which is visible by everyone.
Regards

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sustitución del metodo split() en otro foro alguien pregunto por una sustitución del método split() que recordamos que devolvía una lista con las palabras de un string utilizando una separacion que eligamos. y quería buscar otra forma sin utilizar ese método. elemplo:
input>>> casa arbol cama coche
out>>> ['casa','arbol','cama','coche']
os envío el código que he echo que funciona bien pero sé que python brilla por su simpleza y debe haber alguna manera mejor. Por si podeis echarle un vistazo y sabéis alguna otra manera.
def union(string,x,y):#funcion con tres argumentos, el string y dos posiciones para sacar la palabra e incluirla en la lista
  element=''
  while x<y:
    element+=string[x]
    x+=1
  lista.append(element)

def incorpora(string):#funcion donde recorre el strin para ir cortando antes del espacio mostrar las posiciones para que la función incorpora saque la palabra y la registre en la lista. en el primer while repite hasta que no halla espacios en el string de ahí que añadiese un espacio al final y el segundo while es el que manda a la funcion siempre que halla palabra y luego eliminamos la palabra del string.
  space=' '
  while space in string:
    final=len(string)
    indice=0
    inicio=0
    while indice<final:
      for i in string:
        if i==' ':
          indice=string.index(i)
      union(string,inicio, indice)
      string=string[indice+1:final]
      indice=final

lista=[]
palabras=input("Ingrese una cadena: " )
palabras =palabras+' '#añadimos un espacio al final del string
sep=' '
incorpora(palabras)
for i in lista:
  if i in sep:
    lista.remove(i)
print(lista)

A: Pues claramente que hay una forma simplificada de hacerlo. Un ciclo for y el uso del método index es suficiente.
def my_split(cadena, separador):
    resultado, n = [], None
    cadena += separador if separador in cadena else ""
    for n in range(cadena.count(separador)):
        i = cadena.index(separador)
        resultado.append(cadena[:i])
        cadena = cadena[i+1:]
    return (resultado if n else [cadena])

En el for decimos que iteraremos según las veces que el separador se repita en la cadena. En cada iteración encontraremos el índice del elemento y entonces añadimos el trozo a la lista y luego sobreescribimos el valor de cadena. Al finalizar el ciclo for retornamos la lista con los elementos separados pero retornamos [cadena] en caso el separador no se encuentre en la cadena.
Probamos
cadena = "casa arbol cama coche out"

print(my_split(cadena, " "))

Resultado
['casa', 'arbol', 'cama', 'coche', 'out']

Obviamente deberíamos de colocar un if para el caso que no se pase un separador, es decir "".

A: Una solución usando expresiones regulares:
def my_split(cadena, separador):
    exp = f"([^{separador}]+)"
    return re.findall(exp, cadena)

Supongamos que usamos la coma como separador. Entonces, exp queda reducida a ([^,]+), que es una expresión regular que reconoce y captura un grupo de uno o más caracteres que no sean coma. Al encerrar la expresión entre paréntesis, la capturamos. La función retorna una lista con todas las capturas, es decir, todas aquellas partes del texto que cumplieron con la expresión.
Demo
import re

def my_split(cadena, separador):
    exp = f"([^{separador}]+)"
    return re.findall(exp, cadena)

tests = [
    ("la mona jacinta se ha puesto una cinta", " "),
    ("123,456,678,,443,34", ","),
    ("el valor, 123.45, descontado", ","),
    ("ab^cd^ef", "^"),
    ("45*677*89", "*")
]

for (cadena, separador) in tests:
    m = my_split(cadena, separador)
    print(m)

produce
['la', 'mona', 'jacinta', 'se', 'ha', 'puesto', 'una', 'cinta']
['123', '456', '678', '443', '34']
['el valor', ' 123.45', ' descontado']
['ab', 'cd', 'ef']
['45', '677', '89']

A: No se si es la mejor forma, pero me centré en la velocidad.
Código
def my_split_dante(cadena, separador, maxsplit=-1):
    index = 0
    len_separador = len(separador)
    lista = []

    if(maxsplit == -1):
        maxsplit = float('inf')

    while True:
        # buscamos en la cadena la subcadena de separador desde la ultima coincidencia. Si no hubo coincidencias antes, busca desde el principio.
        index_nuevo = cadena.find(separador, index)

        # Si no se encontró ninguna nueva coincidencia, agrega a la lista una pedazo de la cadena que va desde
        # la ultima coincidencia hasta el final y se devuelve la lista.
        if(index_nuevo == -1):
            break
        else:
            lista.append(cadena[index:index_nuevo])
            index = index_nuevo+len_separador

            # Le resta 1 a maxsplit por cada coincidencia encontrada.
            maxsplit -= 1

            # Cuando maxsplit vale 0, el bucle es interrumpido.
            if(maxsplit == 0):
                break

    lista.append(cadena[index:])
    return lista

print("my_split_dante con el parametro maxsplit", my_split_dante("hola mundo soy dante s.", " ", maxsplit=2))
print("my_split_dante SIN el parametro maxsplit", my_split_dante("hola mundo soy dante s.", " "))

produce
my_split_dante con el parametro maxsplit ['hola', 'mundo', 'soy dante s.']
my_split_dante SIN el parametro maxsplit ['hola', 'mundo', 'soy', 'dante', 's.']


text:
Q: Deriving Killing equation from Isometry In Nakaharas book (Geometry, Topology, Physics) he states the isometry condition
and then derives the Killing equation ("by a simple calculation") on page 279:
$$\begin{equation}\frac{\partial(x^\kappa+\epsilon X^\kappa)}{\partial x^\mu}\frac{\partial(x^\lambda+\epsilon X^\lambda)}{\partial x^\nu}\end{equation}g_{\kappa\lambda}(x+\epsilon X) = g_{\mu\nu}(x)
\tag{7.96b}$$
$$\begin{equation}X^\xi\partial_\xi g_{\mu\nu}+\partial_\mu X^\kappa g_{\kappa \nu}+\partial_\nu X^\lambda g_{\mu\lambda} = 0\tag{7.120a}\end{equation}$$
How does one derive the second from the first?

A: The steps are to note that:
$$\frac{\partial(x^\kappa+\epsilon X^\kappa)}{\partial x^\mu} = \delta^\kappa_\mu+\epsilon \partial_\mu X^\kappa,\qquad g_{\kappa\lambda}(x+\epsilon X) = g_{\kappa\lambda}(x)+\epsilon X^\xi\partial_\xi g_{\kappa\lambda}(x)+O(\epsilon^2)$$
Now combine to get:
$$\frac{\partial(x^\kappa+\epsilon X^\kappa)}{\partial x^\mu}\frac{\partial(x^\lambda+\epsilon X^\lambda)}{\partial x^\nu}g_{\kappa\lambda}(x+\epsilon X) = (\delta^\kappa_\mu+\epsilon \partial_\mu X^\kappa)(\delta^\lambda_\nu+\epsilon \partial_\nu X^\lambda) (g_{\kappa\lambda}+\epsilon X^\xi\partial_x g_{\kappa\lambda} +O(\epsilon^2))$$
multplying it out gives:
$$g_{\mu\nu}+\epsilon (\partial_\nu X^\kappa g_{\kappa\mu}+\partial_\mu X^\lambda g_{\lambda\nu}+\partial_\xi X^\xi g_{\mu\nu})+O(\epsilon^2)$$
by setting this equal to $g_{\mu\nu}$ you get the equation desired.


text:
Q: Rails: logic in model or controller? I'm trying to clean out my controller, and I figured it'd be best to keep this logic in the model:
@current_issue = Issue.order(:id).last
@doc = Doc.new do |n|
  n.user_id = current_user.ftp
  n.season = Date::MONTHNAMES[Time.now.month].to_s + " " + Time.now.year.to_s
  n.article1_body = @current_issue.articles[0].body
  n.article2_body = @current_issue.articles[1].body
  n.article3_body = @current_issue.articles[2].body
  n.cover = @current_issue.cover
  n.message = @current_issue.message
  n.issue_code = @current_issue.issue_code
end
@issues = Issue.get_em_boys

What's the best way to go about doing that?

A: As a starting point...
Controller:
@doc = Doc.new
@doc.generate_from_issue(current_user, @current_issue)
...
@issues = Issue.get_em_boys

Model:
def generate_from_issue(user, issue)
  self.user_id = user.ftp
  self.season = Date::MONTHNAMES[Time.now.month].to_s + " " + Time.now.year.to_s
  self.article1_body = issue.articles[0].body
  self.article2_body = issue.articles[1].body
  self.article3_body = issue.articles[2].body
  self.cover = issue.cover
  self.message = issue.message
  self.issue_code = issue.issue_code
end


text:
Q: WP can send test mail, Contact Form 7 can't As mentioned in the title, I have a WP site, I use WP-SMTP and can send test mails perfectly. However Contact Form 7 or any other contact form plugin can't send any mails. What would you suggest?
Edit: I should mention, I can send test mails via SMTP only with no encryption. When I select SSL or TLS encryption, it also fails.

A: It seems that the cause of the problem was the plugin. Although, it is a known and popular plugin, which works perfectly for many users, in my site it doesn't work. I changed to Fast Secure Contact Form and problem solved.


text:
Q: Download file from web and then save with a save file dialog box? How can I download a file, then save it to wherever I want? I am using Windows Form, Web Application.
I know I can download it with this code:
WebClient wClient = new WebClient();
wClient.DownloadFile("WebLinkHere", @"C:\File.txt");

But I want a save box like when you press CTRL+S.

A: You can use SaveFileDialog class. Example:
var dialog = new SaveFileDialog();
dialog.Filter = "Archive (*.rar)|*.rar";

var result = dialog.ShowDialog(); //shows save file dialog
if(result == DialogResult.OK)
{
    Console.WriteLine ("writing to: " + dialog.FileName); //prints the file to save

    var wClient = new WebClient();
    wClient.DownloadFile("WebLinkHere", dialog.FileName);
}

will show next dialog and if you search for next folder

application will print:
writing to: C:\Temp\archiveName.rar

A: This will work and open the file download popup.
String FileName = "FileName.xls";
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", FileName));
            Response.ContentType = "application/ms-excel";
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
            Response.Write(stringWriter.ToString());
            Response.End();


text:
Q: How to use assets as a source for osmdroid offline maps I'm trying to use osmdroid for offline map usage in my app, but the thing which I'm not able to find is how to set the tile source from the /assets folder.
So I've got the tiles (from Mobile Atlas Creator), placed in /assets/maps.zip
and I'm trying something like this:
final ITileSource tileSource =
   new XYTileSource("maps", null, 15, 17, 256, "png", "/assets");
mapview.setBuiltInZoomControls(true);
mapview.setTileSource(tileSource);
mapview.getController().setZoom(15);
mapview.setUseDataConnection(false);

.. which seems to be wrong some way. So can anybody point me on how to do that?

A: OK, the question has been asked a couple of years ago,
but there is still no clear info on how to use offline maps from the assets folder.
So here is my solution.

*

*Create the maps with Mobile Atlas Creator.
I used Atlas format = osmdroid zip and maps source = OpenStreetMap 4UMaps.eu

*Unzip the maps and put into your assets folder:
assets/map/14, where 14 - is for instance a folder with the corresponding zoom level (you will probably have several folders)

*Add classes which I found somewhere on the internet:
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import org.osmdroid.ResourceProxy.string;
import org.osmdroid.tileprovider.tilesource.BitmapTileSourceBase;
import org.osmdroid.tileprovider.util.StreamUtils;

import java.io.InputStream;

/**
 * Custom tile source,
 * used to load map tiles from the assets
 */
public class AssetsTileSource extends BitmapTileSourceBase {
    private final AssetManager mAssetManager;

    public AssetsTileSource(final AssetManager assetManager, final String aName, final string aResourceId,
            final int aZoomMinLevel, final int aZoomMaxLevel, final int aTileSizePixels,
            final String aImageFilenameEnding) {
        super(aName, aZoomMinLevel, aZoomMaxLevel, aTileSizePixels, aImageFilenameEnding);
        mAssetManager = assetManager;
    }

    @Override
    public Drawable getDrawable(final String aFilePath) {
        InputStream inputStream = null;
        try {
            inputStream = mAssetManager.open(aFilePath);
            if (inputStream != null) {
                final Drawable drawable = getDrawable(inputStream);
                return drawable;
            }
        } catch (final Throwable e) {
            // Tile does not exist in assets folder.
            // Ignore silently
        } finally {
            if (inputStream != null) {
                StreamUtils.closeStream(inputStream);
            }
        }
        return null;
    }
}

and
/**
 * Map tile provider, loads tile from assets folder
 */
public class MapTileFileAssetsProvider extends MapTileModuleProviderBase {

    protected ITileSource mTileSource;

    public MapTileFileAssetsProvider(final ITileSource pTileSource) {
        super(OpenStreetMapTileProviderConstants.NUMBER_OF_TILE_FILESYSTEM_THREADS, OpenStreetMapTileProviderConstants.TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE);

        mTileSource = pTileSource;
    }

    @Override
    public boolean getUsesDataConnection() {
        return false;
    }

    @Override
    protected String getName() {
        return "Assets Folder Provider";
    }

    @Override
    protected String getThreadGroupName() {
        return "assetsfolder";
    }

    @Override
    protected Runnable getTileLoader() {
        return new TileLoader();
    }

    @Override
    public int getMinimumZoomLevel() {
        return mTileSource != null ? mTileSource.getMinimumZoomLevel() : Constants.MAP_ZOOM_ZOOM_MAX;
    }

    @Override
    public int getMaximumZoomLevel() {
        return mTileSource != null ? mTileSource.getMaximumZoomLevel() : Constants.MAP_ZOOM_ZOOM_MIN;
    }

    @Override
    public void setTileSource(final ITileSource pTileSource) {
        mTileSource = pTileSource;
    }

    private class TileLoader extends MapTileModuleProviderBase.TileLoader {

        @Override
        public Drawable loadTile(final MapTileRequestState pState) throws CantContinueException {

            if (mTileSource == null) {
                return null;
            }

            final MapTile pTile = pState.getMapTile();
            String path = mTileSource.getTileRelativeFilenameString(pTile);

            Drawable drawable;
            try {
                drawable = mTileSource.getDrawable(path);
            } catch (final LowMemoryException e) {
                // low memory so empty the queue
                throw new CantContinueException(e);
            }

            return drawable;
        }
    }
}

*Add the constants:

 // map min zoom level
 public static final int MAP_ZOOM_ZOOM_MIN = 12;
 // map max zoom level
 public static final int MAP_ZOOM_ZOOM_MAX = 14;
 // maps folder name in assets
 public static final String MAP_ASSETS_FOLDER_NAME = "map";

As you probably guessed, they represent minimum and maximum zoom level, which we previously created with the Mobile Atlas Creator.

*The last, but not the least,
the snippet of implementation code:
    // making the map not use internet
    mBinding.mapView.setUseDataConnection(false);

    // Initializing the tile provider to use offline maps from the assets
    // This will load for instance from /map/14/12345/12345.png
    AssetsTileSource tileSource = new AssetsTileSource(
            getAssets(),
            Constants.MAP_ASSETS_FOLDER_NAME,
            ResourceProxy.string.offline_mode,
            Constants.MAP_ZOOM_ZOOM_MIN,
            Constants.MAP_ZOOM_ZOOM_MAX,
            256, ".png");

    MapTileModuleProviderBase moduleProvider = new
            MapTileFileAssetsProvider(tileSource);
    SimpleRegisterReceiver simpleReceiver = new
            SimpleRegisterReceiver(this);
    MapTileProviderArray tileProviderArray = new
            MapTileProviderArray(tileSource, simpleReceiver, new
            MapTileModuleProviderBase[] { moduleProvider });

    mBinding.mapView.setTileProvider(tileProviderArray);

    // not forget to invalidate the map on zoom
    mBinding.mapView.setMapListener(new MapListener() {
        @Override
        public boolean onScroll(ScrollEvent scrollEvent) {
            return false;
        }

        @Override
        public boolean onZoom(ZoomEvent zoomEvent) {
            mBinding.mapView.invalidate();
            return false;
        }
    });

A: asset path is "file:///android_asset/" if you need a inputstream you get it via AssetManager.

A: Take a look at BitmapAssetTileSource. Also the iBurn-2012 might be useful to see it in action.


text:
Q: How can I get unattended-upgrades to work reliably on my laptops? For months, I've been having issues with unattended-upgrades not running every day, or thereabouts, with logs often empty for a week or so, or with it not working at all.
I've amended the relevant file (50unattended-upgrades) so that only 'proposed' are not updated, as well as the relevant part that would only allow updates on AC power, so it should now update on battery power.  When I amended the latter, that helped solve the problem, updating automatically more or less every day.  The laptops are used every day, but obviously the odd day missed for updates may occur.
My desktop PC is fine, updating mostly every day.
Sincere apologies for a lack of logs.  Due to disability and chronic illness, it's difficult to gather all of the information together.  It's taken quite a while to write this.  I know more information is helpful, so please do ask if you require any further information.  Please bear with me if you can.  Thank you.
Basically, the apt timers show up as having been successful, but the logs for unattended-upgrades are all empty.  On a new installation, some log files have not been created.  I don't know if that's normal.  A dry run of unattended-upgrades does create a log file and fill it with information.  However, the laptop I've recently installed 18.04 and then 22.04 sat for a few days without any further logs, and updates were available when I checked manually.
This has been a problem with all available versions from 18.04, 20.04, 22.04 and 22.10, and on three different laptop brands.
Linux Mint's automatic updates appear to work well on my laptops, but then its methods for doing so are different.  Do any of the Ubuntu flavours work any differently in this regard, even slightly, thus somehow not exhibiting this problem?
I've used Ubuntu since 2007, so I can delve deeper and edit files if necessary.  The only changes I've made are the ones mentioned above (no other tweaks).
I suspect this is an issue where Ubuntu still will not update because the laptop is running on battery power, as my desktop appears to be fine.
I have looked at others' posts on this subject.
Many thanks for your help.  It's much appreciated.


text:
Q: How to connect to another page after logging in HTML? I want to to connect to another page after logging in HTML.
For example I have my login page when I submit my information (username, password) I have an action for my login and I want to go to another page when my Authentication is true.
I don't have acces of the code of the server, server using jps

A: Try with:
<meta http-equiv="refresh" content="0;url=http://example.com/" />

or
<?php header( 'Location: http://example.com/' ) ; ?>

When you authenticate user

A: It depends what language you use in the backend.
If you do only javascript validation of the login, you should drop this logic and rewrite it using a proper backend language (php, .net, rails, or whatever), since it would be a huge security problem.
Example of redirection using Ruby on Rails:
redirect_to "yourpath"

using PHP:
header("Location:yourpath");

A: If you are using form in jsp or html you can use the folowing code,
<form name="frm" method="post" action="sec.jsp">

This will direct to sec.jsp. You can also use servlet mapping if you are using servlets.


text:
Q: Where are .NET 4.5 assemblies located?
Possible Duplicate:
Where is the .Net Framework 4.5 directory?

usually you would find them under C:\Windows\Microsoft.NET\Framework

But I can't see it after installing Visual Studio 11 (Beta), which also installs .NET 4.5
Where are they located?


text:
Q: configurate multichannel ASIO4ALL v2.13 So I have a device (logilink sound box ua0099) with 6 channels or 8. It doesn't have ASIO. I installed ASIO4ALL. But I don't know what to do to have acces to each channel to choose a specific channel and play a sound on it.
This is my program in matlab`
function BasicSoundOutputDemo( wavfilename1,wavfilename2)

AssertOpenGL;

[y, freq] = psychwavread(wavfilename1);
[y1, freq1] = psychwavread(wavfilename2);
aux = y';
aux1 = y1';
wavedata = [aux1(1,:) ; aux(1,:)];
nrchannels = size(wavedata,1); % Number of rows == number of channels.

InitializePsychSound;
devices = PsychPortAudio('GetDevices' );

pahandle = PsychPortAudio('Open', 18, [], 0, freq, nrchannels);

PsychPortAudio('FillBuffer', pahandle, wavedata);

t1 = PsychPortAudio('Start', pahandle, 1, 0);

KbReleaseWait;

while ~KbCheck
  % Wait a seconds...
  WaitSecs(1);

end

PsychPortAudio('Stop', pahandle);
PsychPortAudio('Close', pahandle);

`
Device id 18 is
When ASIO4ALL opens I have out 8X
My question is this can I control the speakers that I plug in the SUROUND, FRONT and BASS/CENTER with what I have? If yes , how?
If not, what do I need? Another tool? A better device?

A: no configurations needed. i just choose in matlab the asio4all device and choose the channels


text:
Q: Why does the program ouput correct if dimensions create a square but not a rectangle? I'm writing a program where I need to make a hollow box of asterixs'. The program works fine when I enter dimensions for a square but it doesn't work when I enter dimensions for a rectangle.
import java.util.Scanner;
public class asterix {
    public static void main(String[] args) {

    Scanner input = new Scanner( System.in );

 int stars; // length of side
 int column; // width of box
 int row = 1;

// prompt user to enter the length and width of box

 System.out.print("Enter the length: ");
 stars = input.nextInt();

 System.out.print("Enter the width: ");
 column = input.nextInt();

 while ( row <= stars ) {
     column = 1;

 // and for as many columns as rows
while ( column <= stars ) {

    if ( row == 1)
    System.out.print( "*" );

    else if ( row == stars )
    System.out.print( "*" );

    else if ( column == 1 )
    System.out.print( "*" );

    else if ( column == stars )
    System.out.print( "*" );

    else
    System.out.print( " " );

column++; } // end inner while loop

System.out.println();
 row++;

      } // end output
    } // end of main
} // end of Stars

The ideal output I would want is as follows:
Say its 3 by 3:

   ***
   * *
   ***

and say its 4 by 3:

   ****
   *  *
   ****

A: You need to modify the following lines.
System.out.print("Enter the width: ");
int numberOfColumns = input.nextInt();

and
while ( column <= numberOfColumns )

You compare both loops to the number of lines, and therefore get a square. You should use the number of columns in your inner-loop.
I'm sure it's just a slip-up, you would have caught it.

A: column and row represent your current coordinates (seeing as they are modified in the loop).
In the beginning you read the user input into stars and column, so those should represent the maximum number.
As you notice there is some overlap. You need to define column to mean either the current location or the maximum amount of columns and define a new variable for the other meaning.
This shows how important it is to have meaningful names, even if they are longer. If you had named your variables maxColumns, maxRows and currentColumn, currentRow then the problem would have been very visible.


text:
Q: SQL Server: the login is from untrusted domain and cannot be used with integrated authentication. SSMS I have two SQL Servers on different domains. I am trying to connect to SQL server "A" using SSMS on  domain "B", but getting this error.
Login failed. The login is from an untrusted domain and cannot be used with integrated authentication. (Microsoft SQL Server, Error 18452).
Please help.

A: Given that you state the servers are in different domains ... the first comment from @squillman gives the answer. You must do one of the following:

*

*establish a domain trust between the domains

*Create an identical local (non-domain) user on each server, and use that in your connectionstring per @Charlieface, this won't work.

*switch to a SQL login rather than using a Windows account


text:
Q: How to fix kendo header not displaying header content Working with a kendo grid and have a several different columns with header text for each. I am trying to display "Datasheet" in the header cell for this columns but it's not showing. Not sure if I am writing this incorrectly or missing something entirely. Any help on how to get the header text to display is appreciated.
columns.Bound(a => a.ProductRoot.Name).ClientTemplate(
  "#= ProductRoot.Name # "
  ).Title("Product").HtmlAttributes(new { @class = "product-column-standard" }).HeaderHtmlAttributes(new { @class = "product-column-standard" });

columns.Bound(a => a.ProductBuyLink).ClientTemplate(
  "" + ""
  ).Title("Datasheet").HtmlAttributes(new { @class = "product-column-standard" }).HeaderHtmlAttributes(new { @class = "product-column-standard" });

columns.Bound(a => a.ProductRoot.ProductConfigurationType).Title("Configuration").HtmlAttributes(new { @class = "product-column-standard" }).HeaderHtmlAttributes(new { @class = "product-column-standard" });

A: Use .HeaderTemplate("???"); instead
Here is how: https://demos.telerik.com/aspnet-mvc/grid/headertemplate


text:
Q: SAS ARIMA modelling for 5 different variables I am trying do a ARIMA model estimation for 5 different variables. The data consists of 16 months of Point of Sales. How do I approach this complicated ARIMA modelling?
Furthermore I would like to do:

*

*A simple moving average of each product group

*A Holt-Winters
exponential smoothing model

Data is as follows with date and product groups:
 Date   Gloves  ShoeCovers  Socks   Warmers HeadWear

 apr-14 11015   3827        3465    1264    772
 maj-14 11087   2776        4378    1099    1423
 jun-14 7645    1432        4490    674     670
 jul-14 10083   7975        2577    1558    8501
 aug-14 13887   8577        6854    1305    15621
 sep-14 9186    5213        5244    1183    6784
 okt-14 7611    4279        4150    977     6191
 nov-14 6410    4033        2918    507     8276
 dec-14 4856    3552        3192    450     4810
 jan-15 17506   7274        3137    2216    3979
 feb-15 21518   5672        8848    1838    2321
 mar-15 17395   5200        5712    1604    2282
 apr-15 11405   4531        5185    1479    1888
 maj-15 11509   5690        4370    1145    2369
 jun-15 9945    2610        4884    882     1709
 jul-15 8707    5658        4570    1948    6255

Any skilled forecasters out there willing to help? Much appreciated!


text:
Q: call function on button click in handlebars I have been tryinng to call a function on button click in handlebars view,
but unable to do so.
Now, I am new to it and maybe somehow missing the obvious. would love some help on this.
basically, it's a table which I am creating dynamically, but unable to call the function on button click.
here's the relevant code inside calendar.hbs
 {{#each events}}

        {{this.subject}}
        {{this.start.dateTime}} ({{this.start.timeZone}})
        {{this.end.dateTime}} ({{this.end.timeZone}})

            {{#each this.attendees}}

                {{this.emailAddress.name}}

            {{/each}}

        {{this.location.displayName}}
        <button onclick="editEvent({{this}})" >Edit</button>

    {{/each}}

and I have put the function in layout.hbs
inside script tag like this

but I still get an error saying "Uncaught SyntaxError: Unexpected identifier"
please tell me where am I going wrong.
now, I also tried doing it in app.js like this
hbs.registerHelper("editEvent", function(event) {
  console.log('event : ',event);
  });

and then used in in calendar.hbs like
Edit
and it was working I could see it in the console. but the problem was that it seemed to be calling the function on load and it kind of was automatically calling the function for all rows of the table on load... which I dont want.
so, what is the best way to do it?
EDIT:
I looked at the html there and it shows up like this
okay, I looked at it and it's showing up as
<button onclick="editEvent([object Object])" >Edit</button>

not sure how to fix it though.
I am not sure why you marked it as duplicate.
The questions linked to - dont answer the question I have . But if you do feel that my question is answered here, then please at least send me a message with how to fix my problem.


text:
Q: Printing variables of different derived class objects inside a single vector So I have this simple code with one base class and 2 derived classes. Each derived class has it's own variable and the base class has an id variable which should be shared with all the elements I create from the derived classes.
After creating 2 objects and adding them in a vector, I can only print their IDs. Is there any way I can get the a and b variables from the corresponding element(s)? (ex: std::cout << items[0]->a;)
class Item
{
public:
    int id;
    Item(int id) { this->id = id; }
};

class ItemTypeA : public Item
{
public:
    int a;
    ItemTypeA(int a, int id) : Item(id) { this->a = a; }
};

class ItemTypeB : public Item
{
public:
    int b;
    ItemTypeB(int b, int id) : Item(id) { this->b = b; }
};

int main()
{
    std::vector<std::shared_ptr<Item>> items;
    items.push_back(std::make_unique<ItemTypeA>(2, 0));
    items.push_back(std::make_unique<ItemTypeB>(3, 1));

    std::cout << items[0]->// I wanna print the a variable but it only lets me print the ID;

    return 0;
}

A: One of the possible solutions is using virtual functions like in the following example. Take a look for the Print() methods below...
class Item
{
public:
    int id;
    Item(int id) { this->id = id; }
    virtual void Print(std::ostream& os) { os << id << " "; }
};

class ItemTypeA : public Item
{
public:
    int a;
    ItemTypeA(int a, int id) : Item(id) { this->a = a; }
    void Print(std::ostream& os) override { Item::Print( os ); os << a << std::endl; }
};

class ItemTypeB : public Item
{
public:
    int b;
    ItemTypeB(int b, int id) : Item(id) { this->b = b; }
    void Print(std::ostream& os) override { Item::Print( os ); os << b << std::endl; }
};

int main()
{
    std::vector<std::shared_ptr<Item>> items;
    items.push_back(std::make_unique<ItemTypeA>(2, 0));
    items.push_back(std::make_unique<ItemTypeB>(3, 1));

    for ( auto& el: items ) { el->Print(std::cout); }
}


text:
Q: What's a good visualization for Poisson regressions? I want to associate code defects with code complexity metrics like closeness. One common model is to view this as a Poisson process, where the duration is how much time is spent coding and the density is a function of the code complexity. I am able to do a regression and get significance values etc.
However, it's hard for me to visualize the results (and even harder for my less mathematically inclined colleagues). Is there a good way to view this to look at things like outliers, if it's a linear trend etc.? (Links to R packages are appreciated.)
For example, I could just plot Defects / Time ~ Complexity but this is fairly noisy and since Defects is discretized and very small, it's hard to view the trend. One thing I was thinking of is that I could slice the data into quantiles and then do a regression per quantile and plot the resulting densities - I'm not certain how valid this is though, especially since my data are not normally distributed so it might mislead people about what a quantile is.

A: After you've fit the model, why not use predicted defects as a variable to compare to the others using whatever standard techniques are meaningful to them?   It has the advantage of being a continuous variable so you can see even small differences.  For example, people will understand the difference between an expected number of defects of 1.4 and of 0.6 even though they both round to one.
For an example of how the predicted value depends on two variables you could do a contour plot of time v. complexity as the two axes and colour and contours to show the predicted defects; and superimpose the actual data points on top.
The plot below needs some polishing and a legend but might be a starting point.

An alternative is the added variable plot or partial regression plot, more familiar from a traditional Gaussian response regression.  These are implemented in the car library.  Effectively the show the relationship between what is left of the response and what is left of one of the explanatory variables, after the rest of the explanatory variables have had their contribution to both the response and explanatory variables removed.  In my experience most non-statistical audiences find these a bit difficult to appreciate (could by my poor explanations, of course).

#--------------------------------------------------------------------
# Simulate some data
n<-200
time <- rexp(n,.01)
complexity <- sample(1:5, n, prob=c(.1,.25,.35,.2,.1), replace=TRUE)
trueMod <- exp(-1 + time*.005 + complexity*.1 + complexity^2*.05)
defects <- rpois(n, trueMod)
cbind(trueMod, defects)

#----------------------------------------------------------------------
# Fit model
model <- glm(defects~time + poly(complexity,2), family=poisson)
# all sorts of diagnostic checks should be done here - not shown

#---------------------------------------------------------------------
# Two variables at once in a contour plot

# create grid
gridded <- data.frame(
    time=seq(from=0, to=max(time)*1.1, length.out=100),
    complexity=seq(from=0, to=max(complexity)*1.1, length.out=100))

# create predicted values (on the original scale)
yhat <- predict(model, newdata=expand.grid(gridded), type="response")

# draw plot
image(gridded$time, gridded$complexity, matrix(yhat,nrow=100, byrow=FALSE),
    xlab="Time", ylab="Complexity", main="Predicted average number of defects shown as colour and contours\n(actual data shown as circles)")
contour(gridded$time, gridded$complexity, matrix(yhat,nrow=100, byrow=FALSE), add=TRUE, levels=c(1,2,4,8,15,20,30,40,50,60,70,80,100))

# Add the original data
symbols(time, complexity, circles=sqrt(defects), add=T, inches=.5)

#--------------------------------------------------------------------
# added variable plots

library(car)
avPlots(model, layout=c(1,3))

A: So you run a poisson regression on the count data variable "defects" and want to visualize significant differences. What you do when you estimate that regression is estimate the conditional mean $E[y_i| x_i]$, where $y_i$ are the defects and $x_i$ are your regressors, like code complexity.
The easiest way to visualize it is to just take two different values for $x_i$, e.g., high complexity and low complexity, and then plot the predicted frequency of $y_i=0, y_i=1$ etc. for both complexity levels. The resulting histogram would look like this on slide 3. If the differences are strong, the histrograms of those frequencies will look very different (e.g., many zeros for low complexity and many high defects for high complexity). It might look nice of you overlay these two histograms, or you plot the difference in predicted defects.
If you feel reducing your $x_i$ to 2 categories is oversimplification, you can do the same for any discrete set of $x_i$, but it doesn't make for a good visual presentation if you throw more than, say, 4 graphs at your audience at once.
Alternatively, if your $x_i$ is continuous, you could plot one predicted count (e.g., defects=0) depending on that $x_i$. Maybe this results in a nice monotone fuction that is in line with your results.
Btw: have your also run a negative binomial regression on your data? Are the results very different? If so, your Poisson assumption (conditional mean equal to conditional variance) might be too restrictive (see "overdispersion"). That could be the case, for example, if your variable "defect" has many zeros.


text:
Q: End of the execution too long using Pool.starmap I'm executing a paralelized function using Pool.starmap function. The execution of the function it self only takes 6.5 minutes according to tqdm library but the program stays in execution for 20 min more until it finishes. The function is processing and applying filters to some strings in some colums of a pandas dataframe. A different paralelized function could perform better? There is something wrong with starmap function?
Functon to be executed:
def get_best_string_filters(hst, apolnmar, apolnmod, apolnsub, apolnterm, amodnanu, ps, cc, cilindros, combustible, gearbox, year, search_model, search_version, search_container):
    select = table_ecode[(table_ecode.HST == hst)]

    year = int(year[-4:])

    select = initial_selection(select, ps, cc, cilindros, combustible, gearbox, year)

    temp = get_starting_selection(select.copy(), search_model, "HTB")
    if temp.empty:
        search_model, search_version, search_container = find_best_combination(select, search_model, search_version, search_container)
    else:
        select = temp.copy()
        _, search_version, search_container = find_best_combination(select, "", search_version, search_container)

    #print(search_model, search_version, search_container)

    return [apolnmar, apolnmod, apolnsub, apolnterm, amodnanu, search_model, search_version, search_container]

starmap call:
if not exists("dict_search_ammo_make_version_fixed.npy"):
    params = [(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) for a, b, c, d, e, f, g, h, i, j, k, l, m, n, o in values_to_change.values]
    with Pool(mp.cpu_count()) as ex:
        array_split_ammo_make_version = ex.starmap(get_best_string_filters, tqdm(params, total=len(params)))
        dict_split_ammo_make_version = array_to_dict(array_split_ammo_make_version)
        # save the dict to disk for faster future executions
        np.save("dict_search_ammo_make_version_fixed.npy", dict_split_ammo_make_version)
else:
    dict_split_ammo_make_version = np.load('dict_search_ammo_make_version_fixed.npy',allow_pickle='TRUE').item()

tqdm outputs 6.5 minutes and a completed status but the script continues to run for 20 long minutes:

A: In the demos below, generator function params simulates generating arguments to worker function foo slowly and foo, which just returns the passed argument, which is either a list when using imap or individual arguments that are the elements of a list.
Using imap
import time

def foo(the_list):
    time.sleep(10)
    return the_list

if __name__ == '__main__':
    from tqdm import tqdm
    from multiprocessing import Pool

    def params():
        for i in range(1, 9):
            time.sleep(1)
            yield list(range(i))

    with Pool() as ex:
        it = ex.imap(foo, params())
        results = list(tqdm(it, total=8))
    print(results)

Using apply_async
import time

def foo(*args):
    time.sleep(10)
    return args

if __name__ == '__main__':
    from tqdm import tqdm
    from multiprocessing import Pool

    def params():
        for i in range(1, 9):
            time.sleep(1)
            yield list(range(i))

    def my_callback(result):
        bar.update(1)

    with Pool() as ex, tqdm(total=8) as bar:
        results = []
        async_results = [ex.apply_async(foo, param, callback=my_callback) for param in params()]
        results = [async_result.get() for async_result in async_results]
    print(results)

imap with fixed sized tuples
import time

def foo(tpl):
    time.sleep(10)
    # unpack:
    a, b, c, d, e, f, g, h = tpl
    return (a + b) * (c +  d) * (e + f) * (g + h)

if __name__ == '__main__':
    from tqdm import tqdm
    from multiprocessing import Pool

    def params():
        for i in range(1, 9):
            time.sleep(1)
            yield list(range(8))

    with Pool() as ex:
        it = ex.imap(foo, params())
        results = list(tqdm(it, total=8))
    print(results)


text:
Q: ReactJS looping executeAction I have two react modals defined with onAfterOpens like so:
import React from 'react';
import JobList from './JobList';
import RightPanel from './RightPanel';

import LoadJobsScreen from '../../actions/jobs-screen/LoadJobsScreen';
import UserStore from '../../stores/UserStore';
import LoadUsers from '../../actions/global/LoadUsers';
import LoadUsersByDepartment from '../../actions/global/LoadUsersByDepartment';
import Modal from 'react-modal';

export default class JobScreen extends React.Component {

    static contextTypes = {
        executeAction: React.PropTypes.func.isRequired,
        getStore: React.PropTypes.func.isRequired
    };

    componentWillMount() {
        this.displayName = 'JobScreen'
        this.state = {
            traderModalOpened: false,
            OFTModalOpened: false,
            users: this.context.getStore(UserStore).getUsers(),
        }
        this.context.getStore(UserStore).on('change', () => {
            this.setState({
                users: this.context.getStore(UserStore).getUsers()
            });
        });
        this.context.executeAction(LoadJobsScreen, this);
    }

    toggleTraderModal() {
        this.setState({
            traderModalOpened: !this.state.traderModalOpened
        });
        console.log(this.state.traderModalOpened);
    }

    toggleOFTModal() {
        this.setState({
            OFTModalOpened: !this.state.OFTModalOpened
        });
        console.log(this.state.OFTModalOpened);
    }

    render() {
        var users = [];
        this.state.users.forEach((user) => {
            users.push(
                <option value={user.id}>{user.firstName}</option>
            );
        });
        return (

<JobList toggleTraderModal={this.toggleTraderModal.bind(this)} toggleOFTModal={this.toggleOFTModal.bind(this)}/>

<RightPanel />

                <Modal
                    isOpen={this.state.traderModalOpened}
                    className="modal-dialog"
                    overlayClassName="modal show"
                    onAfterOpen={this.context.executeAction(LoadUsersByDepartment, 5)}
                    >

                            <button type="button" onClick={this.toggleTraderModal.bind(this)} className="close" data-dismiss="modal" aria-label="Close">×</button>

Set trader

                            <select>
                                {users}
                            </select>

                            <button type="button" onClick={this.toggleTraderModal.bind(this)} className="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="button" className="btn btn-primary">Save changes</button>

                </Modal>
                <Modal
                    isOpen={this.state.OFTModalOpened}
                    className="modal-dialog"
                    overlayClassName="modal show"
                    onAfterOpen={this.context.executeAction(LoadUsersByDepartment, 8)}
                    >

                            <button type="button" onClick={this.toggleOFTModal.bind(this)} className="close" data-dismiss="modal" aria-label="Close">×</button>

Set OFT member

                            <button type="button" onClick={this.toggleOFTModal.bind(this)} className="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="button" className="btn btn-primary">Save changes</button>

                </Modal>

        );
    }
}

My action:
import qwest from 'qwest';

export default function LoadUsersByDepartment(actionContext, payload) {
    return qwest.get('/users/fetch/department', {department_id: payload}, {responseType: 'json'})
        .then(function (response) {

            actionContext.dispatch('RECEIVED_USERS_DATA', {data: response.response})

        })
};

But in my console I am seeing that the actions are being called constantly. What is happening and how do I get it to just perform the action when the modal is opened?

A: Just a quick shot here. Try this one, instead of existing statement
<Modal
  ...
  onAfterOpen={() => this.context.executeAction(LoadUsersByDepartment, 8)}
  ...
>

What your code does is:
when modal is opened, execute the result from this.context.executeAction(LoadUsersByDepartment, 8) call.
Adjusted code executes your action (not it's result) when modal is opened.


text:
Q: Playstation network signed me out? So I recently turned on my PS4 & my PSN account was signed out, unfortunately I don't know my password nor do I have access to the email address associated with the account. I've never experienced this before though so I'm curious as to why my account was signed out? My account has remained logged into without requiring authentication for over a year..
So I have three questions,
#1 - If I were to be banned from PSN for whatever reason, would I have been logged out automatically, or would I be prompted with a dialogue stating I'm banned.
#2 - Is this normal? Is it a regular occurence for you to be randomly signed out of PSN ( I mean I would assume not, since I've been logged in for over a year.
#3 - Is it possible someone changed my password whilst I was inactive? and so due to crednetials changing I was signed out to reauthenticate my credentials.

A: If you were inactive, sometimes the console will prompt for your password to check up on security preferences, and to make sure it is you. I find it happens about every 6-12 months (even if I'm active), but that is just a guess on my part. Normally, I am able to still browse on my profile and see my Games and Apps, but just unable to use PSN services.
If you do not know your password and do not have the email, I am not sure what you can do to access the PSN account.

A: The only times I remember being signed out of PSN suddenly, are:

*

*When there's been an error on my network

*When there's been a more generalised PSN crash/error (usually more than one player experiences this)

*When PSN has updated itself and the TOS have changed

If you don't have the password or access to the email account, you're pretty screwed. Unless you can message and convince PSN staff that you did have access to the email until recently, but lost it for whatever reason. But that is a very optimistic outlook.
Question #1

How do I know if my account or console has been suspended from PSN?
If we suspend your account or PlayStation console, you will see an error code when
attempting to sign in to PSN.
We usually email you explaining why you've been suspended and how long it will last.
We send that to the email address associated with your account (your sign-in ID). Be
sure to check your junk or spam folder for the email.

- PlayStation suspension info


text:
Q: Nested apply function: variable confusion I have a bit of code which uses a nested apply function.  It is a bit unusual, because it uses a list of functions which it then feeds into the FUN argument of the inner vapply.
Here is the code line:
J <- sapply(X = J.int, FUN = vapply, X = t.vec, FUN.VALUE = numeric(1))

where J.int is a list of functions generated by approx.fun.  As may be predicted, the code gets confused about argument X.  I have a solution, which I will post below, but it doesn't seem very elegant.  If anyone can create a function which is easily generalisable for all the apply functions, or suggest an alternative solution, I would like to see that answer.
For reproducibility, use:
J.lst <- list(data.frame(t = 0.5:9.5, J = rnorm(10, 5, 1)), data.frame(t = 0.5:9.5, J = rnorm(10, 6, 3)))
J.int <- lapply(J.lst, function(df) approxfun(df[, 1] + t.0, df[, 2], yleft = 0, yright = 0))
t.vec <- 1:10
t.0 <- 0

A: My current solution, referred to in the question, is to use:
applyntd <- function(appFUN = apply, Xntd, FUNntd, MARGINntd, FUN.VALUEntd, simplifyntd, USE.NAMESntd, ...){
  appFUN <- match.fun(appFUN)
  if(identical(appFUN, apply)) return(function(Xntd, MARGINntd, FUNntd, ...) apply(X = Xntd, MARGIN = MARGINntd, FUN = FUNntd, ...))
  if(identical(appFUN, lapply)) return(function(Xntd, FUNntd, ...) lapply(X = Xntd, FUN = FUNntd, ...))
  if(identical(appFUN, sapply)) return(function(Xntd, FUNntd, ..., simplifyntd = T, USE.NAMESntd = T) sapply(X = Xntd, FUN = FUNntd, ..., simplify = simplifyntd, USE.NAMES = USE.NAMESntd))
  if(identical(appFUN, vapply)) return(function(Xntd, FUNntd, FUN.VALUEntd, ..., USE.NAMESntd = T) vapply(X = Xntd, FUN = FUNntd, FUN.VALUE = FUN.VALUEntd, ..., USE.NAMES = USE.NAMESntd))
}

and then:
J <- sapply(X = J.int, FUN = applyntd(vapply), Xntd = t.vec, FUN.VALUEntd = numeric(1))

This works, but the applyntd function seems cumbersome.  Let me know if you have better/ more generalisable ideas.


text:
Q: rails geocoder undefined method `full_street_address' i tried to add the gem Geocoder to my App, but i can't figure out how i get the Geotagging to work.
My Model looks like this:
class Home < ActiveRecord::Base

  geocoded_by :full_street_address
  after_validation :geocode
end

And i my Form i added a field for full_street_adress
<%= form_for(@home) do |f| %>
    <%= text_field_tag :full_street_address %>
    <%= f.submit %>
<% end %>

When i try to add a new Home, I get the following error

undefined method `full_street_address' for #

Extracted source (around line #10):
def create
    home = Home.new(params[:home])
    home.save && home.home_memberships.create(:user => current_user, :owner => true)
end

def AddMember

A: You're using wrong key :home in params. Should be

def create
    home = Home.new(params[:full_street_address])
    home.save && home.home_memberships.create(:user => current_user, :owner => true)
end

BTW, in the form you missed f and label (if needed)
<%= form_for(@home) do |f| %>
    <%= f.label :full_street_address, "Home address" %>
    <%= f.text_field_tag :full_street_address %>
    <%= f.submit %>
<% end %>


text:
Q: Perl regex - Find functions in C file and print their definitions -- UPDATED --
I want to find C functions in file and print their definitios
For example:
For this input:
#include <stdlib>

int function(int a)
{
    return a;
}

void func2()
{
    int b = 1;
}

int func3(int a,int b)
{
   a = a +b;
        while(x) {
            x--;
        }
   return a;
}

int main(int argc, char* argv[])
{
    int x=(a+1);
    return 0;
}

The output should be:
int function(int a);
void func2();
int func3(int a,int b);

This is my code:
#!/usr/bin/perl -w
open(FILE, "<", $ARGV[0]) or die "file open error";

if ( @ARGV ) #if there are args
{
    if ( -f $ARGV[0] ) #if its regular file
    {

    while(<FILE>)
      {
      if ($_ =~ /(.+)\s(.+)\(/){
      print $1; # type in arg $1
      print "\n";
      print $2; # name in arg $2
      print "\n";
    }
      }
    }
    else{
print "Arg is not a file\n";}
}
else{
print "no args\n";}

I end with function type in arg $1 and function name in $2. I want to get the full name and args in '()' brackets in $2. How to avoid 'main' word? the     '^[(main)] doesnt work. In the end I want to print it all with ';' at the end.
It needs to check for {} brackets to not print for example:    int x=(a+1);

A: Try /(\S+)\s+(\S+\([^)]*\))/ and then print $1+$2+";\n".
To prevent main with negative lookahead:
/(\S+)\s+((?!main)\S+\([^)]*\))/

If lookahead is not supported:
/(\S+)\s+((m|ma|mai|[^m].*|m[^a].*|ma[^i].*|mai[^n].*)\([^)]*\))/

The part responsible for avoiding main:
(m|ma|mai|[^m].*|m[^a].*|ma[^i].*|mai[^n].*)


text:
Q: Eclipse Luna Dark theme, syntax coloring resets. How to disable? Original Question: Eclipse luna theme issue
Related Question: How to make Eclipse color settings permanent?
TL;DR Eclipse Luna 4.4, Dark theme, Win 7 64bit, some settings reset to an initial value on start. How to make them stay the way i configured them ?
Examples: Java Syntax Coloring, enums are italics with the dark theme, i dont want them italics tho...
Additional Research
In the workspace\.metadata\.plugins\org.eclipse.core.runtime.settings\org.eclipse.jdt.ui.prefs file there is a tag named overriddenByCSS that seems to cause this issue. It only exists if the dark theme is used. I looked into the CSS files of the dark theme but couldnt find anything related...
Also removing or changing the line manually doesnt work, it gets written every start of eclipse.
Why do i ask ?
Even tho the "How to ask" mentions that a new question should be different to an allready existing one, i dont have enough reputation to comment on the original question and add details to it. So i tried in the form of an answer, but someone "thought" it was a good idea to delete my answer (that wasnt really answering, just adding more details...). So, well, lets just flood SO with duplicates then...
EDIT:
I posted a bug at the eclipse bugzilla

A: A few days ago a comment was added to your Eclipse bug report and I have been able to successfully workaround this issue using that advice. It's tedious, but it worked for me.
Before you get started, remember these things:

*

*Eclipse will load your preferences on startup, overwrite them with overriddenByCSS=, etc. and then restore your original settings file on exit. This means that all changes you make to org.eclipse.jdt.ui.prefs should be made while Eclipse is not running.

*Comparing this file while Eclipse is running to the version while Eclipse is not running will help you identify the changes you need to make to preserve your colors.

*Use your preferred version control system to manage these files. This will ensure that you don't lose them in the future and will help you see how Eclipse is changing your preferences when it starts. I will use Mercurial below.
Follow these steps to switch to the Dark theme while preserving control over your syntax colors:

*

*Exit Eclipse and put the core runtime settings under version control:
cd [eclipse workspace]/.metadata/.plugins/org.eclipse.core.runtime/.settings
hg init
hg add .
hg ci -m "before dark"

*Start Eclipse and switch to the Dark theme and then Exit Eclipse.

*Verify that only the theme changed and save the changes to a branch:
hg diff
hg branch dark
hg ci -m "after dark"

*Start Eclipse again and while Eclipse is running, compare the files to what you just checked in. You will see the new overriddenByCSS value which will reference all of the values that were added by Eclipse on startup. Do a diff and keep note of what was changed and before you exit Eclipse, save these overrides.
hg diff
hg ci -m "eclipse overrides"

*Exit Eclipse and you will notice that the changes are gone. Restore the changes it made when it was running:
hg revert .

*Edit org.eclipse.jdt.ui.prefs and remove the line that starts with overriddenByCSS. This will make the other overrides values stick. Save these changes.
hg ci -m "the overrides are now mine"

*Start and Exit Eclipse and verify that Eclipse didn't make any changes to your file.
hg diff

*Now that the overrides are yours, you are free to change them. For the example you mentioned, enums in italic, edit org.eclipse.jdt.ui.prefs and set semanticHighlighting.enum.italic=false

*If you ever want to go back to your default before you started this, you can switch between branches using:
hg up -r default
hg up -r dark

*Important note: If you change syntax color preferences using Eclipse, you'll notice that the overriddenByCSS value comes back when Eclipse is running and your preferences will disappear. Periodically monitor your preference files for changes and commit them when you like them. Revert them when you don't.
Here is what my Eclipse looks like now with all of the colors that I originally tweaked before switching to the Dark theme:

A: On Eclipse 4.6 (Ubuntu) the solution that worked for me is the following:

*

*Set the Dark theme (before setting any color scheme)

*Edit the file org.eclipse.e4.ui.css.swt.theme.prefs under .metadata/.plugins/org.eclipse.core.runtime/.settings

*Copy the used theme id (in my case themeid=org.eclipse.e4.ui.css.theme.e4_dark)

*Set any other theme than dark.

*Set your desired scheme

*Quit eclipse

*Edit again org.eclipse.e4.ui.css.swt.theme.prefs

*Replace the themeid with the copied value.

*Restart eclipse.

A: Just go to window->preferences->oomph->setup tasks, and enable skip automatic task execution at startup time

A: To set up Dark theme as a "global" theme, and the theme you like from Eclipse Color Theme that you installed from Market Place, you can do the following. I used:

*

*windows 10 (64 bit, but for 32 bit is probably the same)

*eclipse oxygen

Steps:

*

*Set the "global" theme to the dark theme: (Windows>Preferences>General>Appearance>Theme:Dark)

*close eclipse. (You can change the Color Theme to let's say Recogn Eyes -which is my favorite-)

*Re-open eclipse. (If you changed the Color theme you will have the default for the Dark theme, since you are reading this)

*Open File explorer and look for C:\Users\[user]\eclipse-workspace\.metadata\.plugins\org.eclipse.core.runtime\.settings

*Open org.eclipse.e4.ui.css.swt.theme.

*Copy text after =, and keep that in your clipboard , in my case it was org.eclipse.e4.ui.css.theme.e4_dark

*(In eclipse) Set the schema to default, and close the application.

*open eclipse and choose your favorite color theme.

*Close eclipse.

*Go to the file org.eclipse.e4.ui.css.swt.theme again and paste what was in the clipboard (themeid=org.eclipse.e4.ui.css.theme.e4_dark, in my case) after the =.


text:
Q: Under what conditions on $A \subseteq X^2$ is the function $F_A(\gamma) := \gamma(A)$ l.s.c on the space of finite Borel measures $\mathscr M(X^2)$? Let $X$ be a topological space (assumed to be Polish, if that helps) and let $\mathscr M(X^2)$ be the space of finite Borel measures on the product space $X^2$. Let $A$ be a nonempty subset of $X^2$.

Question. Under what conditions (on the subset $A$)  is the function $F_A:\mathscr M(X^2) \to \mathbb R$ defined by $F_A(\gamma) := \gamma(A)$ lower-semicontinuous ?

A: We might as well work on $X$ instead of $X^2$, since the product plays no role here.  I will assume only that $X$ is a metric space, and that $\mathscr{M}(X)$ carries the weak topology.
The answer is that $F_A$ is lsc if and only if $A$ is open.
The key fact is that in a metric space, for an open set $A$, the indicator function $1_A$ can be written as an increasing pointwise limit of a uniformly bounded sequence of  continuous functions $f_n$.  Indeed, we can take $f_n(x) = \min(1, n \cdot d(x, A^c))$.  Therefore if we let $F_n(\gamma) = \int f_n\,d\gamma$, the function $F_n$ is continuous on $\mathscr{M}(X)$, and the monotone convergence theorem shows that $F_n(\gamma) \uparrow F_A(\gamma)$ for each $\gamma$.  Thus $F_A$ is lsc.
Conversely, if $A$ is a set with $F_A$ lsc, let $x_n \in A^c$ with $x_n \to x$.  Letting $\delta_{x_n}$ be the corresponding Dirac measures, we have $\delta_{x_n} \to \delta_x$ in the weak topology.  Now $F_A(\delta_{x_n}) = 0$ for each $n$, so by lower semicontinuity $F_A(\delta_x) \le 0$, which is to say $x \notin A$.  So we have shown $A^c$ is closed.


text:
Q: Find a continuous function with the following properties: Part A: Let $H = \{z \in \mathbb{C} \; \rvert \; \text{Re}(z) \geq 0\} \setminus\{0\}$. Specifying any branch cuts you may use, find a continuous function $f:H \to \mathbb{R}$ such that

*

*$f$ is harmonic in $H$.

*$f(z)=1$ on the positive imaginary axis.

*$f(z) = 0$ on the negative imaginary axis.
Part B: Let $D = \{z \in \mathbb{C} \; \rvert \; |z| \leq 1\} \setminus\{-1,1\}$. Specifying any branch cuts you may use, find a continuous function $g:D \to \mathbb{R}$ such that

*

*$g$ is harmonic in $D$.

*$g(z)=1$ for $|z|=1$, $\text{Im}(z)>0$.

*$g(z)=1$ for $|z|=1$, $\text{Im}(z)<0$.
My attempt:
For part A: Using the principal branch of the logarithm, i.e. not allowing $(-\infty,0]$, we have that $\text{Log}(z) = \ln|z| + i\text{Arg}(z)$ is analytic, hence its real and imaginary parts are harmonic. Thus $\text{Arg}(z)$ is harmonic. To get properties 2 and 3, I'll just define $f$ as the following:
$$ f(z) = \frac{\text{Arg}(z) + \pi/2}{\pi}$$
For part B: I am not sure. I found a solution for part A reasoning through it intuitively, but I can't seem to find anything for part B this way. I'm wondering if there is a better technique for solving problems like this that I'm just unaware of.


text:
Q: Custom DelegatingHandler unsuccessful status code handling I have a custom DelegatingHandler that scans calls to the back-end watching for 401 (cookie expired) and redirects the browser to relogin.
protected override async Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request,
    CancellationToken cancellationToken)
{
    var response = await base.SendAsync(request, cancellationToken);

    // Server returned 401 Unauthorized, redirect to login page
    if (response.StatusCode == HttpStatusCode.Unauthorized)
        _authenticationStateProvider.SignIn();

    return response;
}

The problem is that before the redirect happens in the browser, an unhandled exception is thrown due to the 401.
System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()

This results in a momentary Blazor error bar at the bottom of the page.  What is the best way to handle this?  I don't want to wrap up every http call in a try/catch.  Should I be looking at Error Boundaries?  Is there something better?

A: I had the same issue. I used try to catch the Unauthorized and Forbidden exceptions since those are the ones I'm redirecting on but since I have many http calls, I decided to create a service instead that wraps the calls and just return the data I need or an empty result. As for error boundaries, I have an <ErrorBoundary> set at the page level but this is for unhandled exceptions so I don't recommend them for this.
Here's an example of my solution:
Service
  public class MyHttpService
  {
    public MyHttpService(IHttpClientFactory httpClientFactory)
    {
      _httpClientFactory = httpClientFactory;
    }

    public async Task<T> GetData<T>(string requestUri) where T : new()
    {
       var http = _httpClientFactory.CreateClient("SecureClient");

       try
       {
          var response = await http.GetAsync(requestUri);
          var result = await response.Content.ReadFromJsonAsync<T>();
          return result;
       }
       catch (HttpRequestException ex) when (ex.StatusCode is Unauthorized || ex.StatusCode is Forbidden)
       {
          Console.WriteLine("redirecting");
          return new T();
       }
     }

    //....put, post, delete methods

  }

Component
     protected async override Task OnInitializedAsync()
     {
       var students= await _httpService.GetData<List<Students>>("api/students");
     }

Custom delegate handler
You can call EnsureSuccessStatusCode() before returning your response so it
can throw the exception, if not successful, and go to the catch block in the
service.
    response.EnsureSuccessStatusCode();
    return response;


text:
Q: What does "in the middle of the/a pack" mean? Does this expression mean something like "in the middle of some score list", or "average level"?

A: Yeah, it means not outstanding but not failing.
For example, I will reference cleveland.com site (no offence intended).

U.S. students in the middle of the pack on financial smarts

Means that US students are not awful at understanding the value of money, but not brilliant. Of the countries / places surveyed, they came about the middle.
As far as I know, there is no technical definition, however I would have thought that for it to be correct, it would be between the Upper and Lower Quartiles (Q1 and Q3).
Article from cleveland.com

A: It means 'average', not outstanding by any quality.

*

*American 15-year-olds are middle of the pack in reading, survey shows

*THE FIRST major international study of reading in a decade shows that American 15-year-olds are about as proficient at reading as they are at mathematics and science. They're adequate but not very good - the definition of mediocre.

Source: http://articles.baltimoresun.com
Note: What does MOTP stand for?
  MOTP stands for Middle of the Pack

*

*This definition appears very rarely and is found in the following Acronym Finder categories: Slang/chat, popular culture

Source: www.acronymfinder.com


text:
Q: How to evaluate the following integral? $\int \ln(e^x + c)~\mathrm dx$ I can't seem to find an answer for this kind of integration, and I'd like to know if there is an answer for it, and if yes what is it.
$$\int \ln(e^x + {c})~\mathrm dx\,,$$
where $c$ is a constant.
My teacher keeps avoiding me after I asked him, so I appreciate any help because I've tried everything I know.

A: I'm assuming $c >0$.
Let $u =e^{x}$.
Then $du = e^{x} \ dx = u \ dx$.
And
$$ \begin{align} \int \log(e^{x} + c) \ dx &= \int \frac{\log(u+c)}{u} du \\ &= \int \frac{\log(c(1+\frac{u}{c}))}{u} \ du \\ &= \log (c) \int \frac{1}{u} \ du + \int \frac{\log(1+\frac{u}{c})}{u} du \\ &=\log(c) \log (u) - \text{Li}_{2} \left(-\frac{u}{c} \right) + C  \\ &= \log(c) \log(e^{x}) - \text{Li}_{2} \left(-\frac{e^{x}}{c} \right) + C  \\ &= x \log(c) - \text{Li}_{2} \left(-\frac{e^{x}}{c} \right) + C \end{align}   $$
where $\text{Li}_{2}(x)$ is the dilogarithm function.
EDIT:
Similar to what I did above,
$$ \int \ln(e^{x}-c) \ dx = x\log(c) + \int \frac{\log(\frac{u}{c}-1)}{u} \ du$$
Let $ \displaystyle v= \frac{u}{c}$.
$$ = x \log(c) + \int \frac{\log (v-1)}{v} \ dv$$
Let $w = v-1$.
$$ \begin{align} &= x \log (c) + \int \frac{\log w}{1+w} \ dw \\ &= x \log(c) + \log(w) \log(1+w) - \int \frac{\log(1+w)}{w} \ dw \\ &= x \log(c) + \log(w) \log(1+w) + \text{Li}_{2}(-w) + C \\ &= x \log(c) + \log \left(\frac{e^{x}}{c}-1\right)\log\left(\frac{e^{x}}{c}\right) + \text{Li}_{2} \left( 1-\frac{e^{x}}{c} \right) + C \end{align}$$
This is not in the form given by Wolfram Alpha.
But using it to evaluate some definite integrals for specific values of $c$, it appears to be correct.

A: Another approach is
$$
\begin{align}
\int\log(e^x+c)\,\mathrm{d}x
&=\frac{x^2}{2}+\int\log(1+ce^{-x})\,\mathrm{d}x\\
&=\frac{x^2}{2}+\int\left(ce^{-x}-\frac{c^2}{2}e^{-2x}+\frac{c^3}{3}e^{-3x}-\dots\right)\,\mathrm{d}x\\
&=\frac{x^2}{2}+\left(-ce^{-x}+\frac{c^2}{2^2}e^{-2x}-\frac{c^3}{3^2}e^{-3x}+\dots\right)+C\\
&=\frac{x^2}{2}+\mathrm{Li}_2\left(-ce^{-x}\right)+C
\end{align}
$$
which should be the same as Random Variable's answer using the Inversion Formula proven in this answer:
$$
\mathrm{Li}_2(x)=-\frac{\pi^2}{6}-\mathrm{Li}_2(1/x)-\frac12\log(-x)^2
$$


text:
Q: I am using ubuntu14.04. I have installed numpy in python3, but it is not in python2.7. I have installed both python3-numpy as well as python-numpy from the App store. But then, numpy only works on python3. I want it to work on python2.7 also.

A: I have solved the issue. This problem was caused by my earlier installation of another software, which is called PSI4. PSI4 is a quantum chemistry software, which was built in a way that it also includes python2.7.10. Therefore, after the installation, when I typed the command "python", something as below will show up:
cpjwong@cpjwong-OptiPlex-9020:~$ python
Python 2.7.10 |Continuum Analytics, Inc.| (default, Sep 15 2015, 14:50:01)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>>

You can see the company name "Continuum Analytics, Inc.", which implies that the pre-installed python2.7 in ubuntu 14.04 has been overwritten. The numpy for this version of python can be installed by firstly downloading numpy-1.7.0.tar.gz and then run the following command:
tar xvzf numpy-1.7.0.tar.gz
cd numpy-1.7.0/
python setup.py build
python setup.py install
cd ..

Then, you can check whether numpy is properly installed by typing the following command:
cpjwong@cpjwong-OptiPlex-9020:~$ python
Python 2.7.10 |Continuum Analytics, Inc.| (default, Sep 15 2015, 14:50:01)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> import numpy
>>>


text:
Q: Android Studio: Gradle execution failed while building the NDK application This part in the build.gradle file seems to be causing failures to execute the application.
The error message on the console:
Error:Execution failed for task ':app:ndkBuild'.
> Process 'command '/Users/marshall/android-sdks/ndk-bundle/ndk-build'' finished with non-zero exit value 2

the ndkBuild task is the one I defined in the build.gradle file. Here's the code block.
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
    def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
    commandLine "$ndkDir/ndk-build",
            'NDK_PROJECT_PATH=build/intermediates/ndk',
            'NDK_LIBS_OUT=src/main/jniLibs',
            'APP_BUILD_SCRIPT=src/main/jni/Android.mk',
            'NDK_APPLICATION_MK=src/main/jni/Application.mk'
}

tasks.withType(JavaCompile) {
    compileTask->compileTask.dependsOn ndkBuild
}

I double-checked if the directory of the ndk repository is correct, and it doesn't seem to be the reason for the failure.
Here's the entire build.gradle file's source code.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.my.project"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

android {
    sourceSets {
        main {
            jni.srcDirs = []
        }
    }
}
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
    def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
    commandLine "$ndkDir/ndk-build",
            'NDK_PROJECT_PATH=build/intermediates/ndk',
            'NDK_LIBS_OUT=src/main/jniLibs',
            'APP_BUILD_SCRIPT=src/main/jni/Android.mk',
            'NDK_APPLICATION_MK=src/main/jni/Application.mk'
}

tasks.withType(JavaCompile) {
    compileTask->compileTask.dependsOn ndkBuild
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:25.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile project(':openCVLibrary310')
    compile 'com.android.support:appcompat-v7:25.0.0'
}

A: I solved this issue by adding the Android SDK and NDK path to the .bash_profile file as follows.
export ANDROID_HOME=/usr/local/opt/android-sdk
export PATH=${PATH}:/usr/local/opt/android-ndk


text:
Q: Change title of page dynamically in page I have an page (with snippet code and short code and manual php code) and it call a REST API and base Of response, I want change tag title of this page (Not in database).and it was change every call.
i try do :
in snippet code:
$GLOBALS['MyTitle'] = $response-> title;

in function:
function change_title($title) {

        $variable = $GLOBALS['MyTitle'];

        if (!empty($variable))
        {
             $title = $variable;
        }

    return $title;
}
add_filter('pre_get_document_title', 'change_title',500);

but it was empty every time because the function section run sooner then snippet code(Api Call).
WordPress has not any function for change title tag text? like wp_set_title('my title') to use without add_filter?

A: Changing title of the page dynamically by applying the filter the hook used for the filter is document_title_parts. Here is the official wordpress documentation link and below is the example. In this example i have used get method for API.
add_filter( 'document_title_parts', 'function_to_dynamic_title');
function function_to_dynamic_title( $title_parts_array ) {

        $request = wp_remote_get( 'https://dummyjson.com/products/1' );

        if( is_wp_error( $request ) ) {
            return $data;
        }

        $body = wp_remote_retrieve_body( $request );

        $data = json_decode( $body );

        $title_parts_array['title'] = $data->title;

    return $title_parts_array;
}

Screenshot for your reference

A: In WordPress, we have an action to change the title programmatically.
add_filter('the_title','your_callback_function');
function your_callback_function($data)
{
  global $post;
  // add your condition according to page
  return 'Desired Title'. $post->ID;
}


text:
Q: Modify JQuery Object I have a JQuery plugin creating a new object each time I call the plugin's main-function:
Function call:
new BpNotification( options );

Function itself:
function BpNotification( options ) {
    this.init();
}

BpNotification.prototype = {
    init: function() {

        this.t = setTimeout(function(){}, 5000);

    }
}

Is it possible to modify this timeout-option "t" from 'outside' after the object is created?

A: You can change t as you like:
function BpNotification( options ) {
    this.init();
}

BpNotification.prototype = {
    init: function() {
       this.t = setTimeout(function(){alert('default');}, 500);
    }
}

var Bpn = new BpNotification();
clearTimeout(Bpn.t);
Bpn.t = setTimeout(function(){alert('updated!');}, 500);

DEMO

A: You would want to create a setter function to change the setTimeout value, in the prototype object:
BpNotification.prototype = {
    init: function() {
    },
    updateTimeout: function(newVal){
        this.t = setTimeout(function(),newVal);
    }
};

var bpNot = new BpNotification();

bpNot.init();
bpNot.updateTimeout(10000);


text:
Q: My laravel livewire create form keeps giving me errors LONG POST WARNING
why isn't my form to create a new user not working? im using laravel 9 and livewire. This is my code:
this is the button from where i show the model to create a form:

                    <x-jet-input  placeholder="search will go here"/>

                    <x-jet-button wire:click="create">New Skill</x-jet-button>

This is the model that shows the form. this model is also used to edit a skill as per Caleb the livewire creator:
<form wire:submit.prevent="save">
        <x-jet-dialog-modal wire:model.defer="showEditModal">
            <x-slot name="title">Edit Skill</x-slot>

            <x-slot name="content">

                    <x-jet-label for="name" value="{{ __('Skill name') }}" />
                    <select wire:model="editing.name"
                            id="name"
                            type="text"
                            class="mt-1 block w-full border-gray-300
                             focus:border-indigo-300 focus:ring
                              focus:ring-indigo-200 focus:ring-opacity-50
                               rounded-md shadow-sm">
                        @foreach(\App\Models\Skill::LANGUAGES as $value => $label)
                            <option value="{{ $value }}">{{ $label }}</option>
                        @endforeach

                    </select>
                        <x-jet-input-error for="editing.name" class="mt-2" />
                        <x-jet-label for="years" value="{{ __('Years of experience') }}" class="mt-4"/>
                        <x-jet-input wire:model="editing.years" id="years" type="number"
                             min="{{\App\Models\Skill::MIN_YEARS_OF_EXPERIENCE}}"
                             max="{{\App\Models\Skill::MAX_YEARS_OF_EXPERIENCE}}"
                         class="mt-1 block w-full"
                         placeholder="Years of experience"/>
                        <x-jet-input-error for="editing.years" class="mt-2" />

            </x-slot>

            <x-slot name="footer">
                <x-jet-secondary-button wire:click="$set('showEditModal', false)" class="mr-2">Cancel</x-jet-secondary-button>
                <x-jet-button type="submit">Save</x-jet-button>
            </x-slot>
        </x-jet-dialog-modal>
    </form>

And this is my livewire component:
<?php

namespace App\Http\Livewire;

use App\Models\Skill;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class Skills extends Component
{
    public $name ='';
    public $showEditModal = false;
    public Skill $editing;

    public function rules()
    {
        return [
            'editing.name' => 'required|in:'.collect(Skill::LANGUAGES)->keys()->implode(','),
            'editing.years' => 'required|numeric|between:' . Skill::MIN_YEARS_OF_EXPERIENCE . ',' . Skill::MAX_YEARS_OF_EXPERIENCE,
        ];
    }

    public function render()
    {
        return view('livewire.skills', [
            'skills' => Skill::where('user_id', auth()->id())->get(),
        ]);
    }

    public function mount(){
        $this->editing = $this->makeBlankSkill();
    }

    public function makeBlankSkill(){
        return Skill::make([
         'name' => 'javascript',
         'user_id' => auth()->user()->id,
        ]);
    }

    public function create(){
        if ($this->editing->getKey()) $this->editing = $this->makeBlankSkill();
        $this->showEditModal = true;
    }

    public function edit(Skill $skill) {
        if ($this->editing->isNot($skill)) $this->editing = $skill;
        $this->showEditModal = true;
    }

    public function save()
    {
        $this->validate();
        $this->editing->save();
        $this->showEditModal = false;
    }
}

I keep getting SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value and i dont know why.
This is my modal:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Skill extends Model
{
    use HasFactory;
    const DEFAULT_OPTION = 'Please select a skill';

    const LANGUAGES = [
        'javascript' => 'JavaScript',
        'php' => 'PHP',
        'python' => 'Python',
        'java' => 'Java',
        'c#' => 'C#',
        'c++' => 'C++',
        'ruby' => 'Ruby',
        'swift' => 'Swift',
        'typescript' => 'TypeScript',
        'rust' => 'Rust',
        'go' => 'Go',
        'kotlin' => 'Kotlin',
        'scala' => 'Scala',
        'dart' => 'Dart',
        'r' => 'R',
        'perl' => 'Perl',
        'elixir' => 'Elixir',
        'clojure' => 'Clojure',
        'haskell' => 'Haskell',
        'erlang' => 'Erlang',
        'lisp' => 'Lisp',
        'sql' => 'SQL',
        'bash' => 'Bash',
        'laravel' => 'Laravel',
        'symfony' => 'Symfony',
        'codeigniter' => 'CodeIgniter',
        'yii' => 'Yii',
        'zend' => 'Zend',
        'cakephp' => 'CakePHP',
        'fuelphp' => 'FuelPHP',
        'slim' => 'Slim',
        'lumen' => 'Lumen',
        'phalcon' => 'Phalcon',
        'silex' => 'Silex',
        'express' => 'Express',
        'koa' => 'Koa',
        'hapi' => 'Hapi',
        'meteor' => 'Meteor',
        'angular' => 'Angular',
        'ember' => 'Ember',
        'react' => 'React',
        'vue' => 'Vue',
        'backbone' => 'Backbone',
        'd3' => 'D3',
        'threejs' => 'Three.js',
        ];

    const MIN_YEARS_OF_EXPERIENCE = 1;
    const MAX_YEARS_OF_EXPERIENCE = 50;

    protected $fillable = [
        'name', 'user_id', 'years'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Any help is greatly appriceated
I've done all there is to do.At least i hope. I've added the
$illable

array ive set the
'user_id' => auth()->user()->id,

Not sure what else im missing

A: If user_id is null when creating a new Skill, this means there is no authenticated user. You can simply check by doing dd(auth()->id()). If you're logged in, this will return the primary key for your authentication model. If this is empty, you're simply not authenticated, and so you must first log in.
In the case your user_id is actually set, but it isn't arriving in your database upon saving, you'll have to check if the property user_id is correctly set on the Skill model's protected $fillable property.
If you dd($this->editing) right after mount, you can check the attributes of the model, and if the user_id is set, you know the error happens when saving to the database.
As it turns out, Livewire won't hydrate newly set properties on models. This is because Livewire "rehydrates" the models by simply re-fetching them from the database. This can be solved defining a rules property as shown here, directly relating to the model properties. This would ensure Livewire keeps the state of the updated properties.

A:     public function save()
{
    $this->validate();
    $user = auth()->user();
    $this->editing->user_id = $user->id;
    $this->editing->save();
    $this->showEditModal = false;
}

This was the answer for me


text:
Q: Как убрать из основной логики input() для команд p, s и поместить input() внутрь функций people() и shelf()?     {"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"},
    {"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"},
    {"type": "insurance", "number": "10006", "name": "Аристарх Павлов"}
]
directories = {
    '1': ['2207 876234', '11-2'],
    '2': ['10006'],
    '3': []
}

def people(doc):
    result = ' - Документ не существует.'
    for document in documents:
        if document["number"] == doc:
            result = f' - Владелец: {document["name"]}'
    print(result)

def shelf(doc):
    result = ' - Документ не существует.'
    for shelf_number, doc_number_ in directories.items():
        if doc in doc_number_:
            return f' - Полка №: {shelf_number}'
    print(result)

while True:
    choice = input('\n- Какую операцию вы хотите выполнить?\n\n'
                   '- p: команда, по номеру документа выведет имя человека, которому он принадлежит\n'
                   '- s: команда, по номеру документа выведет номер полки, на которой он находится\n'
                   '- q: команда, для завершение работы\n').lower()
    if choice == 'p':
        people(input(' - Введите номер документа: '))
    elif choice == 's':
        shelf(str(input(' - Введите номер документа: ')))
    elif choice == 'q':
        print(' - До скорой встречи!')
        break
    else:
        print(' - Неизвестная команда, попробуйте выбрать из списка:')

A: documents = [
    {"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"},
    {"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"},
    {"type": "insurance", "number": "10006", "name": "Аристарх Павлов"}
]
directories = {
    '1': ['2207 876234', '11-2'],
    '2': ['10006'],
    '3': []
}

def people():
    doc = input(' - Введите номер документа: ')
    result = ' - Документ не существует.'
    for document in documents:
        if document["number"] == doc:
            result = f' - Владелец: {document["name"]}'
            break
    print(result)

def shelf():
    doc = input(' - Введите номер документа: ')
    result = ' - Документ не существует.'
    for shelf_number, doc_number_ in directories.items():
        if doc in doc_number_:
            result = f' - Полка №: {shelf_number}'
            break
    print(result)

while True:
    choice = input('\n- Какую операцию вы хотите выполнить?\n\n'
                   '- p: команда, по номеру документа выведет имя человека, которому он принадлежит\n'
                   '- s: команда, по номеру документа выведет номер полки, на которой он находится\n'
                   '- q: команда, для завершение работы\n>').lower()
    if choice == 'p':
        people()
    elif choice == 's':
        shelf()
    elif choice == 'q':
        print(' - До скорой встречи!')
        break
    else:
        print(' - Неизвестная команда, попробуйте выбрать из списка:')


text:
Q: Batch nested If statement error with not defined variables I have a problem with a simple batch script. See:
SET TEST=
IF NOT DEFINED TEST (
    SET "TEST=1"
) ELSE (
    IF %TEST% LSS 1 ( SET "TEST=1")
)

Here the if in the else branch failes, because the variable TEST ist not defined. But the else branch even shouldn't been executed if the variable TEST isn't defined!?
What is here the problem?
(I knew, that this code would work, if I leave the else and write it under the if statement, but then this code get's executed every time.)
How to solve this problem?
THX.

A: Magoo's answer will prevent the error but it will lead to alphabetical comparison instead of numerical.I think it will be better to use delayed expansion and one additional if defined statement :
setlocal enableDelayedExpansion
SET "TEST="
IF NOT DEFINED TEST (
    SET "TEST=1"
) ELSE (
    if defined test IF !TEST! LSS 1 ( SET "TEST=1")
)

A: The entire statement is parsed that is, examined for syntactic correctness before it is executed.
The parser finds
) ELSE (
    IF LSS 1 ( SET "TEST=1")
)

and objects because 1 is not a comparison operator.
) ELSE (
    IF "%TEST%" LSS "1" ( SET "TEST=1")
)

should fix the problem.


text:
Q: Validate contents of std::initializer_list at compile time I am attempting to determine at compile time if all the values in a std::initializer_list are unique. I was able to locate a solution to valiate the size of a list but have been unable to apply it to the contents. I have tried with both free functions and in constructors but both approaches have resulted in the following errors with GCC 4.7.2.

error: non-constant condition for static assertion
  error: 'begin' is not a constant expression

I realize the members of std::initializer_list are not declared constexpr but I'm hoping there is a solution like the size validation. Is it possible to validate the contents at compile time using something like the following?
#include <initializer_list>

template<typename InputIterator>
constexpr bool Validate(InputIterator begin, InputIterator end)
{
    static_assert(*begin == *end, "begin and end are the same");
    //  The actual implemetnation is a single line recursive check.
    return true;
}

template<typename InputType>
constexpr bool Validate(const std::initializer_list<InputType>& input)
{
    // "-1" removed to simplify and eliminate potential cause of error
    return Validate(input.begin(), input.end() /* - 1 */);
}

int main()
{
    Validate({1, 2, 1});
}

A: After some digging it looks like using std::initializer_list is not possible in GCC 4.7 due to the lack of constexpr in it's declaration. It should work with GCC 4.8 as <initializer_list> has been updated to include constexpr. Unfortunately using GCC 4.8 is not an option at the moment.
It is possible to access elements of an array if the decayed pointer is passed by reference though. This allows the validation to occur as desired but still isn't quite the solution I am hoping for. The following code is a workable solution for arrays. It still requires that the size of the array be supplied to the validation function but that it easy enough to correct.
#include <initializer_list>

template<typename T>
constexpr bool Compare(T& data, int size, int needleIndex, int haystackIndex)
{
    return
        needleIndex == haystackIndex ?
            Compare(data, size, needleIndex + 1, haystackIndex)
        :   needleIndex == size ?
                false
            :   data[needleIndex] == data[haystackIndex] ?
                    true
                :   Compare(data, size, needleIndex + 1, haystackIndex);
}

template<typename T>
constexpr bool Compare(T& data, int size, int index)
{
    return
        index == size ?
            false
        :   Compare(data, size, index + 1) ?
                true
            :   Compare(data, size, 0, index);
}

template<typename T, int ArraySize>
constexpr bool Validate(T(&input)[ArraySize], int size)
{
    return !Compare(input, size, 0);
}

int main()
{
    constexpr int initData0[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    constexpr int initData1[] = {1, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    constexpr int initData2[] = {2, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    constexpr int initData3[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 8};
    constexpr int initData4[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 7};
    constexpr int initData5[] = {0, 1, 0, 3, 4, 5, 6, 7, 8, 9};
    constexpr int initData6[] = {0, 1, 2, 3, 4, 5, 6, 9, 8, 9};

    static_assert(Validate(initData0, 10), "set 0 failed"); // <-- PASS
    static_assert(Validate(initData1, 10), "set 1 failed"); // <-- (and below) FAIL
    static_assert(Validate(initData2, 10), "set 2 failed");
    static_assert(Validate(initData3, 10), "set 3 failed");
    static_assert(Validate(initData4, 10), "set 4 failed");
    static_assert(Validate(initData5, 10), "set 5 failed");
    static_assert(Validate(initData6, 10), "set 6 failed");
}

.
Build log:

C:\Source\SwitchCaseString\main.cpp: In function 'int main()':
  C:\Source\SwitchCaseString\main.cpp:198:2: error: static assertion failed: set 1 failed
  C:\Source\SwitchCaseString\main.cpp:199:2: error: static assertion failed: set 2 failed
  C:\Source\SwitchCaseString\main.cpp:200:2: error: static assertion failed: set 3 failed
  C:\Source\SwitchCaseString\main.cpp:201:2: error: static assertion failed: set 4 failed
  C:\Source\SwitchCaseString\main.cpp:202:2: error: static assertion failed: set 5 failed
  C:\Source\SwitchCaseString\main.cpp:203:2: error: static assertion failed: set 6 failed