text:
Q: Como salvar no banco de dados uma opção do ? DJANGO Olá, sou iniciante em Django e estou fazendo aplicações simples apenas para treinar o uso de Banco de Dados com o uso de formulários. Dentro do meu formulário, eu tenho uma parte em que a pessoa vai selecionar uma determinada categoria, porém, a categoria selecionada não está sendo salva no meu banco de dados.
Por exemplo:
Eu tenho dentro do arquivo models.py, um objeto chamado de Ideia, feito da seguinte maneira:
class Ideia(models.Model):
    CATEGORIAS = (
        ('CAT1', 'Categoria 1'),
        ('CAT2', 'Categoria 2'),
        ('CAT3', 'Categoria 3'),
        ('CAT4', 'Categoria 4'),
        ('OUTROS', 'Outros'),
    )

    pessoa = models.ForeignKey(
        Pessoa, on_delete=None
    )

    titulo = models.CharField(
        max_length=255,
        verbose_name='Nome da ideia'
    )

    descricao = models.TextField(
        verbose_name='Descreva sua ideia'
    )

    categoria = models.CharField(
        verbose_name='Categorias',
        choices=CATEGORIAS,
        max_length=255
    )

O meu arquivo views.py está com a seguinte estrutura:
def cadastrar_ideia(request):
    if request.method == 'POST':
        email_pessoa = request.POST.get('email')
        pessoa = Pessoa.objects.filter(email=email_pessoa).first()
        if pessoa is not None:
            ideia = Ideia()
            ideia.pessoa = pessoa
            ideia.titulo = request.POST.get('titulo')
            ideia.descricao = request.POST.get('descricao')
            ideia.categoria = request.POST.get('categoria')
            ideia.save()
            print('Deu certo')

            return redirect('/sobre')

    return render(request, 'ideia.html', {})

E, por final, a minha estrutura no HTML se encontra da seguinte maneira:
<form action="/ideias" method="post">
    {% csrf_token %}
    <input type="hidden" name="email" value="{{pessoa.email}}">
    <input type="text" name="titulo" placeholder="Nome da ideia">
    <label for="descricao">Descreva sua ideia</label>
    <textarea name="descricao" cols="30" rows="10">
    </textarea>
    <select name="categoria">
        <option value="CAT1">Categoria 1</option>
        <option value="CAT2">Categoria 2</option>
        <option value="CAT3">Categoria 3</option>
        <option value="CAT4">Categoria 4</option>
        <option value="OUTROS">Outros</option>
    </select>
    <input type="submit" value="Cadastrar Ideia">
</form>

Todos os outros atributos está sendo salvos no meu banco de dados, porém, na parte de categorias de uma ideia cadastrada no sistema, aparece apenas "----", como se nada estivesse sido selecionado.
Estou esquecendo de alguma coisa importante para que a informação da categoria seja salva?

A: Utilize uma CreateView para resolver isto, tente o seguinte:
from django.views import generic
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy

class IdeiaCreate(SuccessMessageMixin, generic.CreateView):

    model = Ideia
    fields = '__all__'
    template_name = 'ideia.html'
    success_url = reverse_lazy('name_de_sua_url')
    success_message = 'Deu certo!'

No seu template, mude o form para, deixe a
<form action="" method="post">
    {% csrf_token %}
    {% for field in form %}
        {{ field.label_tag }}
        {{ field }}
    {% endfor %}
    <input type="submit" value="Cadastrar Ideia">
</form>

Para exibir a mensagem de sucesso no template, basta fazer o seguinte:
{% for m in messages %}
    {{ m }}
{% endfor %}


text:
Q: c# stringbuilder vs Aggreggate? Is StringBuilder really faster than Aggreggate?

    string c = tmpArr[0].Aggregate(string.Empty, (current, m) => current + (m.Name + " "));

    StringBuilder sb = new StringBuilder();

    foreach (Mobile m in tmpArr[0])
        sb.Append(m.Name + " ");

    sb.ToString();

which of those two is faster? aggregate certainly is cleaner, but is it fast or is it the same as doing

foreach(Mobile m in tmpArr[0])
      c += m.Name + " ";

what I really would like to do is something like string.Join(",",tmpArr[0]), but I don't want it to concat their ToString values, just their Names, how would I do that best?
my problem with not using string.Join is I would actually have to do something like this:

string separator = "";
          StringBuilder sb = new StringBuilder();
    foreach (Mobile m in tmpArr[0])
    {
        separator = ", ";
        sb.Append(separator + m.Name);
    }

A: Is a bad idea to multiple time add chunks to a string, because since string are immutable in .NET you obtain a lot of garbaged string in memory, and probably that dublication is more expensive in term of execution time too. Using StringBuilder, String.Concat(), or String.Join() are definitely the best way when you need to compose strings.

A: The cleanest way to do this is to use String.Join, because that's what it is there for:
string.Join(" ", tmpArr[0].Select(x => x.Name));

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Autocomplete and Special Characters in WordPress Hopefully im not missing an already existing answer to this question. Im working with a wordpress theme that uses jquery ui autocomplete to provide category selections in a front end form.  Code is below.  Problem is that if a category name has an &, it cant display the character and instead shows & in the autocomplete box. Can i make it show the character properly?
`
    jQuery(function(){

        /* Auto Complete */
        var availableTags = [
            <?php
                $terms_array = array();
                $terms = get_terms( 'majors', 'hide_empty=0' );

                if ($terms) foreach ($terms as $term) {
                    $terms_array[] = '"'.$term->name.'"';
                }
                echo implode(',', $terms_array);
            ?>
        ];
        function split( val ) {
            return val.split( /,\s*/ );
        }
        function extractLast( term ) {
            return split( term ).pop();
        }

        jQuery("#majors_wrap input").live( "keydown", function( event ) {
            if ( (event.keyCode === jQuery.ui.keyCode.TAB || event.keyCode === jQuery.ui.keyCode.COMMA) &&
                    jQuery( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        }).autocomplete({
            minLength: 0,
            source: function( request, response ) {
                // delegate back to autocomplete, but extract the last term
                response( jQuery.ui.autocomplete.filter(
                    availableTags, extractLast( request.term ) ) );
            },
            focus: function() {
                jQuery('input.ui-autocomplete-input').val('');
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {

                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                //this.value = terms.join( ", " );
                this.value = terms.join( "" );

                jQuery(this).blur();
                jQuery(this).focus();

                return false;
            }
        });

    });
</script>`

A: Just replace it in the returned data: terms.push( ui.item.value.replace("&","&" );


text:
Q: How to apply Breadcrum using AngularJS? I want to add breadcrums in my application , How i can achieve this task using AngularJS. So far i have implemented router and header file and not sure after this how to use breadcrums in AngularJS.
So far tried below code...
INDEX

HTML

Risk Assessment Platform

Dashboard

Process Risk & Control
                        Inventory

Create
                                New Process

Create New Unaligned
                                Risk

Create
                                New Unaligned Control

View/
                                Search Inventory

View End-to-End

Reports

Data Upload

Upload Inventory

Risk Assessment

RCSA

CRA

Reports

Administration

{{user.customUserDetails.workFullName}}

Logout

ROUTER.JS
angular.module('riskAssessmentApp')
       .config(function($stateProvider, $httpProvider, $urlRouterProvider) {

        /*
         * This has to be here because the browsers will not catch the home
         * state without it
         */
        $urlRouterProvider.otherwise( function($injector, $location) {
            var $state = $injector.get("$state");
            $state.go("home");
        });

        $httpProvider.defaults.withCredentials = true;
        $httpProvider.defaults.headers.post = {'Content-Type': 'application/json'};
        $httpProvider.interceptors.push('HttpResponseInterceptor');

        $stateProvider
         .state('home', {
                url : '/',
                templateUrl: 'views/riskAssesmentHomePage.html',
                controller:  'riskHomePageController',
                data: {
                    authenticate: true
                }
             }).state('smlogin', {
                url: '/smlogin',
                controller: 'SMLoginController'
            })
             .state('login', {
               url : '/login',
               templateUrl : 'views/login.html',
               controller : 'LoginController'
             })
             .state('error', {
                 url:'/error',
                 templateUrl: 'views/error.html'
             })
             .state('settings', {
                 url:'/settings',
                 templateUrl: 'views/settings.html',
                 controller: 'SettingsController'
             })
             .state('sessions', {
                 url:'/sessions',
                 templateUrl: 'views/sessions.html',
                 controller: 'SessionsController',
                 resolve:{
                     resolvedSessions:['Sessions', function (Sessions) {
                         return Sessions.get();
                     }]
                 }
             })
             .state('metrics', {
                 url:'/metrics',
                 templateUrl: 'views/metrics.html',
                 controller: 'MetricsController'
             })
             .state('logs', {
                 url:'/logs',
                 templateUrl: 'views/logs.html',
                 controller: 'LogsController',
                 resolve:{
                     resolvedLogs:['LogsService', function (LogsService) {
                         return LogsService.findAll();
                     }]
                 }
             })
             .state('createProcess', {
                 url:'/process/create',
                 templateUrl : 'views/createEditProcessContent.html',
                 controller : 'ProcessController',
                data: {
                    authenticate: true
                }
             })
             .state('editProcess', {
                 url:'/process/:process_Id/:refresh',
                 templateUrl : 'views/createEditProcessContent.html',
                 controller : 'ProcessController',
                data: {
                    authenticate: true
                }
             })
             .state('createRisk', {
                 url:'/risk/create',
                 templateUrl: 'views/createNewRisk.html',
                 controller: 'RiskController',
                data: {
                    authenticate: true
                }
             })

A: You can use https://github.com/ncuillery/angular-breadcrumb
Define a ncyBreadcrumb.label property to each states
And then use the directive


text:
Q: Elixir - Changing Behavior This is mostly a Functional Programming question rather than an Elixir one, but since I'm learning Elixir it would be nice if someone can answer it using that language. Even so, if someone wants to give a more general answer it'll be appreciated.
I'm an OO programmer myself and I can't wrap my head around how to change the behavior of a component based on a configuration file (for example).
Example:
I have an application that loads/saves users from a database. In a production environment, I want my users to be saved and retrieved from a MongoDB database, while in development and testing I want to use an in-memory map. If I was programming given system in an OO language (Lets say Java), I would simply make an Interface named "UserRepository" with 2 implementations: "MemoryUserRepository" and "MongoDBUserRepository". I would then instantiate the corresponding Repository based on a configuration file (or hardcoding it, it doesn't matter) at startup and right after it, all the objects that interact with the Repository will never know its implementation (they will use a repository, but will never care if it's in memory or in mongo).
That gives me the ability to create as many implementations as I want and the only thing I need to do to change the behavior of the system is instantiate the implementation that I want to use.
I want the same behavior but in Elixir (let's use the same example). Since it's not an Object Oriented language I can't use the above approach. Obviously I want it to be extensible (I could easily pass a String with the type of repository I want to use in each call and use pattern matching to determine what behavior to use, but that doesn't scale well because every time I'll want to add an implementation I will have to look in every piece of code I'm pattern matching the type and add the new implementation). What would be the best approach to achieve this?
Thanks in advance!

A: Suppose you have these two (or more) repository implementations, which implement the same interface:
defmodule MyApp.Repository.Memory do
  def get(key) do
    # ...
  end

  def put(key, value) do
    # ...
  end
end

defmodule MyApp.Repository.Disk do
  def get(key) do
    # ...
  end

  def put(key, value) do
    # ...
  end
end

Then you can write a general repository module that will just forward the function calls to one of the repository backends, based on a configuration value in your config/config.exs file:
defmodule MyApp.Repository do
  @backend Application.get_env(:my_app, :repository_backend)

  defdelegate [get(key), put(key, value)], to: @backend
end

The configuration can be made so that it is environment specific (just look at the default config.exs in a mix project freshly created with mix new my_app):
# config/config.exs
import_config "#{Mix.env}.exs"

# config/dev.exs
config :my_app, repository_backend: MyApp.Repository.Memory

# config/prod.exs
config :my_app, repository_backend: MyApp.Repository.Disk

Throughout your entire code, you can then just use the MyApp.Repository module without explicitly referencing one of the specific implementations:
MyApp.Repository.put(:foo, "Hello world!")
value = MyApp.Repository.get(:foo)


text:
Q: Using shouldBeDisabled to enable / disable controls Is using shouldBeDisplay the way to enable / disable a control on the html or it is easier to go with jscript?  I have the follow code (spacebar i believe) but it does not trigger anything.
template:
<template name="prodlist">
<select id="category-select">
        <option {{ shouldBeDisabled }} selected="selected">Please Select</option>
        {{#each prodlist}}
            <option value="{{this}}">{{this}}</option>
        {{/each}}
    </select>
</template>

helper:
Template.registerHelper("shouldBeDisabled", function(prodlist) {
    return "disabled"
});

A: Found the error - the disable should be placed at the select not option:
<template name="prodlist">
<select id="category-select" disabled= {{ shouldBeDisabled }}>
        <option selected="selected">Please Select</option>
        {{#each prodlist}}
            <option value="{{this}}">{{this}}</option>
        {{/each}}
    </select>
</template>


text:
Q: Error launching Angular in .Net Core as Windows Service I am trying to launch Angular in .Net Project as self-hosted windows service. The error I am getting while accessing on chrome is:

HTTP Error 502.5 - Process Failure
Common causes of this issue: The application process failed to start
  The application process started but then stopped The application
  process started but failed to listen on the configured port

Program.cs
public class Program
{
public static void Main(string[] args)
{
  try
  {
    var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
    var pathToContentRoot = Path.GetDirectoryName(pathToExe);

    IWebHost host;

    if (Debugger.IsAttached || args.Contains("console"))
    {
      Debugger.Launch();
      host = WebHost.CreateDefaultBuilder()
              .UseContentRoot(Directory.GetCurrentDirectory())
              .UseStartup<Startup>()
              .UseUrls("http://localhost:60967/")
              .Build();
      host.Run();
    }
    else
    {
      host = WebHost.CreateDefaultBuilder(args)
              .UseContentRoot(pathToContentRoot)
              .UseStartup<Startup>()
              .Build();
      host.RunAsService();
    }
  }
  catch (Exception ex)
  {
    throw;
  }
}

On checking the event viewer, the error shown is:

Application 'MACHINE/WEBROOT/APPHOST/API.WEBAPI' with physical root 'C:\Projects\MIRCOM\Api\Dev\Api\' failed to start process with commandline 'c:\program files (x86)\microsoft visual studio\2017\community\common7\ide\extensions\microsoft\web tools\projectsystem\VSIISExeLauncher.exe -argFile "C:\Users\gaurav.saxena\AppData\Local\Temp\tmpA00F.tmp"', ErrorCode = '0x80004005' : 0.

The strange thing is it keeps referencing my Api.
The API as self-hosted works great, but the UI doesn't.

A: There is a difference in the working directory when running an application as a windows service. The working directory, in that case, is %WinDir%\System32.
In this case, you are calling
UseContentRoot(Directory.GetCurrentDirectory())

which will return %WinDir%\System32 to use as the Content Root. Of course, your files won't be found there, resulting in the error above.
Try using
System.Reflection.Assembly.GetEntryAssembly().Location

or
AppDomain.CurrentDomain.BaseDirectory

to resolve the correct directory and set the correct contentRoot.


text:
Q: SQL's to_date formatting not being displayed I have the below SQL query
select to_date(start_date, 'dd-Mon-yy') AS start_date FROM table

I also have the below ResultSet objects (rs)
rs.getDate("start_date")

When I run the query in SQL developer directly against the database (Oracle) the format is returned as expected (08-AUG-12), but when I run the query in my Java app using JDBC it prints out as 2012-08-08.
Am I getting the format the correct way? Should I just select on the column (date datatype) and then format via JodaTime's DateTimeFormatter? I'm not sure what I'm doing wrong here.
The same thing happens when I convert from java.sql.Date to java.util.Date...

A: you are simply converting to a date here... you probably want to be converting to a string for output.
TO_CHAR( mydate, 'mm-dd-yyyy' )

A: Database format is not taken in consideration when you are dealing with a Date object in Java. If you want to match exactly the format that you have on your function, you can use TO_CHAR, and fetch the column as a String.
Alternatively, you keep fetching the column as Date, and then format it accordingly with DateTimeFormatter, for example.


text:
Q: Induced electric field in a dielectric material moving in a magnetic field I came across a problem which is as follows:

A bar of thickness $d$ is made to move with a velocity v perpendicular to a uniform magnetic field of induction $B$. Top and bottom faces of the bar are parallel to the lines of magnetic field.

(a) Find surface charge densities on the upper and the bottom faces of the bar, assuming material of the bar to be a perfect conductor.
(b) Find the surface charge densities on the upper and the bottom faces of the bar, assuming material of the bar to be a dielectric of dielectric constant $K$.

Part (a) is pretty simple. I just equated the force on the moving electron due to magnetic field and the electric field produced due to the charges induced on the plates as follows
$$qvB=qE$$
where $E$ is the electric field due to the induced charges
as $E=\sigma/\epsilon$. I get the charge density on plates as $\epsilon Bv$.
My Doubts:
It is part (b) that I cannot understand. My doubts regarding it are :
Doubt 1) The dielectric constant gives the relation between the external electric field and the field induced due to the charges of the dielectric. But in this case there is no external field, so how to actually use the dielectric constant to find electric field in a dielectric .
Doubt 2) Also secondly I don't understand how the force on an electron will be affected due to the material being a dielectric.I thought that the same amount of charge as in the case of conductor should be produced to equalise the force of magnetic field but that surely isn't the case. So what actually is happening?

A: One way to look at it is to do a Lorentz boost with $-\vec v$, then:
$$\vec B'=\gamma \vec B$$
$$ \vec E'=\gamma(-\vec v \times \vec B)$$
so $E'=\gamma v B$, which differs from your (non-relativistic) results by:
$$\gamma=\frac 1{\sqrt{1-\frac{v^2}{c^2}}}$$
In this frame, the block is at rest in a magnetic field and a perpendicular electric field. For the conductor, that will give a surface charge density satisfying:
$$E'=\frac{\sigma'}{\epsilon_0}$$
or
$$\sigma'=\epsilon_0E'=\epsilon_0\gamma v B$$
Now boost that back to the frame of the picture, where the surface charge is invariant, but the surface area contracts by the Lorentz factor:
$$\sigma=\gamma\sigma'=\epsilon_0\gamma^2 v B$$
The same reasoning can be applied to (b).


text:
Q: Why does a logger Java need check isDebugEnabled()? Why java logger need check
if (log.isDebugEnabled()) {
   log.debug("Debug message");
}

instead call directly log.debug("Debug message");?

A: It doesn't. Typically, you would call log.isDebugEnabled() in cases when you need some extra code to log what you want:
if (log.isDebugEnabled()) {
    for (...) {
        // Some heavy logic that is only needed when logging things
        log.debug("Debug message");
    }
}

This way you never trigger the extra logic when it's not needed.

A: In addition to @1615903's answer:
You can configure different levels of logging. For some environment you might want to disable DEBUG level and logging engine (SLF4J) wouldn't put those messages into log but the code (log.debug("...")) would still be executed, which is completely useless with disabled DEBUG level. Using isXXXEnabled() you can avoid excess work.


text:
Q: compare NSString using isEqualToString Please, why doesn't isEqualToString work?
- (void)viewDidLoad {
    [super viewDidLoad];

    extern NSString* globalpassword;

    if ([passwo.text isEqualToString: globalpassword]) {

        res = [[XMLTestViewController alloc] initWithNibName:@"XMLTestViewController" bundle:nil];
        res.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self.view addSubview:res.view];
    } else {

        NSLog(@"faux");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"chikos"
                                                        message:@"Wrong Password" delegate:self cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:@"OK", nil];

        [alert show];
        [alert release];
    }
}

the result is
2011-08-11 17:56:36.543 XMLTest[6389:207] pol
2011-08-11 17:56:36.544 XMLTest[6389:207] pol
2011-08-11 17:56:36.544 XMLTest[6389:207] faux

A: Take a look at your NSLog line; it should look like this :
NSLog(@"hi all freind");

(notice the @ sign!)

EDIT This must mean that you're ignoring your compiler warnings! They're there for a reason; in this case, telling you that you're passing in the wrong parameter to NSLog.
I bet you're also getting warnings on the NSLog(cc) and NSLog(bb) lines as well?

A: The strings differ. Try logging bb and cc like this:
NSLog(@"bb: '%@', cc: '%@'", bb, cc);

With the single quotes you can see whether there is unexpected whitespace in either bb or cc.


text:
Q: Movable divisor with base locus on a hyperkahler variety I'm looking for an example of the following:

$X$ is a hyperkahler fourfold (deformation equivalent to $K3^{[2]}$);
  $D$ is a movable divisor on $X$ with $D^4=0$; and the base locus of
  $D$ is a smooth rational surface $\not \simeq \mathbb P^2$.

Note that it is relatively easy to construct such divisors with base locus equal to $\mathbb P^2$: $X=S^{[2]}$ for a degree 2 K3 surface works (Here $X$ contains a $\mathbb P^2$ which can be flopped, and the resulting birational model has a lagrangian fibration). But finding such examples with e.g. blow-ups of $\mathbb P^2$ or $\mathbb P^1\times \mathbb P^1$ seems a bit more difficult.
Any ideas on how to construct such examples would be greatly appreciated!

A: You can make more examples using the natural $K$-equivalence between the Hilbert scheme of a $K3$ Deligne-Mumford stack to the corresponding Hilbert scheme of the crepant resolution of its coarse moduli space.  The example in your post arises this way when the stack has a single stacky point whose inertia group is cyclic of order $2$, so that the crepant resolution has a $(-2)$-curve whose $\text{Sym}^2$ is the flopped $\mathbb{P}^2$ (I assume that your example arises by flopping $\text{Sym}^2$ of one of the preimages of a bitangent line to the plane sextic, which preimage is the $(-2)$-curve in my interpretation).  The following example is the next case, where the stack has a single stacky point whose inertia group is cyclic of order $3$, so that the crepant resolution is a chain of two $(-2)$-curves.
Let $S$ be a smooth quartic K3 surface in $\mathbb{P}^3$ that is a general member of the $5$-dimensional projective linear system of quartics that contain a specified line $L$ as well as a specified disjoint curve $C=M\cup N$ that is a union of two lines intersection transversally at one point $p$.  The plane cubics residual to $L$ form an elliptic fibration on $S$, $$\pi:S\to \mathbb{P}^1.$$  This induces an Abelian fibration on $S^{[2]}$.  Let $D'$ denote the pullback to $S^{[2]}$ of the hyperplane class on $\text{Sym}^2(\mathbb{P}^1) = \mathbb{P}^2$.
The curve $M\cup N$ can be contracted to form a normal projective surface $S'$ with a single $A_2$-singularity $q$.  Explicitly, the $2$-plane spanned by $M$ and $N$ intersects $S$ in the union of $M$, of $N$, and of a plane conic $C$.  The linear system of sections of $\mathcal{O}_{\mathbb{P}^3}(2)$ that contain $C$ induces a closed immersion of $S'$ as a sextic surface in $\mathbb{P}^4$ (probably there is a direct construction of this sextic suface).
There is a smooth, proper Deligne-Mumford stack $\mathcal{S}$ whose coarse moduli space is a $1$-morphism, $$\nu:\mathcal{S}\to S',$$ that is an isomorphism over the open subset $U:=S'\setminus\{q\}$, and whose inertia group over $q$ is cyclic of order $3$.  The Hilbert scheme $X$ of length $2$ closed substacks of $\mathcal{S}$ has a unique connected component that contains $U^{[2]}$.  This is a projective hyperkähler $4$-fold that is K-equivalent, hence deformation equivalent (by Huybrechts), to $S^{[2]}$.
The surface in $X$ that is the fundamental locus of the K-equivalence with $S^{[2]}$ equals the punctual Hilbert scheme of $\mathcal{S}$ for the point $q$.  Because $K$-equivalences preserve classes in the Grothendieck ring of varieties, etc., we know that this fundamental locus has the same class as the fiber over $2[q]$ for the Hilbert-Chow morphism, $$FC:S^{[2]}\to \text{Sym}^2(S').$$  In particular, the fundamental locus has $3$ irreducible components, each of which is a rational surface.


text:
Q: get global value in Global.asax i have a problem about global.asax, in file global.asax i want to get variable session which i already set session in login.aspx and while i get variable session, its error : Object reference not set to an instance of an object
code for global.asax :
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
     string SID = Cookies.GetCookie().SessionID; // error at this point
     if (ShoppingCart.CheckIsSessionActive() == false)
     {
         Cookies.DeleteCookie();
         FormsAuthentication.SignOut();
                Response.Redirect("../expired.htm");
     }
}

code setting session in login.aspx.cs
  protected void btnLogin_Click(object sender, EventArgs e)
  {
      Cookies.DeleteAllCookies();

      var sess = Cryptography.SetSID();

      Cookies cookies = new Cookies();
      cookies.UserID = (int)row["Id"];
      cookies.UserName = txtLoginID.Text;
      cookies.SessionID = sess;

      Cookies.SetCookie(cookies);

      Response.Redirect("~/Admin/Lounge.aspx");
  }

but if i disabled code for global.asax and direct to file lounge.aspx, and in file Lounge.aspx.cs get value like in file global.asax its working
code for lounge.aspx.cs :
  protected void Page_Load(object sender, EventArgs e)
  {
        int UserID = Cookies.GetCookie().UserID;
        string SID = Cookies.GetCookie().SessionID;
  }

code for function GetCookie() :
  public static Cookies GetCookie()
    {
        Cookies cookies = Cache.Get("Cookie" + HttpContext.Current.User.Identity.Name) as Cookies;

        if (cookies == null)
        {
            cookies = GetCookieToCache();
            Cache.Insert("Cookie" + HttpContext.Current.User.Identity.Name, cookies, 15);
        }

        return cookies;
    }

    private static Cookies GetCookieToCache()
    {
        Cookies cookies = new Cookies();
        HttpCookie HttpCookie = HttpContext.Current.Request.Cookies[COOKIESNAME];

        if (HttpCookie != null)
        {
            Hashtable hTable = new Hashtable();
            HMB.Components.Utility.DecodeParameters(HttpCookie.Value, out hTable);

            cookies.UserID = Convert.ToInt32(Cryptography.TDESDecrypt(hTable["1"].ToString()));
            cookies.UserName = Cryptography.TDESDecrypt(hTable["2"].ToString());
            cookies.SessionID = Cryptography.TDESDecrypt(hTable["3"].ToString());

        }

        return cookies;
    }

thx


text:
Q: Why the histogram doesn't work - shiny library in R Dataset: https://www.kaggle.com/mirichoi0218/insurance
Hi, I have a problem with shiny library. Wanted to create app that will show the Charges depending on the age, region and children. Unfortunately, the histogram doesn't work.
ui <- fluidPage(
  titlePanel("Insurance charges"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("ageInput", "Age", 18, 64, 41),
      radioButtons("childrenInput", "Liczba dzieci",
                   choices = c("0", "1", "2", "3",'4','5'),
                   selected = "0"),
      selectInput("regionInput", "Region",
                  choices = c("NE", "NW", "SE","SW"))
    ),
    mainPanel(
      plotOutput("coolplot"),
      br(), br(),
      tableOutput("results")
    )
  )
)

server <- function(input, output) {
  output$coolplot <- renderPlot({
    filtered <-
      insurance %>%
      filter(age >= input$ageInput[1],
             age <= input$ageInput[2],
             children == input$childrenInput,
             region == input$regionInput
      )
    ggplot(filtered, aes(insurance$charges)) +
      geom_histogram()
  })
}

shinyApp(ui = ui, server = server)

A: The major issue with your code is that

*

*you map insurance$charges on x in ggplot(). That's why you always get a histogram for the total dataset. Simply use aes(charges) to use the column from your filtered dataset.

*Not sure about that. Maybe your recoded your data, but the regions in the Kaggle dataset have labels "northeast", "northwest", .... To account for that you could use a named vector for the choices in the selectInput

*Finally, you have to use a vector of length 2 for the value of the sliderInput to get a range slider.
And as an example on how to provide a minimal reproducible example I used a random fake dataset for the reprex.
library(shiny)
library(ggplot2)
library(dplyr)

ui <- fluidPage(
  titlePanel("Insurance charges"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("ageInput", "Age", min = 18, max = 64, value = c(18, 41)),
      radioButtons("childrenInput", "Liczba dzieci",
        choices = c("0", "1", "2", "3", "4", "5"),
        selected = "0"
      ),
      selectInput("regionInput", "Region",
        choices = c("NE" = "northeast", "NW" = "northwest", "SE" = "southeast", "SW" = "southwest")
      )
    ),
    mainPanel(
      plotOutput("coolplot"),
      br(), br(),
      tableOutput("results")
    )
  )
)

server <- function(input, output) {
  output$coolplot <- renderPlot({
    filtered <- insurance %>%
      filter(
        age >= input$ageInput[1],
        age <= input$ageInput[2],
        children == input$childrenInput,
        region == input$regionInput
      )

    ggplot(filtered, aes(charges)) +
      geom_histogram()
  })
}

shinyApp(ui = ui, server = server)

DATA
set.seed(123)

insurance <- data.frame(
  age = sample(18:64, 1000, replace = TRUE),
  children = sample(0:5, 1000, replace = TRUE),
  region = sample(c("southwest", "southeast", "northwest", "northeast"), 1000, replace = TRUE),
  charges = runif(1000, 3000, 40000)
)


text:
Q: pandas value assignment with conditions on index I am trying to calculate the Demarker Indicator in Python. Following describes how to calculate it:

*

*Choose a predetermined period "X" (Standard value is "14", although a value of "8" or "9" tends to be more sensitive);

*Calculate DeMax = High – Previous High if >0, otherwise DeMax = 0;

*Calculate DeMin = Previous Low – Low if >0, otherwise DeMin = 0;
DeM = MA of DeMax/(MA of DeMax + MA of DeMin).
Following is my attempt, df is a dataframe contains open high low close price with date as index:
df['DeMax'] = df['High'] - df['High'].shift(1)
df['DeMin'] = df['Low'].shift(1)-df['Low']
# Method 1: df['DeMax'][df['DeMax'] < 0] = 0.0
# Method 2: df[df['DeMax']< 0]['DeMax'] = 0.0

If I use Method 1, it is ok. But if I use Method2, I will get warning SettingWithCopyWarning, even I use copy method like this df['DeMax'] = df['High'].copy() - df['High'].copy().shift(1) won't solve the issue.
I have also checked that df['DeMax'][df['DeMax'] < 0] and df[test['DeMax']< 0]['DeMax'] are same pandas series, so why they behave differently if I try to assign values?
Also, if I do something like this
df['DeMax'] = df['High'] - df['High'].shift(1)
df['DeMin'] = df['Low'].shift(1)-df['Low']
a = df['DeMax'][df['DeMax'] < 0]
a = 0

Then a will be 0 instead of a pandas series, but I also expect df['DeMax'][df['DeMax'] < 0] will be 0, which does not happen, could anyone help? Thanks.

A: You are looking for .loc
df.loc[df['DeMax'] < 0,'DeMax']=0 # it will change all value less that 0 to 0


text:
Q: unable to create directory with name .dirname on nexus 5 I am unable to create directory with name .dirname in android kitket(nexus 5). so please suggest me what will I do to resolve this problem.when I call mkdirs() method it return false however I have set all permission on android manifest file.
following is my code:-
Map<String, File> externalLocations = ExternalStorage
                .getAllStorageLocations();
        File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
        File externalSdCard = externalLocations
                .get(ExternalStorage.EXTERNAL_SD_CARD);
        Environment.getExternalStorageState();
       // long count = System.currentTimeMillis();
        if (sdCard == null) {
            path = null;
        } else {
            path = sdCard.getAbsolutePath().toString() +"/.DriverMaticsV/" + "12345" + "/Picture/";
        }
        if (externalSdCard != null) {
            if (storageLocInt == 0) {
                path = sdCard.getAbsolutePath().toString() +"/.DriverMaticsV/" + "12345" + "/Picture/";
            } else {
                path = externalSdCard.getAbsolutePath().toString() + "/.DriverMaticsV/" + "12345" + "/Picture/";
            }
        }
        File file = new File(path);
        if (!file.exists()) {
            boolean result = file.mkdirs();
            Utilities.showDLog("CamperaUtil", ""+result);
        }

Android Manifest permission:-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application>.....</application>

A: i think "dirname" is command name in linux, you cannot created directories with command name in linux, i will suggest that connect android device to windows machine and create directory from Windows commad prompt.


text:
Q: Is "forall elimination twice with the same fresh variable" allowed? I am looking to prove that $\forall x \forall y \; P(x,y) \vdash \forall x \; P(x,x)$ and I wonder if this is allowed:
1. ∀x ∀y P(x,y)             Premise
2. | x0                     fresh variable
3. | ∀y P(x0, y)            ∀-elimination (1)
4. | P(x0, x0)              ∀-elimination (3)
5. ∀x P(x, x)               ∀-introduction (4)

It's the second forall elimination that I am worried about being incorrect. If this is not allowed, I would like to know why that is the case.

A: Using the proof checker associated with forallx, both linked below, the proof as you presented it is correct.
Here is the proof:

For the second forall elimination any name may be used to stand for the variable $y$ including the name used for the first forall elimination of variable $x$.

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/
P. D. Magnus, Tim Button with additions by J. Robert Loftis remixed and revised by Aaron Thomas-Bolduc, Richard Zach, forallx Calgary Remix: An Introduction to Formal Logic, Winter 2018. http://forallx.openlogicproject.org/


text:
Q: How to get every char from a text inside an element using a loop *HTML

a b

cd

*JS
var inlineDiv_num = $('#board_code > div ').size();
for( var x=0; x<inlineDiv_num; x++ ){
  var inlineDiv_num_textL = $('#board_code > div ').eq(x).text().length;
  for( var y=0; y<inlineDiv_num_textL; y++){
        //PROBLEM HERE
        alert(  $('#board_code > div ').eq(x).eq(y).text() );
  }//for y
}//for x

I am expecting that the first alert will be 'a', 2nd is ' ', 3rd is 'c', 4th is 'd'. I will use the char that i get for comparison to something like intellisense thingy.
NOTE
My 2 for loop structure should not be compromised, i need this structure for latter solving

A: Check this fiddle.
It will give all the characters one by one in the alert using the substr function.
EDIT: You can also use the alert(inlineDiv_num_text.charAt(y)); function instead of substr as mentioned by ElisianoPetrini.
var inlineDiv_num = $('#board_code > div ').size();
for (var x = 0; x < inlineDiv_num; x++) {
    var inlineDiv_num_textL = $('#board_code > div ').eq(x).text().length;
    var inlineDiv_num_text = $('#board_code > div ').eq(x).text();
    for (var y = 0; y < inlineDiv_num_textL; y++) {
        alert(inlineDiv_num_text.substr(y, 1)); //modified this
    } //for y
} //for x

A: Try
var $ct = $('#board_code');

$ct.children('div').each(function(idx, div){
    var text = $(this).text();

    for(var i = 0; i < text.length; i++){
        console.log(text.charAt(i))
    }
})

Demo: Fiddle

A: I'd structure it a bit differently.
$("#board_code > div").each( function(idx) {
    var s=$(this).text()
    for(i=0;i<s.length;i++){
        alert("'"+s.charAt(i)+"'")
    }
})

You can find it here: http://jsfiddle.net/bjzDf/


text:
Q: NGINX, GeoIP, Varnish : Too many Redirects I own two servers. One in Singapore (data.example.me) and other one in Europe (eu.data.example.me).
I want the website to serve the users from their closest server when they visit my website.
I configured Nginx on Signapore server using GeoIP Module.
I get "ERR_TOO_MANY_REDIRECTS" when visiting the website (data.example.me) from Europe. From other places it is working fine.
This is the configuration on Europe Server. It has Varnish installed.
# Marker to tell the VCL compiler that this VCL has been adapted to the
# new 4.0 format.
vcl 4.0;

# Default backend definition. Set this to point to your content server.
backend default {
.host = "139.51.1.1"; // Points to Nginx Server in Singapore
.port = "80";
}

On Nginx Server in Singapore configuration is as follows.
map $geoip_city_continent_code $closest_server {
default data.example.me;
EU      eu.data.example.me;
}

    server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html /_h5ai/public/index.php;

    server_name data.example.me eu.data.example.me;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
            autoindex on;

            # Site Settings (DDOS & Other Stuff)
            limit_req zone=one burst=10 nodelay;
            limit_conn addr 5;

            # Bandwidth Control
            limit_rate_after 102400K;
            limit_rate 5120K;
    }

    client_body_timeout 5s;
    client_header_timeout 5s;

    #GeoIP
     if ($closest_server != $host) {
rewrite ^ $scheme://$closest_server$request_uri break;
}

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
    #
    #       # With php-fpm (or other unix sockets):
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    #       # With php-cgi (or other tcp sockets):
    #       fastcgi_pass 127.0.0.1:9000;
    }

    location ~ /\.ht {
            deny all;
    }
    }

    server {
    listen 80;
    server_name 139.59.123.176;

    return 301 $scheme://data.vineethp.me$request_uri;
    }

A: The 302 Found redirect code is most likely returned by your application instead of nginx, since there is no reference to a temporary redirect in your nginx configuration.


text:
Q: How should I send the response in Servlet to Front end? I have written a Servlet something like this
public class ServletUtil extends HttpServlet {

private static final long serialVersionUID = 1571172240732862415L;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String acInfo = request.getQueryString();
    someDao dao = new someDao();
     ArrayList<String> resultAutoComplete=dao.someResults(acInfo);
    out.close();
}

}
I have an auto complete Object/wizard in front end and as the user types in it is making Ajax call to back end to grab the list of results. So I have written a Servlet and I am pulling the user input and getting my results from DAO layer.
My question here is how should I send this list(resultAutoComplete) to Front end in the Servlet?

A: I'd expect you to serialise this in some fashion such that the client understands it. e.g. perhaps using JSON or similar.
I note that your response content type is text/html. So why not simply write each element of your list to your Writer out, separated by (say) a <li> element (with the appropriate unordered/order list entities surrounding this)

A: By serializing it to a String and writing it to out...
Seriously though, I wouldn't code at the low level Servlet spec. For this kind of return-this-pojo call I would use Spring 3's RESTful service libraries, or something similar.

A: Try this,
for (String str : resultAutoComplete)
                {
            out.println(str);
        }

A: No json! instead of going through a list in javascript, return a completed <li> lists and replace innerHTML of <ul>.The reason to do so is to give a better performance. Unless you want to do something more flexible, leave things to the back-end.
When do json, you gotta parse string into json object and then loop through and generate html, that's just an extra step. Keep things simple, plus, parsing string could be costly.
If you don't loop through the list and instead do out.println the list object, you would likely see the address. also, you need to generate html, so:
StringBuilder sb = new StringBuilder();
for(String option: options){
sb.append("<li>").append(option).append("</li>");
}
out.println(sb);


text:
Q: "This application could not be started." Only when the file is in system32 directory I wrote a little piece of software that downloads file from internet, that is, nothing more. My intentions are to use it thru the command line...
It works great, but when I place it in C:\Windows\System32\ to actually use it from everywhere I want it doesn't work now... It didn't throw an exception... it just show me this messagebox - http://i.imgur.com/a7rlMgo.png and if I click "Yes" it opens this page in the browser - http://support.microsoft.com/kb/2715633/en-us
What should I do to get it working?
The code if it is of any use.. :
private const string InsufficientParametersMessage = "Insufficient Parameters...";

private static string[] _arguments;

static void Main(string[] args)
{
    _arguments = args;

    TakeCommand();

    Environment.Exit(0);
}

private static void TakeCommand()
{
    if (_arguments.Length < 1)
    {
        Console.WriteLine(InsufficientParametersMessage);
    }
    else if (_arguments.Length == 1)
    {
        DownloadFile(_arguments[0]);
    }
    else if (_arguments.Length > 1)
    {
        DownloadFile(_arguments[0], _arguments[1]);
    }
}

private static void DownloadFile(string url)
{
    DownloadFile(url, Path.GetFileName(url));
}

private static void DownloadFile(string url, string localFileName)
{
    WebClient client = new WebClient();

    if (File.Exists(localFileName))
    {
        File.Delete(localFileName);
    }

    try
    {
        client.DownloadFile(url, localFileName);
        Console.WriteLine("Done...");
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message);
    }
}

A: Short Answer: Uncheck "Prefer 32-bit".
Long Answer: (Not 100% sure but here goes)
Assuming you have a 64 bit machine, keep in mind that System32 is a folder that is reserved for 64 bit application usage, and although it may seem strange, SysWOW64 contains 32 bit dlls and is reserved for 32-bit applications. Typically, 32-bit applications that access System32 will go through a file system redirector to the SysWOW64 folder. More info here.
However, when your application (which runs as a 32-bit process) runs in System32 itself, the redirector probably doesn't do anything because it thinks there isn't any need to redirect, which is why your app works outside of System32 but not inside it.
So to solve this, uncheck Prefer 32-bit so that it will try to target 64 bit platform, ... or better yet, put the app elsewhere and add the application directory to your environment path variable. That way you can still access your application .exe anywhere, and it won't pollute your System32 folder which should only be used for Windows files anyways.

A: This answer may not be applicable to the OP's problem (which has been solved anyway), but maybe for others who end up here due to a search on "This application could not be started" and System32. In my case I had written a screensaver program in C# that had to run 32-bit, and the solution was to install it in the Windows directory, not Windows\System32. Then it works OK on both 32- and 64-bit systems.

A: If you put your 32-bit exe in both the System32 and the SysWOW64 folder. It works just fine. Not one, not the other, but both folders.
This might sound strange, but try it. If you put the same exe in both folders it will start up without any modifications.

A: I just moved the NuGet.exe from c:\Windows\System32 to c:\Windows and it works.

A: Maybe this answer is not directly applicable for OP answer, but for sure it is connected and it solved my issue.
On my company computer I have a few folders, which automatically sync with OneDrive. Those files are permanently labelled as "Work", not "Personal".
Each time I copied between those folders, which are syncing, I cannot run my developed application.
When I created a new directory, outside of syncing folders, I was able to change File Ownership to "Personal" (see below):

Just after that, my program works perfectly.


text:
Q: jqGrid: Searching with json data I have succeeded to load data from server in spring framework with pagination but my searching/finding records and filter bar is not working.
But if i make loadonce=true then the filter or searching working fine.
My code for my jsp is:
var allColumnNames=["Sr. No","contactName", "city", "country"];

 var grid = jQuery('#list');

        grid.jqGrid({
            url:'customerData.html',
            datatype: 'json',
            mtype: 'GET',
            loadonce: false,

            colNames: allColumnNames,
            colModel: [

                { name:'id', index:'id', jsonmap:"id", width:20,index:'id', search:true, stype:'int' ,hidden:true},
                { name: "contactName" ,index:'contactName', width:160, search:true, stype:'text' },
                { name: "city",index:'city', width:160, search:true, stype:'text'  },
                { name: "country" ,index:'country', width:160, search:true, stype:'text' }
            ],
             caption: 'Customer Details',
                height: 'auto',
                gridview: true,
                rownumbers: true,
                viewrecords: true,
                pager: '#pager',
                rowNum: 10,
                rowList: [5, 10, 20, 50],
                rownumbers: true
            });

           $("#search").click(function() {
            var searchFiler = $("#filter").val(), f;

            if (searchFiler.length === 0) {
                grid[0].p.search = false;
                $.extend(grid[0].p.postData,{filters:""});
            }
            f = {groupOp:"OR",rules:[]};
            f.rules.push({field:"contactName",op:"cn",data:searchFiler});
            f.rules.push({field:"city",op:"cn",data:searchFiler});
            grid[0].p.search = true;
            $.extend(grid[0].p.postData,{filters:JSON.stringify(f)});
            grid.trigger("reloadGrid",[{page:1,current:true}]);
        });

I am new to jqGrid, Please help me in above problem.
Thanks in advance!

A: When you put loadonce=true jqGrid only makes one request that takes all the data, and then if you filter, sort, search... are controlled by jqGrid in the frontend.
But if loadonce=false, only loads the data needed at this moment, and every time jqGrid needs new data, it sends another request to the server with differents parameters.

So I can guess that your server file "customerData.html", it's not ready to answer all the different questions.
Here http://trirand.com there are a lot of jqGrid examples an most of them have the server side code.


text:
Q: Connection String error while changing database I developed my web application using Asp.net and SQL Server. After that I try to host it on my local server. I installed SQL Server Express on my server and created the database on that server. And then I host my web app after changing my connection string according to the new database. But I get an error while running the web site. I use Windows authentication in SQL Server. Please help me fix this issue.

The system cannot find the file specified
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified
Source Error:
  The source code that generated this unhandled exception can only be shown when compiled in debug mode.

To enable this, please follow one of the below steps, then request the URL:

*

*Add a "Debug=true" directive at the top of the file that generated the error.
Example:
<%@ Page Language="C#" Debug="true" %>

or:

*Add the following section to the configuration file of your application:
<configuration>
    <system.web>
        <compilation debug="true"/>
    </system.web>
</configuration>

Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.
Important: running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario.


text:
Q: Movie searching site using TMDb and axios npm I'm trying to make a movie searching site using TMDb and axios npm. What am I doing wrong?
Search works fine, but I can't access the movies themselves.

$(document).ready(() => {
  $('#searchForm').on('submit', (e) => {
    let searchText = $('#searchText').val();
    getMovies(searchText);
    e.preventDefault();
  });
});

function getMovies(searchText) {
  axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
    .then((response) => {
      console.log(response);
      let movies = response.data.Search;
      let output = '';
      $.each(movies, (index, movie) => {
        output += `

${movie.original_title}

              Movie Details

        `;
      });

      $('#movies').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

function movieSelected(id) {
  sessionStorage.setItem('id', id);
  window.location = 'movie.html';
  return false;
}

function getMovie() {
  let id = sessionStorage.getItem('id');

  axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
    .then((response) => {
      console.log(response);
      let movie = response.data;

      let output = `

${movie.Title}

Genre: ${movie.genres.Name}

Released: ${movie.release_date}

Rated: ${movie.vote_average}

Review: ${movie.overview}

Plot

            ${movie.Plot}

            View TMDb
            Go Back To Search

      `;

      $('#movie').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}
#movies img,
#movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 390px;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>MovieInfo</title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <link href="css/style.css" rel="stylesheet" />

        MovieInfo

Search For Any Movie

      <form id="searchForm">
        <input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
      </form>

--More details, because I have more code:
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.

A: This will help you click here, Now it is working. There was very small bug, which I mentioned to you.
And also fixed the image not showing issue.

A: Just replace response.data.Search by response.data.results

$(document).ready(() => {
  $('#searchForm').on('submit', (e) => {
    let searchText = $('#searchText').val();
    getMovies(searchText);
    e.preventDefault();
  });
});

function getMovies(searchText) {
  axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
    .then((response) => {
      console.log(response);
      let movies = response.data.results;
      let output = '';
      $.each(movies, (index, movie) => {
        output += `

${movie.original_title}

              Movie Details

        `;
      });

      $('#movies').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

function movieSelected(id) {
  sessionStorage.setItem('id', id);
  window.location = 'movie.html';
  return false;
}

function getMovie() {
  let id = sessionStorage.getItem('id');

  axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
    .then((response) => {
      console.log(response);
      let movie = response.data;

      let output = `

${movie.Title}

Genre: ${movie.genres.Name}

Released: ${movie.release_date}

Rated: ${movie.vote_average}

Review: ${movie.overview}

Plot

            ${movie.Plot}

            View TMDb
            Go Back To Search

      `;

      $('#movie').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}
#movies img,
#movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 390px;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>MovieInfo</title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <link href="css/style.css" rel="stylesheet" />

        MovieInfo

Search For Any Movie

      <form id="searchForm">
        <input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
      </form>


text:
Q: Apache Superset Installation - Load_Examples commad not working I am trying to install Apache Superset and have followed all of the installation instructions from here.
https://gist.github.com/mark05e/d9cccae129dd11a21d7219eddd7d9923
I have got as far as trying to install the load_examples. When I run the command
Python superset load_examples I am getting this error
C:\Users\Superset\superset\Scripts
(superset) λ python superset load_examples
INFO:root:logging was configured successfully
C:\Users\Superset\Superset\superset\Scripts\flask_caching_init_.py:201: UserWarning: Flask-Caching: CACHE_TYPE is set to null, caching is effectively disabled.
warnings.warn(
Usage: superset [OPTIONS] COMMAND [ARGS]...
Try 'superset --help' for help.
Error: No such command 'load_examples'.
However, if I run python superset --help I can see that it is a command.

Does anyone have any ideas what I am doing wrong?

A: It seems that you're trying use command load_examples. But the right command written with dash — load-examples.

A: you can run on the virtual env
first of all you want to activate the environment
After than you can run this below code
superset load_examples


text:
Q: PDA Internal ftp files copy Im trying to make a windows script for making a retrieval from a PDA (INTERMEC CN70). The fun part of this pda is that what i try to do is implemented in activesync, but not more supported at my place of work.
So as the files generated by the pda is saved in an internal FTP of the pda and is connected in an Ethernet dock, I made an easy script to connect to the internal FTP, the issue is that i'm not an script rock star and once inside i don't know how to copy the files with the script, i seerched options like robocopy or xcopy but i don't know how to make this commands work for not overwriting the files.
I post my script here
@ECHO OFF
SET /p ippda=PDA ACTUAL IP?:
IF "%ippda%"=="" GOTO Faliure
explorer ftp://intermec:cr52401@%ippda%/
Goto End
:Faliure
ECHO IP faliure
PAUSE
:END

Thanks for your time^^


text:
Q: How do I make image face mouse in javascript? I'm trying to use javascript to make an image face the mouse of the user, I'm close but my calculations are a bit off (the rotation on the x-axis seems to be inverted). I based my code of this link: rotate3d shorthand
javascript:
$(document).mousemove(function(e){
   pageheight = $(document).height();
   pagewidth = $(document).width();
   widthpercentage = e.pageX / pagewidth;
   heightpercentage = e.pageY / pageheight;
   specialW = (widthpercentage * 180 - 90);
   specialH = (heightpercentage * 180 - 90);

   function toRadians(degrees) {
     radians = degrees * (Math.PI /180);
     return radians;
    }

   function matrix(x, y, z, rads) {
    var sc = Math.sin(rads / 2) * Math.cos(rads / 2);
    var sq = Math.pow(Math.sin(rads / 2), 2);

    var array = [];
    var a1 = 1 - 2 * (Math.pow(y, 2) + Math.pow(z, 2)) * sq,
        a2 = 2 * (x * y * sq - z * sc),
        a3 = 2 * (x * z * sq + y * sc),
        a4 = 0,
        b1 = 2 * (x * y * sq + z * sc),
        b2 = 1 - 2 * (Math.pow(x, 2) + Math.pow(z, 2)) * sq,
        b3 = 2 * (y * z * sq - x * sc),
        b4 = 0,
        c1 = 2 * (x * z * sq - y * sc),
        c2 = 2 * (y * z * sq + x * sc),
        c3 = 1 - 2 * (Math.pow(x, 2) + Math.pow(y, 2)) * sq,
        c4 = 0,
        d1 = 0,
        d2 = 0,
        d3 = 0,
        d4 = 1;
      array.push(a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4);
        return array;
        }

        xmatrix = matrix(1, 0, 0, toRadians(specialH));
        ymatrix = matrix(0, 1, 0, toRadians(specialW));

        function multiply(xarray, yarray) {
            var newarray = [];
            var a1 = (xarray[0] * yarray[0]) + (xarray[4] * yarray[1]) + (xarray[8] * yarray[2]) + (xarray[12] * yarray[3]),
                a2 = (xarray[0] * yarray[4]) + (xarray[4] * yarray[5]) + (xarray[8] * yarray[6]) + (xarray[12] * yarray[7]),
                a3 = (xarray[0] * yarray[8]) + (xarray[4] * yarray[9]) + (xarray[8] * yarray[10]) + (xarray[12] * yarray[11]),
                a4 = (xarray[0] * yarray[12]) + (xarray[4] * yarray[13]) + (xarray[8] * yarray[14]) + (xarray[12] * yarray[15]),
                b1 = (xarray[1] * yarray[0]) + (xarray[5] * yarray[1]) + (xarray[9] * yarray[2]) + (xarray[13] * yarray[3]),
                b2 = (xarray[1] * yarray[4]) + (xarray[5] * yarray[5]) + (xarray[9] * yarray[6]) + (xarray[13] * yarray[7]),
                b3 = (xarray[1] * yarray[8]) + (xarray[5] * yarray[9]) + (xarray[9] * yarray[10]) + (xarray[13] * yarray[11]),
                b4 = (xarray[1] * yarray[12]) + (xarray[5] * yarray[13]) + (xarray[9] * yarray[14]) + (xarray[13] * yarray[15]),
                c1 = (xarray[2] * yarray[0]) + (xarray[6] * yarray[1]) + (xarray[10] * yarray[2]) + (xarray[14] * yarray[3]),
                c2 = (xarray[2] * yarray[4]) + (xarray[6] * yarray[5]) + (xarray[10] * yarray[6]) + (xarray[14] * yarray[7]),
                c3 = (xarray[2] * yarray[8]) + (xarray[6] * yarray[9]) + (xarray[10] * yarray[10]) + (xarray[14] * yarray[11]),
                c4 = (xarray[2] * yarray[12]) + (xarray[6] * yarray[13]) + (xarray[10] * yarray[14]) + (xarray[14] * yarray[15]),
                d1 = (xarray[3] * yarray[0]) + (xarray[7] * yarray[1]) + (xarray[11] * yarray[2]) + (xarray[15] * yarray[3]),
                d2 = (xarray[3] * yarray[4]) + (xarray[7] * yarray[5]) + (xarray[11] * yarray[6]) + (xarray[15] * yarray[7]),
                d3 = (xarray[3] * yarray[8]) + (xarray[7] * yarray[9]) + (xarray[11] * yarray[10]) + (xarray[15] * yarray[11]),
                d4 = (xarray[3] * yarray[12]) + (xarray[7] * yarray[13]) + (xarray[11] * yarray[14]) + (xarray[15] * yarray[15]);

        newarray.push(a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4);
        return newarray;
        }
        var newmatrix  = multiply(xmatrix, ymatrix);

        $('#page1 img').css('transform', 'matrix3d(' + newmatrix[0] + ','  + newmatrix[1] + ',' + newmatrix[2] + ',' + newmatrix[3] + ',' + newmatrix[4] + ',' + newmatrix[5] + ',' + newmatrix[6] + ',' + newmatrix[7] + ',' + newmatrix[8] + ',' + newmatrix[9] + ',' + newmatrix[10] + ',' + newmatrix[11] + ',' + newmatrix[12] + ',' + newmatrix[13] + ',' + newmatrix[14] + ',' + newmatrix[15] + ')');
});

I know it's a lot of code, but if I could get a second a opinion, It would be greatly appreciated. Thanks
No plugins please.

A: I actually just edited the matrix() function and added this right before array.push:
if ( y = 1 ) {
    a3 = a3 * -1;
    c1 = c1 * -1;
}

And this fixed the issue.


text:
Q: Add panels to Bootstrap 3 accordion dynamically I am trying to add Bootstrap 3 panels to an accordion dynamically. My (relevant) code is given below:

and the JS code:
$("#addqueuebutton").on("click",function(){
    var queue = '
';
    queue += '
';
    queue += '
';
    queue += '' + $('#queuename').val() + '';
    queue += '';
    queue += '
';
    queue += '
';
    queue += '
';
    queue += '
' + This is a test + '
';
    queue += '
';
    queue += '
';
    $('#queues-accordion').append(queue);
})

I followed this guide - Add dynamic closed panels in Bootstrap 3 accordion, but I am not getting the panel to appear on the page. Can anyone point out my mistake please?

A: The following line is invalid
queue += '
' + This is a test + '
';

This is a test is a string and should be added like a string. Javascript will interpret it like a variable (which is again invalid).
Something like this should work instead
queue += '
This is a test
';

or store This is a test as a variable and concatenate it
var test = 'This is a test';
queue += '
' + test + '
';


text:
Q: Javascript Date object return same hour for different timestamps I have two separate timestamps:
'2021-03-28T02:00:00' and '2021-03-28T03:00:00'
Both dates return the same JS timestamp:
Sun Mar 28 2021 03:00:00 GMT+0200 (Central European Summer Time)
I believe this is because Central European Summer time starts 2021-03-28T02:00:00 but then I would expect 2021-03-28T03:00:00 to return 04:00:00 and not 03:00:00.
In short. I need the date '2021-03-28T02:00:00' to return:
Sun Mar 28 2021 02:00:00 GMT+0200 (Central European Summer Time)
How come this is not what I am getting? why do I get the same timestamp from the two different dates?

A: 2021-03-28T02:00:00 cannot return what you want because such a time doesn't exist in practice. One second earlier, 2021-03-28T001:59:59 GMT+0100 exists, but as soon as the next second elapses the time becomes  03:00:00 GMT+0200.
You will have to modify your surrounding code in some other way, to remove the 'need' to display an impossible time.


text:
Q: How to update woocommerce_after_order_notes when address changes? Before anything, thank you in advance for your help.
I have a woocommercer store. I have set up a field for the clients to choose the delivery date they prefer with add_action( 'woocommerce_after_order_notes', 'elige_fecha_entrega' );
The delivery options depend on the shipping zone. For certain zones the have certain days available. All this code is fine and it works. My next question is how to make the content change dynamically if the client changes its address.
I mean, how could I add a trigger so when the address changes my action runs again so the options are updated without refreshing the page (which is what they have to do now).
Thank you in advance.


text:
Q: Working with authorized .net payment gateway in ios i am working with authorized .net payement gateway in ios
In the following method
 (void) createTransaction {
    AuthNet *an = [AuthNet getInstance];

    [an setDelegate:self];

    CreditCardType *creditCardType = [CreditCardType creditCardType];
    creditCardType.cardNumber = @"4111111111111111";
    NSLog(@"babul cardNumber is %@",creditCardType.cardNumber);
    creditCardType.cardCode = @"100";
    NSLog(@"babul cardCode is %@",creditCardType.cardCode);
    creditCardType.expirationDate = @"1212";
    NSLog(@"babul expirationDate is %@",creditCardType.expirationDate);
    PaymentType *paymentType = [PaymentType paymentType];
    paymentType.creditCard = creditCardType;

    ExtendedAmountType *extendedAmountTypeTax = [ExtendedAmountType extendedAmountType];
    extendedAmountTypeTax.amount = @"0";
    extendedAmountTypeTax.name = @"Tax";

    ExtendedAmountType *extendedAmountTypeShipping = [ExtendedAmountType extendedAmountType];
    extendedAmountTypeShipping.amount = @"0";
    extendedAmountTypeShipping.name = @"Shipping";

    LineItemType *lineItem = [LineItemType lineItem];
    lineItem.itemName = @"Soda";
    lineItem.itemDescription = @"Soda";
    lineItem.itemQuantity = @"1";
    lineItem.itemPrice = @"1.00";
    lineItem.itemID = @"1";

    TransactionRequestType *requestType = [TransactionRequestType transactionRequest];
    requestType.lineItems = [NSArray arrayWithObject:lineItem];
    requestType.amount = @"1.00";
    requestType.payment = paymentType;
    requestType.tax = extendedAmountTypeTax;
    requestType.shipping = extendedAmountTypeShipping;

   CreateTransactionRequest *request = [CreateTransactionRequest createTransactionRequest];
    request.transactionRequest = requestType;
    request.transactionType = AUTH_ONLY;
    request.anetApiRequest.merchantAuthentication.mobileDeviceId =
    [[[UIDevice currentDevice] uniqueGlobalDeviceIdentifier]
     stringByReplacingOccurrencesOfString:@"-" withString:@"_"];
    request.anetApiRequest.merchantAuthentication.sessionToken = sessionToken;
    [an purchaseWithRequest:request];
}

i am getting the response as
Create Transaction response
2012-07-26 19:14:00.131 Authorized[2355:207] ErrorE00003The element 'merchantAuthentication' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'mobileDeviceId' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'name, transactionKey, sessionToken, password' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'.
namespace warning : xmlns: URI AnetApi/xml/v1/schema/AnetApiSchema.xsd is not absolute
ttp://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"
                                                                               ^
2012-07-26 19:14:00.131 Authorized[2355:207] Error = (null)
2012-07-26 19:14:00.247 Authorized[2355:207] babul output is Message.code = E00003
Message.text = The element 'merchantAuthentication' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'mobileDeviceId' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'name, transactionKey, sessionToken, password' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'.
Is there any alternative to the above problem and how the transactions are going to be stored in authorized .net
(i created my test account, i am giving those credentials, i approved my device but later i am getting the above error)
Thanks in advance

A: I think you need to go for in app purchase because Apple will not approve application payment through any web service or API.


text:
Q: How to set different resolutions in the android graphical layout i am a new developer in android applications.
Recently i've been working on creating some UIs.Here comes the problem.
Assume that i need to create an xml file for a UI with a resolution of 500 x 600.
When i create the file,i need to see how it looks like in the graphical layout window in eclipse from time to time.But i got only 3.7in WVGA or 4.0in QVGA or others,while no 500x600 resolutions.
So how can i be able to see this UI in the graphical layout window with the specified resolution?
I've been searching it for some days,yet i don't make it.
Any help will be appreaciate.
thanks a lot!
^_^

A: It would be better if that was dynamic but if its really needed you can create version for each resolution.

A: Just open the list with the available configurations and click the "Custom..." entry.
A new window pops up. Scroll down and click on the "Custom" entry, then click the "New..." button, and you are able to create a customized "device" with your resolution.


text:
Q: Transform RGB color space to LMS color space So I have been trying to convert an RGB color space to LMS space, apply certain color filters and then back to RGB space. Works fine with OpenCV and on images.
Now, I need to apply such color filters on a Qt application or the elements in the application. I found the QColorSpace and QColorTransform in Qt Graphical Effects module but these have no examples as such.
So my question is, if I have a Qt application that displays a rectangle with a few colors in it, then how can I apply a color filter on this application which would make the rectangle with the same colors look different because of the color filter?
If the color filter cannot be applied on the whole application, then is it possible to apply it on only the rectangle?
I understand that such a filter needs to be programmed in the shader somehow. But I am not sure how to do this.
Any examples explaining this in Qt would be great.


text:
Q: What exactly is an input/output stream? I've written code to spec that must be capable of taking in text from an input stream and writing it out through an output stream. The code is made to encrypt messages from a file or from the user entering, and either writing it to the command prompt or to a file. How can the general class of input/output stream handle both of these things, and what type of argument do i give to the parameters of the function that fit the spec of input stream and output stream?

A: your functions might be something like:
public void encryptFile(String inFile, String outFile) {
   ...
}

public void encryptConsoleToFile(String outFile) {
   ...
}

or maybe am I misunderstanding your question?

A: A input/output stream represents any stream of data coming from some source that is either coming into your code or going away from it. Specifically:
An input stream represents data coming from some source that can be read, a producer of data. Whether or not the length of data is known is dependent on the source. Examples of this are input streams to read from files (FileInputStream object in java), read from networks, read from existing byte arrays (ByteArrayInputStream), etc. A file for example will produce data when read via the input stream until the end of file is reached whereas something like an ongoing TCP connection would produce data until the connection is terminated.
An output stream behaves in the exact same way except it is used for writing data from your program to the target destination. Writing to a file (FileOutputStream), writing to a TCP stream, writing to a target byte array are all examples of this.
The so-called specifications of your input/output stream are tied directly to what source/destination you are reading from/writing to. For example, when writing to a console, you may elect to use line-buffering so that the user can see the output near-immediately whereas writing to a file you can use a larger buffer to improve performance.
In java specifically, the InputStream and OutputStream class define the basic specifications of all I/O streams in java.

A:
What exactly is an input/output stream?

InputStream and OutputStream are two separate abstract classes. I recommend reading through and understanding their documentation.

How can the general class of input/output stream handle both of these things, and what type of argument do i give to the parameters of the function that fit the spec of input stream and output stream?

They are generally not implemented by the same class (and since they are abstract classes, it's not possible to have a class extend both). There is one class hierarchy for input, another for output.


text:
Q: Represent multiple normal priors with a single call in Bayesian logistic regression with Tensorflow I am trying to properly represent multiple normal priors with a function call in the joint distribution and run mcmc.sample_chain with NUTS kernel. I used the excellent blog post here for a sketch with the following MCMC implementation.
def trace_fn(_, pkr):
    return (
        pkr.inner_results.inner_results.target_log_prob,
        pkr.inner_results.inner_results.leapfrogs_taken,
        pkr.inner_results.inner_results.has_divergence,
        pkr.inner_results.inner_results.energy,
        pkr.inner_results.inner_results.log_accept_ratio
    )
def run_nuts(
    target_log_prob_fn,
    inits,
    trace_fn=trace_fn,
    bijectors_list=None,
    num_steps=5000,
    num_burnin=500,
    n_chains=n_chains):

    step_size = np.random.rand(n_chains, 1)*.5 + 1.

    if not isinstance(inits, list):
        inits = [inits]

    if bijectors_list is None:
        bijectors_list = [tfb.Identity()]*len(inits)

    kernel = tfp.mcmc.DualAveragingStepSizeAdaptation(
        tfp.mcmc.TransformedTransitionKernel(
            inner_kernel=tfp.mcmc.NoUTurnSampler(
                target_log_prob_fn,
                step_size=[step_size]*len(inits)
            ),
            bijector=bijectors_list
        ),
        target_accept_prob=.8,
        num_adaptation_steps=int(0.8*num_burnin),
        step_size_setter_fn=lambda pkr, new_step_size: pkr._replace(
              inner_results=pkr.inner_results._replace(step_size=new_step_size)
          ),
        step_size_getter_fn=lambda pkr: pkr.inner_results.step_size,
        log_accept_prob_getter_fn=lambda pkr: pkr.inner_results.log_accept_ratio,
    )

    res = tfp.mcmc.sample_chain(
        num_results=num_steps,
        num_burnin_steps=num_burnin,
        current_state=inits,
        kernel=kernel,
        trace_fn=trace_fn
    )
    return res

I can get the MCMC working when individually specifying the priors but not when declaring them as a batch.
This works
dtype=tf.float32
root = tfd.JointDistributionCoroutine.Root
def basic_logistic(data_df):
    def _generator():
        a = yield root(tfd.Sample(tfd.Normal(0,10),1, name='a'))
        b = yield root(tfd.Sample(tfd.Normal(0,10),1, name='b'))
        c = yield root(tfd.Sample(tfd.Normal(0,10),1, name='c'))
        l = a+tf.cast(data_df['x1'],dtype)*b + tf.cast(data_df['x2'],dtype)*c
        print(l)
        y = yield tfd.Independent(
            tfd.Bernoulli(
                logits = l,
                name = 'success'
            ),
            reinterpreted_batch_ndims=1
        )

    return tfd.JointDistributionCoroutine(_generator)

arm_0_test = basic_logistic(arm_0_test_df)
arm_0_log_prob = lambda *args: arm_0_test.log_prob(args + (tf.cast(arm_0_test_df['y'],dtype),))

n_chains=3
arm0_res = run_nuts(arm_0_log_prob, [tf.ones((n_chains,1)), tf.ones((n_chains,1)), tf.ones((n_chains,1))])

This does not
dtype=tf.float32
root = tfd.JointDistributionCoroutine.Root
def basic_logistic_multiple(X_df):
    X_df_copy = X_df.copy()
    n_features = X_df_copy.shape[1] + 1 # have to include intercept term
    prior_means = [0 for i in range(n_features)] # list of prior means
    print(prior_means)
    prior_sds = [10 for i in range(n_features)] # list of prior sds
    X_df_copy.insert(0, 'intercept', np.ones(X_df_copy.shape[0])) # Add column of 1s for intercept
    X = tf.convert_to_tensor(X_df_copy, dtype=dtype)
    def _generator():
        beta = yield root(tfd.Sample(
                tfd.Normal(prior_means, prior_sds, name='beta')
            ))
        print(beta)
        l = tf.tensordot(X, beta, axes=1)
        # l = tf.reshape(l, (l.shape[0], ))
        print(l)
        y = yield tfd.Independent(
            tfd.Bernoulli(
                logits = l,
                name = 'success'
            ),
            reinterpreted_batch_ndims=1
        )

    return tfd.JointDistributionCoroutine(_generator)

arm_0_test = basic_logistic_multiple(arm_0_test_df)
arm_0_log_prob = lambda *args: arm_0_test.log_prob(args + (tf.cast(arm_0_test_df['y'],dtype),))

n_chains=3
init_beta, _ = arm_0_test.sample(n_chains)
init_beta = tf.zeros_like(init_beta)
arm0_res = run_nuts(arm_0_log_prob, [init_beta,])

I get the following error

ValueError: Dimensions must be equal, but are 3 and 1000000 for '{{node mcmc_sample_chain/dual_averaging_step_size_adaptation___init__/_bootstrap_results/transformed_kernel_bootstrap_results/NoUTurnSampler/.bootstrap_results/process_args/maybe_call_fn_and_grads/value_and_gradients/value_and_gradient/JointDistributionCoroutine_CONSTRUCTED_AT_top_level/log_prob/add_1}} = AddV2[T=DT_FLOAT](mcmc_sample_chain/dual_averaging_step_size_adaptation___init__/_bootstrap_results/transformed_kernel_bootstrap_results/NoUTurnSampler/.bootstrap_results/process_args/maybe_call_fn_and_grads/value_and_gradients/value_and_gradient/JointDistributionCoroutine_CONSTRUCTED_AT_top_level/log_prob/add, mcmc_sample_chain/dual_averaging_step_size_adaptation___init__/_bootstrap_results/transformed_kernel_bootstrap_results/NoUTurnSampler/.bootstrap_results/process_args/maybe_call_fn_and_grads/value_and_gradients/value_and_gradient/JointDistributionCoroutine_CONSTRUCTED_AT_top_level/log_prob/Independentsuccess/log_prob/Sum)' with input shapes: [3,3], [1000000].

I can sample from both Jointdistributions fine so I believe it is something clashing in the sample_chain function. Possibly my initial state declaration?
Thanks for any help!


text:
Q: Check Host Connectivity by HostName/IP I have this script which can check host connectivity by its name, but I want it to check the connectivity either by name or its IP address as sometimes I don't have the HostName with me.
$ComputersFile = "HostName.txt"
$OutputFile = "Output.txt"

$Computers = Get-Content $ComputersFile

Remove-Item 'Output.txt'

foreach ($Computer in $Computers) {
    try {
        $DNS = [System.Net.Dns]::GetHostByAddress($Computer)
        if (Test-Connection $Computer -Count 1 -ErrorAction SilentlyContinue) {
            "$Computer^Yes^$($DNS.HostName)^$($DNS.AddressList[0].IPAddressToString)^ONLINE" |
                Out-File -Enc UTF8 -Append $OutputFile
        } else {
            "$Computer^Yes^$($DNS.HostName)^$($DNS.AddressList[0].IPAddressToString)^OFFLINE" |
                Out-File -Enc UTF8 -Append $OutputFile
        }
    } catch {
        "$Computer^No" | Out-File -Enc UTF8 -Append $OutputFile
    }
}

The input will be a text file which has a bunch of IP addresses and HostName.
The script should be able to read/recognize both of them and check whether the host is online/offline.


text:
Q: How to use an option in a selection element to run a function depending on the selected option I aim to use a selected option (item01) on a selector element to run a specific function and this function should then apply a class to each of the objects inside of the array (array01) using the ids of the objects that correspond to elements on a different part of the web page.
This is what I have written, but I can not figure out what to do to make it work.

let array01 = [{id:"07-01"}, {id:"05-01"}, {id:"05-03"}, {id:"05-05"}, {id:"05-07"}, {id:"05-09"}, {id:"05-11"}, {id:"05-13"}, {id:"05-05"}, {id:"06-05"}, {id:"07-08"}, {id:"07-11"}, {id:"06-13"}]

const test = array01.map(item => item.id);

$("#item1").on("click", function() {
  test.forEach(element => (("#" + element).addClass("mySpecialClass")));
});
<select id="selector" class="selector">
  <option selected>Preset</option>
  <option value="item1" class="item1" id="item1">item1</option>
  <option value="item2" class="item2" id="item2">item2</option>
  <option value="item3" class="item3" id="item3">item3</option>
</select>

A: The simplest way to do what you require would be to match the elements which should have the class to the selected option's value. In the example below I've done this by placing the classes to group the elements in the HTML.
Note in the example below that it's using the change event of the select, not the click on the option elements. The latter is not very reliable across all browsers.

$('#selector').on('change', e => {
  $('.item').removeClass('mySpecialClass');
  $('.' + e.target.value).addClass('mySpecialClass');
});
.mySpecialClass {
  background-color: #C00;
  color: #FFF;
}

<select id="selector" class="selector">
  <option selected>Preset</option>
  <option value="item1">item1</option>
  <option value="item2">item2</option>
  <option value="item3">item3</option>
</select>

item1

item2

item3

item1 item2

item3 item2

item1 item3

item2 item3

item1 item2 item3


text:
Q: SSH disconnecting after successful auth when using AD credentials I am working on getting SSH to accept AD credentials.
Server details

*

*CentOS 8

*Server is successfully joined to the domain

*Ran realm discover which returned proper information regarding our AD environment

*realm permit run to permit specific users

*SSH config file has been slightly modified. It mainly only blocks root logins.

*SSH to the server using a local user account works.

*User looking is possible using id someuser. I do not need to append upn suffix (@ad.sample.com).

Behavior

*

*When signing in via SSH it prompts for user name (provided AD user name), then password (provide AD user password), and after providing the password the SSH session immediately terminates. I can see the request coming in via the /var/log/secure log and I can see that the credentials are being accepted. As soon as it passes authentication though the session is immediately closed. I tested using the wrong credentials for the user and can see this being reported in the secure log as all on the terminal itself.

*I also tested trying to sign in via the actual server console, it initially appears to let me in, then immediately boots me back to login.

*Interesting thing from the SSH debug is that the MOTD is visible.

*When a new user attempts to sign in via SSH their home directory gets created.

Part of the output from SSH debug
someuser@x.x.x.x's password:
debug3: packet_send2: adding 48 (len 72 padlen 8 extra_pad 64)
debug2: we sent a password packet, wait for reply
debug1: Authentication succeeded (password).
Authenticated to x.x.x.x ([x.x.x.x]:xx).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug1: Requesting
debug1: Entering interactive session.
debug1: client_input_global_request: rtype  want_reply 0
debug2: callback start
debug2: fd 3 setting TCP_NODELAY
debug3: packet_set_tos: set IP_TOS 0x10
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug1: Sending environment.
debug3: Ignored env XDG_SESSION_ID
debug3: Ignored env HOSTNAME
debug3: Ignored env TERM
debug3: Ignored env SHELL
debug3: Ignored env HISTSIZE
debug3: Ignored env SSH_CLIENT
debug3: Ignored env SSH_TTY
debug3: Ignored env USER
debug3: Ignored env LS_COLORS
debug3: Ignored env MAIL
debug3: Ignored env PATH
debug3: Ignored env PWD
debug1: Sending env LANG = en_US.UTF-8
debug2: channel 0: request env confirm 0
debug3: Ignored env HISTCONTROL
debug3: Ignored env SHLVL
debug3: Ignored env HOME
debug3: Ignored env LOGNAME
debug3: Ignored env SSH_CONNECTION
debug3: Ignored env LESSOPEN
debug3: Ignored env XDG_RUNTIME_DIR
debug3: Ignored env _
debug2: channel 0: request shell confirm 1
debug2: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0
Activate the web console with: systemctl enable --now cockpit.socket

Last login: Tue Jun  9 some date from x.x.x.x
debug2: channel 0: rcvd eof
debug2: channel 0: output open -> drain
debug2: channel 0: obuf empty
debug2: channel 0: close_write
debug2: channel 0: output drain -> closed
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype  reply 0
debug2: channel 0: rcvd eow
debug2: channel 0: close_read
debug2: channel 0: input open -> closed
debug2: channel 0: rcvd close
debug3: channel 0: will not send data after close
debug2: channel 0: almost dead
debug2: channel 0: gc: notify user
debug2: channel 0: gc: user detached
debug2: channel 0: send close
debug2: channel 0: is dead
debug2: channel 0: garbage collecting
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
  #0 client-session (t4 r0 i3/0 o3/0 fd -1/-1 cc -1)

Connection to x.x.x.x closed.
Transferred: sent 2824, received 2420 bytes, in 0.1 seconds
Bytes per second: sent 24722.5, received 21185.7
debug1: Exit status 1

Our sssd.conf
[sssd]
domains = ad.sample.com
config_file_version = 2
services = nss, pam

[domain/ad.sample.com]
ad_domain = ad.sample.com
krb5_realm = AD.SAMPLE.COM
realmd_tags = manages-system joined-with-adcli
cache_credentials = True
id_provider = ad
krb5_store_password_if_offline = True
default_shell = /bin/bash
ldap_id_mapping = True
#use_fully_qualified_names = True
use_fully_qualified_names = False
#fallback_homedir = /home/%u@%d
fallback_homedir = /home/%u
access_provider = simple
simple_allow_users = someuser

I have checked several posts/blogs about setting this up and I don't think I've missed anything. I should mentioned that I have tried adding SSH to the services section in the sssd.conf file. It didn't make any difference.
Does anyone know what else I can check? Or what might be wrong?

A: Another thing to check is your access.conf file.  Some of the behavior you describe can be done with settings to allow local accounts but deny others until valid group or users are set up.

A: I was able to finally figure this issue out. There was one main issue:

*

*My SSSD config was missing values to define the users shell

I was initially alerted to this issue by the following post: Highlight of error in SSH debug
Specifically, there was the following line the SSH debug that was indicating the problem
client_input_channel_req: channel 0 rtype exit-status reply 0

According to this link this shows that a shell cannot be selected for the user.
I checked our AD and the attribute for loginShell is populated, but the system doesn't appear to accept this. I added the following lines to my /etc/sssd/sssd.conf file
override_shell = /bin/bash
shell_fallback = /bin/bash

Once I added these, I was able to successfully login using SSH.
I then ran into another problem there the users home directory was not getting created. There is an AD attribute that can control this called unixHomeDirectory. We don't populate this for all users so I added an override for the home directory in the SSSD config as well.
override_homedir = /home/%u

The final config for SSSD looks like this:
[sssd]
domains = example.com
config_file_version = 2
services = nss, pam

[domain/example.com]
ad_domain = example.com
krb5_realm = example.com
realmd_tags = manages-system joined-with-adcli
cache_credentials = True
id_provider = ad
krb5_store_password_if_offline = True
default_shell = /bin/bash
override_shell = /bin/bash
shell_fallback = /bin/bash
ldap_id_mapping = True
use_fully_qualified_names = False
fallback_homedir = /home/%u
override_homedir = /home/%u
access_provider = simple
simple_allow_users = someuser


text:
Q: Slide function for icons on touchscreen I have this slider here, but when I click it, it disappears. I'm looking through it now for hours but it's not possible with my skills to find a solution.

// get our elements
const slider = document.querySelector('.slider-container'),
  slides = Array.from(document.querySelectorAll('.slide'))

// set up our state
let isDragging = false,
  startPos = 0,
  currentTranslate = 0,
  prevTranslate = 0,
  animationID,
  currentIndex = 0

// add our event listeners
slides.forEach((slide, index) => {
  const slideImage = slide.querySelector('img')
  // disable default image drag
  slideImage.addEventListener('dragstart', (e) => e.preventDefault())
  // touch events
  slide.addEventListener('touchstart', touchStart(index))
  slide.addEventListener('touchend', touchEnd)
  slide.addEventListener('touchmove', touchMove)
  // mouse events
  slide.addEventListener('mousedown', touchStart(index))
  slide.addEventListener('mouseup', touchEnd)
  slide.addEventListener('mousemove', touchMove)
  slide.addEventListener('mouseleave', touchEnd)
})

// make responsive to viewport changes
window.addEventListener('resize', setPositionByIndex)

// prevent menu popup on long press
window.oncontextmenu = function (event) {
  event.preventDefault()
  event.stopPropagation()
  return false
}

function getPositionX(event) {
  return event.type.includes('mouse') ? event.pageX : event.touches[0].clientX
}

// use a HOF so we have index in a closure
function touchStart(index) {
  return function (event) {
    currentIndex = index
    startPos = getPositionX(event)
    isDragging = true
    animationID = requestAnimationFrame(animation)
    slider.classList.add('grabbing')
  }
}

function touchMove(event) {
  if (isDragging) {
    const currentPosition = getPositionX(event)
    currentTranslate = prevTranslate + currentPosition - startPos
  }
}

function touchEnd() {
  cancelAnimationFrame(animationID)
  isDragging = false
  const movedBy = currentTranslate - prevTranslate

  // if moved enough negative then snap to next slide if there is one
  if (movedBy < -100 && currentIndex < slides.length - 1) currentIndex += 1

  // if moved enough positive then snap to previous slide if there is one
  if (movedBy > 100 && currentIndex > 0) currentIndex -= 1

  setPositionByIndex()

  slider.classList.remove('grabbing')
}

function animation() {
  setSliderPosition()
  if (isDragging) requestAnimationFrame(animation)
}

function setPositionByIndex() {
  currentTranslate = currentIndex * -window.innerWidth
  prevTranslate = currentTranslate
  setSliderPosition()
}

function setSliderPosition() {
  slider.style.transform = `translateX(${currentTranslate}px)`
}
var mySwiper2 = new Swiper ('.swiper-container-2', {
  // Optional parameters
  init: true,
  direction: 'horizontal',
  loop: true,
  preloadImages: true,

  /* THIS PAL RIGHT HERE*/
  slidesPerView: 'auto'
})
```
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.wrapper{
  margin: 20px;
  padding: 25px;
}
ul{
  display: flex;
  list-style: none;
}
ul li{
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 22px;
}
ul li img{
  height: 75px;
  border-radius: 50px;
  border: 5px solid #fff;
  transition: .5s ease;
  -webkit-backface-visibility: hidden;
}
ul li img:hover{
  transform: rotate(-5deg);
}
.slide{

  border-radius: 100%;
  padding: 6px;
  position: center;
}

.title{
  font-family: Futura;
  margin-top: 20px;
  text-decoration: none;
  color: #000;
  font-size: 18px;
  font-weight: 0;
}
.grabbing {
cursor: grabbing;
}

.grabbing .slide img{
transform: scale(0.9);
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Insta Sory UI</title>
    <link rel="stylesheet" href="style.css">

                Test

                Test

                Test

                Test


text:
Q: WalletConnect stops sending requests after a few minutes I am building a wallet app and have successfully managed to set WalletConnect V2 up so that I can pair with a dApp and then respond to requests.  However, after only about 5 minutes I get this error:
Error: Not initialized. subscription

and then all requests stop being sent to my wallet.  I am building this in react-native and have added every listener that I could find in the docs to my web3wallet.  It seems like the dApp may be trying to send the wallet app something and my app is not set up to receive it.  Any guidance in this would be appreciated.
Here is my current web3wallet implementation:
const core = new Core({
   projectId: CONNECT_WALLET_PROJECT_ID
});

const metadata = {
    name: 'Wallet',
    description: 'A Wallet Application',
    url: "#",
    icons: []
};

const web3wallet = await Web3Wallet.init({
      core,
      metadata: metadata
});

 web3wallet.on("session_delete", (proposal) => {
      Alert.alert("session deleted");
      console.log('wc delete: ', proposal);
});

web3wallet.on("session_request", (event) => {
      console.log('session request: ', event);
      console.log('create wallet method worked');
      // const { id, method, params } = event.request;
      setGlobalVariableValue({
         key: 'walletConnectEventData',
         value: {'event': 'session_request', 'data': event}
      });

      navigation.navigate('WalletConnectModal');
});

web3wallet.on("session_update", (proposal) => {
      console.log('session update! ', proposal)
});

web3wallet.on("push_request", (proposal) => {
      console.log("push_request")
      console.log("push_request", proposal)
});

web3wallet.on("push_message", (proposal) => {
      console.log("push_message")
      console.log("push_message: ", proposal)
});

web3wallet.on("push_delete", (proposal) => {
      console.log("push_delete");
      console.log("push_delete: ", proposal)
});

web3wallet.on("session_ping", (proposal) => {
      console.log("session_ping");
      console.log("session_ping: ", proposal)
});

web3wallet.on("session_event", (proposal) => {
      console.log("session_event");
      console.log("session_event: ", proposal)
});

web3wallet.on("pairing_ping", (proposal) => {
      console.log("pairing ping");
      console.log('pairing ping: ', proposal);
});

web3wallet.on("pairing_delete", (proposal) => {
      console.log("pairing delete");
      console.log("pairing delete: ", proposal)
});

web3wallet.on("auth_request", (proposal) => {
      console.log("auth_request")
      console.log("auth request: ", proposal);
});


text:
Q: Set Page Language HTML Attribute I'm trying to figure out how to set the "lang" attribute on the HTML element for a Visualforce page without having to manually add the html element or use Javascript.  I realize that I can set applyHTMLTag="false" and add the element myself, and have also had success with the following jQuery:
jQuery(document).ready(function(){jQuery("html").attr("lang", "en-US");});

However, both options have drawbacks, the former being that it makes the page difficult to include in other pages, and the second that it does not work with javascript turned off.  I was hoping setting the "language" attribute of <apex:page> would also set the page language, but it seems this isn't the case (I'm assuming it's only used to retrieve the internal representation of the page in different languages, however I need the attribute on the page itself to make it more accessible for screen readers).  Is there a way to tell Visualforce the attributes I want on the HTML element in markup or codebehind?

A: html-lang
You can use the HTML pass-through attribute html-lang on apex:page to set the lang attribute on the html element:
<apex:page html-lang="en-US">

A: In the VF page, for  tag add an attribute - applyHtmlTag="false". This simple attribute did the trick.


text:
Q: What's the difference between StaticLayout and DynamicLayout I understand that DynamicLayout is intended for a Layout that has its text being changed, whereas StaticLayout deals with an immutable text.
However, the two classes mostly have the same methods, according to their docs:
http://developer.android.com/reference/android/text/StaticLayout.html
http://developer.android.com/reference/android/text/DynamicLayout.html
Specifically, I don't see a method setText() on the DynamicLayout class.
What is their difference, and how can I use DynamicLayout to calculate layouts where the text ist changing?

A: In order to be updated on text change, DynamicLayout expects Spannable as first parameter. In that case it creates instance of internal static class DynamicLayout.ChangeWatcher, and attaches it to the Spannable. The Spannable, in turn, needs to implement Editable in order to be updated.
Example:
SpannableStringBuilder base = new SpannableStringBuilder("a");
DynamicLayout dynamicLayout = new DynamicLayout(base, base, paint, width, Alignment.ALIGN_NORMAL, 1.0, 0, true);
int firstHeight = dynamicLayout.getHeight();
base.append("\nA");
int secondHeight = dynamicLayout.getHeight();