text:
Q: The underlying provider failed on Open at the time Unity resolve the dependencies I am using an MVC Application that works with Unity to register all the dependencies of my project. I am also using Entity Framework for the DAL.
In my local machine the application is running fine but at the time I deployed on the server I am receiving an error when Unity is trying to resolve the dependencies.
The underlying provider failed on Open. ...  At the time of the exception, the container was: Resolving Class mapped from IClass ... Calling constructor of MyDbContext(System.String connectionName)
1- Does this have a relation with the connection string structure?
Bellow is my connection string
<add name="DBConnection" connectionString="Server=MyServer;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

At this moment I don't have the access to the DB to check if the IIS user has the privileges on the server to run any query, but supposing it doesn't, does this has any relation with the error at the time Unity is trying to resolve the connection string?
2- Does Unity try to open a connection to the DB once it tries to resolve the DBContext?
Here is how I am injecting the parameters
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

container.RegisterType<IUnitOfWork, MyDbContext>(
                Activator.CreateInstance<T>(),
                new InjectionConstructor(connectionString));

A: Your problem is most probably tied to fact that your application pool identity on production doesn't have access to the db. Unity creates instance of all dependent classes once the need arises. So if your Class needs IUnitOfWork, unity tries to instantiate MyDbContext.
Let me point out that you shouldn't register instance of entity context (MyDbContext) as singleton in first place - entity framework context is not thread-safe (Entity Framework Thread Safety), also DI is part of critical infrastructure (there shouldn't be IO calls - such as opening the db that can go wrong)
Instead use something like
public interface IEntityContextProvider {
   public MyDbContext CreateContext();
}
public class EntityContextProvider : IEntityContextProvider  {
   public MyDbContext CreateContext() {
     return new MyDbContext("ef connection string");
   }
}

Usage:
public class SomeClassUsingEF {
  // DI
  private readonly IEntityContextProvider _entityContextProvider;
  // DI
  public SomeClassUsingEF(IEntityContextProvider entityContextProvider)
  {
     if (entityContextProvider == null)
       throw new ArgumentNullException(nameof(entityContextProvider));
     _entityContextProvider = entityContextProvider;
  }

  public void SomeQueryToDB() {
    using(var context = _entityContextProvider.CreateContext()) {
      // select/insert/updates here
    }
  }
}

Also you connection string looks a lot like "ordinary" connection string - i.e. connection string to db wout entity framework - I'm missing the metadata in it. Code wise its usually something like
 private string GetEFConnectionString()
 {
    string providerName = "System.Data.SqlClient";
    string serverName = @".\SQL2008";
    string databaseName = "my-db";

    // Initialize the connection string builder for the
    // underlying provider.
    var sqlBuilder = new SqlConnectionStringBuilder();

    // Set the properties for the data source.
    sqlBuilder.DataSource = serverName;
    sqlBuilder.InitialCatalog = databaseName;
    sqlBuilder.IntegratedSecurity = true;

    // Build the SqlConnection connection string.
    string providerString = sqlBuilder.ToString();

    // Initialize the EntityConnectionStringBuilder.
    var entityBuilder = new EntityConnectionStringBuilder();

    // Set the provider name.
    entityBuilder.Provider = providerName;

    // Set the provider-specific connection string.
    entityBuilder.ProviderConnectionString = providerString;

    // Set the Metadata location.
    entityBuilder.Metadata = @"res://*/Model.csdl|
      res://*/Model.ssdl|
      res://*/Model.msl";
    return entityBuilder.ToString();
}


text:
Q: The visibility of a Text Box is seen in the code view but design view I have a Text Box in my Table in SSRS 2008.
In the Design View, when I check the Visibility -> Hidden property of this Text Box from the Properties window on the right, it is set to: FALSE. The visibility of the column where the Text Box locates is set to: SHOW. There is no grouping for this column/text box.
However, when I go to Code View, I see there is a visibility property is assigned as an expression like below:

When I run the report, the line we see in the code view is working, the table is hiding the Text Box based on the parameter (Filter) value. But somehow we do not see this rule in the design view, we have to specifically look and see from the code view. I could not find why it is happening. Anyone experienced a similar issue? Do I missing something or some area to check in the design view? Any idea would be appreciated.

A: This sometimes happens when design changes or dataset changes are done that the designer can;t handle properly. I had a recent instance where the name of a column in the dataset had changed and I removed a column group at the same time.
I ended up with a property like you have that could not be accessed thru the designer.
I simply deleted TablixMembers group (via the code view) as it had no other data in it (yours is the same) and then applied the hidden expression again via the designer. Everything worked as expected after that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't switch account to my facebook page anymore Before I am able to switch to my facebook page in Messenger Desktop (Windows 11). After I switch to my main account, I can't be able to switch it back to my page.
I hope anyone can help me with this.

A: I had this issue a while ago it lasted around 4 weeks if you have a CRM like Hootsuite you can switch back into your main page through that for the time being until it fixes itself out.


text:
Q: Vaildate 1 field with mutiple options So I have a rails app with a url field for embedding youtube and vimeo videos. Everything works fine but I cannot find a solution to validating both fields but only when one is used.
A user chooses a video url and has a choice of using vimeo or youtube and upon saving I would like to validate that the url code of the video(youtube or vimeo) is correct.
This is what I have
youtube validate code
validates :url ,
:format => {:with => /(https?):\/\/(www.)?(youtube\.com\/watch\?v=|youtu\.be\/)([A-Za-z0-9_-]*)(\&\S+)?.*/}

Vimeo validate code
validates :url ,
:format => {:with => /http:\/\/(www.)?vimeo\.com\/([A-Za-z0-9._%-]*)((\?|#)\S+)?/}

When I have the youtube code I cannot save a vimeo video and vice versa.
Both of the above codes work but only one, how can I have it so both work at the same time?

A: You could mash your regexes together into one big incomprehensible regex or you could use a custom validation method:
validate :youtube_or_vimeo_url

private

def youtube_or_vimeo_url
    return if(self.url =~ /\A(https?):\/\/(www.)?(youtube\.com\/watch\?v=|youtu\.be\/)([A-Za-z0-9_-]*)(\&\S+)?.*/)
    return if(self.url =~ /\Ahttp:\/\/(www.)?vimeo\.com\/([A-Za-z0-9._%-]*)((\?|#)\S+)?/)
    errors.add(:url, 'Bad video URL etc.')
end

You could also separate your two YouTube patterns with this approach and get code that is easier to read.
And while I'm here, if you're using a lot of slashes in your regexes you might want to use %r{} instead:
def youtube_or_vimeo_url
    return if(self.url =~ %r{\A(https?)://(www.)?(youtube\.com/watch\?v=|youtu\.be/)([A-Za-z0-9_-]*)(\&\S+)?.*})
    return if(self.url =~ %r{\Ahttp://(www.)?vimeo\.com/([A-Za-z0-9._%-]*)((\?|#)\S+)?})
    errors.add(:url, 'Bad video URL etc.')
end


text:
Q: Stop launching of call Receive screen and respond by own Activity in android I want to stop launching of call receive screen (default, as usual when call comes) when any incoming call occurs. Instead of that I want to launch my own Activity to respond.

A: first make a subclass of BroadcastReceiver
public class CallReceiver extends BroadcastReceiver {
add it in manifest.xml file
<receiver android:name="com.myapp.calldropper.CallReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>
in onReceive start another Activity Screen upon the default
Intent callRejectIntent = new Intent(context, MainActivity.class);
callRejectIntent.putExtra("MOBILE_NUMBER", mobNum);
callRejectIntent.putExtra("REJECT_COUNT", rejectCount);
callRejectIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callRejectIntent);

your Activity will launch upon the default one. now you can responde the incomming call from your activity, you can Reject call.
for that make a seperate package named com.android.internal.telephony and in this create a simple text file named ITelephony.aidl. this file will contain
package com.android.internal.telephony;
import android.os.Bundle;
interface ITelephony {
    boolean endCall();
    void dial(String number);
    void answerRingingCall();
}

add code below in onCreate
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    try {
        // "cheat" with Java reflection to gain access to TelephonyManager's ITelephony getter
        Class<?> c = Class.forName(tm.getClass().getName());
        Method m = c.getDeclaredMethod("getITelephony");
        m.setAccessible(true);
        telephonyService = (ITelephony) m.invoke(tm);

    } catch (Exception e) {
        e.printStackTrace();
    }

now you can reject the call by calling below function
private void ignoreCall() {
    try {
        // telephonyService.silenceRinger();
        telephonyService.endCall();
    } catch (RemoteException e) {
        e.printStackTrace();
    }
    moveTaskToBack(true);
    finish();
}


text:
Q: How to design a block diagram Hello I was wondering how to do block diagrams in Latex. I am a beginner to the program so I am pretty remedial at it so far. I want to create

just without the bold lines or gray blocks. I am having trouble connecting everything and putting blocks in parallel or series. So far I have only been able to do a very simple one. Can I get some help please, thank you.
     \tikzset{
block/.style={
  draw,
  fill=blue!20,
  rectangle,
  minimum height=3em,
  minimum width=6em
  },
sum/.style={
  draw,
  fill=blue!20,
  circle,
  },
input/.style={coordinate},
output/.style={coordinate},
pinstyle/.style={
  pin edge={to-,thin,black}
  }
}

% The block diagram code is probably more verbose than necessary
\begin{center}

\begin{tikzpicture}[auto,>=latex']
    % We start by placing the blocks
    \node [input, name=input] {};
    \node [sum, right = of input] (sum) {};
    \node [block, right = of sum] (controller) {$K_d$};
    \node [block, right = of controller, pin={[pinstyle]above:$f(t)$},
            node distance=3cm] (system) {$G(s)$};
    % We draw an edge between the controller and system block to
    % calculate the coordinate u. We need it to place the measurement block.
    \draw [->] (controller) -- node[name=u] {} (system);
    \node [output, right =of system] (output) {};
    %\node [block, below of=u] (measurements) {Measurements};

    % Once the nodes are placed, connecting them is easy.
    \draw [draw,->] (input) -- node {$r$} (sum);
    \draw [->] (sum) -- node {} (controller);
    \draw [->] (system) -- node [name=y] {$x$}(output);
    \draw [->] (y) -- ++(0,-2cm) -| node[pos=0.99] {}
        node [near end] {} (sum);
\end{tikzpicture}

A: Here is one way. It uses a chain, and you can change the edge labels on the spot with [el=<label>]. By "upgrading" styles when necessary we can thus avoid having to add all the joins by hand.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta,chains}
\begin{document}

\begin{center}

\begin{tikzpicture}[auto,>=Latex,
    cnode/.style={},
    block/.style={cnode,
      draw,
      fill=blue!20,
      rectangle,
      minimum height=3em,
      minimum width=6em
      },
      tblock/.style={block,minimum width=2em},
    sum/.style={cnode,
      draw,
      fill=blue!20,
      circle,
      },
    input/.style={coordinate,cnode},
    output/.style={coordinate,cnode},
    arj/.style={-Latex,semithick}]
    %
    \begin{scope}[start chain=R going right,
        cnode/.append style={join=by arj,on chain},
        node distance=2.5em,
        arj/.append style={edge label=\pgfkeysvalueof{/tikz/el}},
        el/.initial={}]
     \path node[input]{}
          [el={$r$}]
          node[tblock,alias=Nbar]{$\overline{N}$}
          [el={}]
          node[sum,label=above left:{$+$},label=below right:{$-$}]{}
          [el={$u$}]
          node[tblock,alias=B]{$B$}
          [el={},arj/.append style={very thick}]
          node[sum,label=above left:{$+$},label=below right:{$+$}]{}
          [el={$\dot x$}]
          node[tblock,alias=o]{$1/s$}
          [el={$x$}]
          node[tblock,alias=C,xshift=3em]{$C$}
          [el={$y$}]
          node[output]{};
    \end{scope}
    %
    \begin{scope}[start chain=D going below,
        cnode/.append style={on chain},
        node distance=2.5em]
     \chainin (o);
     \node[tblock,alias=A]{$A$};
     \node[tblock,alias=K]{$K$};
    \end{scope}
    %
    \path (o) -- (C) coordinate[pos=1/3] (oC1) coordinate[pos=2/3] (oC2);
    \draw[arj] (K) -| (R-2);
    \tikzset{arj/.append style={very thick}}
    \draw[arj] (A) -| (R-5);
    \draw[arj] (oC1) |- (A);
    \draw[arj] (oC2) |- (K);
\end{tikzpicture}
\end{center}
\end{document}

A: Another way is:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{arrows.meta,
                chains,
                positioning,
                quotes}

\begin{document}
    \begin{tikzpicture}[
node distance = 4mm and 6mm,
  start chain = going right,
  base/.style = {draw, fill=blue!20},
 block/.style = {base, minimum height=2em, minimum width=3em},
   sum/.style = {base, circle, node contents={}},
   arr/.style = {ultra thick, -{Latex[length=5pt, width=6pt]}},
every edge/.style = {draw, -Latex},
                        ]
% We start by placing the blocks in chain
    \begin{scope}[nodes={on chain}]
\coordinate (in);
\node (n1)  [block]    {$\bar{N}$};
\node (n2)  [sum];
\node (n3)  [block]  {$B$};
\node (n4)  [sum];
\node (n5)  [block]  {$1/s$};
\coordinate (n6);
\coordinate (n7);
\node (n8) [block]     {$C$};
\coordinate (out);
    \end{scope}
%
\path   (in) edge["$r$"]   (n1)
        (n1) edge[near end,"+"] (n2)
        (n2) edge["$u$"]                    (n3)
        (n3) edge[arr,near end,"+"]         (n4)
        (n4) edge[arr,"$\dot{\mathbf{x}}$"] (n5)
        (n5) edge[arr,"$\mathbf{x}$"]       (n8)
        (n8) edge[arr,"$\mathbf{y}$"]       (out);
% Block in backloops
\node (n11)  [block, below=of n5]  {$A$};
\node (n12)  [block, below=of n11] {$K$};
%
\draw[arr]  (n6)  |- (n11);
\draw[arr]  (n11) -| (n4) node[below right] {$+$};
\draw[arr]  (n7)  |- (n12);
\draw[-Latex]  (n12) -| (n2) node[below right] {$-$};
\end{tikzpicture}
\end{document}

A: Here is a proposal using the block diagram package on the ctan.
https://ctan.org/pkg/schemabloc
\documentclass{article}
\usepackage{schemabloc}

\begin{document}

\begin{tikzpicture}

\sbEntree{E}
\sbBlocL{B1}{$\overline{N}$}{E}
    \sbRelier[$r$]{E}{B1}
\sbComp*{C1}{B1}
    \sbRelier{B1}{C1}
\sbStyleBloc{blue,very thick,fill=yellow,text=red}%
\sbBloc{B2}{$B$}{C1}
    \sbRelier[$u$]{C1}{B2}
\sbSumb*{C2}{B2}
    \sbRelier{B2}{C2}
\sbBloc{B3}{$\frac{1}{s}$}{C2}
    \sbRelier[$\dot{x}$]{C2}{B3}
\sbBloc[6]{B4}{$C$}{B3}
    \sbRelier[$x$]{B3}{B4}
\sbSortie[4]{Y}{B4}

\sbStyleBloc{very thick,fill=green,text=blue}%
    \sbRelier[$y$]{B4}{Y}
    \sbDecaleNoeudy{B3}{R3}
\sbStyleLien{ultra thick, red}
    \sbBlocr[-1.5]{R3}{$A$}{R3}
        \sbRelieryx{B3-B4}{R3}
        \sbRelierxy{R3}{C2}
    \sbDecaleNoeudy[9]{B3}{R4}
    \sbBlocr[-1.5]{R4}{$K$}{R4}
        \sbRelieryx{B3-B4}{R4}
        \sbRelierxy{R4}{C1}
\end{tikzpicture}


text:
Q: save data like session and cache in asp mvc as you all know we simply use
Session["kurd"]="";

or
Cahce.Insert(...)
and its save data in memory;
its save data without serialize or any thing like that so we can simply save everything
but its not reliable way to save data;

so may you guys say you can save on database or file but in my case
  it  cant be done, because my data its not serializable,  and i can
  only save it in cache , session , viewdata,viewbage
  ,... because it dos not need to be serialize data first ; and because
  of not reliability in session , cache ,... i want way that can save
  data just like cache and session ,... without serialize data

anyone knows how we can do such thing (save data) in disk
i mean save data on hard drive just like session did on memory?
update :
the data type is instance of that class in picture that contain httpclient , httpclienthandeler,deviceinfo,...

update :
how wonderful it is that no one knows
how can i save data in hard drive just like what session did in memory
no question no serialize no bs, just save it very easy

A: Programmatically you can use ObjectDumper.
Or, if you are debugging, you can use a Visual Studio extension called Object Exporter

A: i solved this problem
HttpClient cant be serialize but
i found out that the only thing in HttpClient that we should save in this thread
is "CookieContainer"
so serlize and deserilze like this
var formatter = new SoapFormatter();
string file = "..\cookies.dat";
//
using (Stream s = File.Create (file))
    formatter.Serialize(s, cookies);
//
CookieContainer retrievedCookies = null;
using (Stream s = File.OpenRead (file))
    retrievedCookies = (CookieContainer) formatter.Deserialize(s);

so i serialize it and save it and then for new use i create new HttpClient and assign that CookieContainer to HttpClent.CookieContainer
this problem was for Instasharper


text:
Q: A circle being drawn when hover over div I've looked for this question, I found some answers but it's not really what I need.
I'm not really experienced with jquery, but I already made the hover function! When I hover over the div, it will resize.
What I want to add to this effect is: on the same hover, a circle will be drawn around an image.
I've already seen answers where people add a box-radius. But what I'm looking for is that you actually see the circle being drawn.
An example at 0:49 seconds (its a bit random but this video shows the effect I need):
http://www.youtube.com/watch?feature=player_detailpage&v=jCdNnaTzItM#t=45s
I hope this is possible!
my code:
$('li#balk1').hover(
    function(){ $(".ad").css('transform', 'scale(1.2)'); },
    function(){ $(".ad").css('transform', 'scale(1)'); }
);

There should be a circle around ".ad"

A: Alright, it turns out you can do this, I've thrown up a fiddle modifying this solution. I believe it relies on the use of the tween and curve plugins, which are explained in more detail in the second link.

A: Checkout this Codepen (link) or it's also available as a gist (link)
Using a SVG stroke attributes we animate an SVG line generated with a rand calculated imperfect bezier curve.  I think this should be pretty close what you were looking for.
jQuery and D3 dependencies
<style>
path.ln {
    stroke-width: 2px;
    stroke: #999;
    fill: none;
    vector-effect: non-scaling-stroke;
    stroke-dasharray: 1000;
    stroke-dashoffset: 1000;
    -webkit-animation: dash 4s cubic-bezier(0.45,0.3,0.35,0.3);
    -moz-animation:dash 4s cubic-bezier(0.45,0.3,0.35,0.3);
    -o-animation:dash 4s cubic-bezier(0.45,0.3,0.35,0.3);
    animation:dash 4s cubic-bezier(0.45,0.3,0.35,0.3);
}

@keyframes dash {
    to { stroke-dashoffset: 0; }
}
</style>

<script>
function path(min_rad_delta,max_rad_delta, el_min, el_max, el_min_delta,el_max_delta) {
    var d = Math.sqrt( 0.5 * 0.5 + 1 * 1 ), r = 1; //returns the square root of a number
    var el = (el_min + Math.random() * (el_max - el_min)) * Math.PI / 180;
    var path = 'M' + [r * Math.sin(el), r * Math.cos(el)] + ' C' + [d * r * Math.sin(el + Math.LN2), d * r * Math.cos(el + Math.LOG10E)];

    for (var i = 0; i < 4; i++) {
        el += Math.PI / 2 * (1 + el_min_delta + Math.random() * (el_max_delta - el_min_delta));
        r *= (1 + min_rad_delta + Math.random()*(max_rad_delta - min_rad_delta));
        path += ' ' + (i?'S':'') + [d * r * Math.sin(el - 0.45), d * r * Math.cos(el - 0.45)];
        path += ' ' + [r * Math.sin(el), r * Math.cos(el)];
    }
    return path;
}

function cX(lambda_min, lambda_max, el_min, el_max) {
    var el = (el_min + Math.random()*(el_max - el_min));
    return 'rotate(' + el + ') ' + 'scale(1, ' + (lambda_min + Math.random()*(lambda_max - lambda_min)) + ')'+ 'rotate(' + (-el) + ')';
}
</script>

<svg id="circle" width="50%" height="75%" viewBox='-1.5 -1.5 3 3'></svg>

<script>
d3.selectAll( 'svg' )
    .append( 'path' )
    .classed( 'ln', true)
    .attr( 'd', path(-0.1,0, 0,360, 0,0.2 ))
    .attr( 'transform', cX( 0.6, 0.8, 0, 360 ));
setTimeout(function() { location = '' } ,5000)
</script>


text:
Q: Call to function "merge" failed: arguments must be maps or objects, got "tuple" I'm getting the below error which I'd appreciate some help with. I'm trying to add a bolt-on to a terraform public module to apply a best practice set of options in addition to any passed to the module in the usual way. What's the correct way of doing this please as I'm not certain that nesting my lookup function within a merge is valid.
terraform version = 1.1.12
provider version = hashicorp/aws 2.49

error message

│ Error: Error in function call
│
│   on ../modules/db_option_group/main.tf line 5, in locals:
│    5:   merged_options = merge(var.mysql_standard_options,var.options)
│     ├────────────────
│     │ var.mysql_standard_options is tuple with 1 element
│     │ var.options is empty tuple
│
│ Call to function "merge" failed: arguments must be maps or objects, got "tuple".

main.tf snippet

locals {
  name        = var.use_name_prefix ? null : var.name
  name_prefix = var.use_name_prefix ? "${var.name}-" : null
  merged_options = merge(lookup(var.option_group_map,var.engine_name),var.options) # error caused here
  description = coalesce(var.option_group_description, format("%s option group", var.name))
}

resource "aws_db_option_group" "this" {
  count = var.create ? 1 : 0

  name                     = local.name
  name_prefix              = local.name_prefix
  option_group_description = local.description
  engine_name              = var.engine_name
  major_engine_version     = var.major_engine_version

  dynamic "option" {
    # for_each = var.options
    for_each = local.merged_options
    content {
      option_name                    = option.value.option_name
      port                           = lookup(option.value, "port", null)
      version                        = lookup(option.value, "version", null)
      db_security_group_memberships  = lookup(option.value, "db_security_group_memberships", null)
      vpc_security_group_memberships = lookup(option.value, "vpc_security_group_memberships", null)

      dynamic "option_settings" {
        for_each = lookup(option.value, "option_settings", [])
        content {
          name  = lookup(option_settings.value, "name", null)
          value = lookup(option_settings.value, "value", null)
        }
      }
    }
  }

variables.tf snippet

variable "options" {
  description = "A list of Options to apply"
  type        = any
  default     = []
}

variable "option_group_map" {
  type = map
  default = {
    "mysql" = "var.mysql_standard_options"
    "mariadb" = "var.mysql_standard_options"
    "sqlserver-ee" = "var.sqlserver_standard_options"
    "sqlserver-ex" = "var.sqlserver_standard_options"
    "sqlserver-se" = "var.sqlserver_standard_options"
    "sqlserver-web" = "var.sqlserver_standard_options"
    "oracle-ee" = "var.oracle_standard_options"
    "oracle-se2" = "var.oracle_standard_options"
  }
}

variable "mysql_standard_options" {
  description = "A list of DB options to apply for MySQL instances"
  type        = any
  default     = [
                   {
                      # For auditing of connection attempts.
                      option_name = "MARIADB_AUDIT_PLUGIN"

                      option_settings = [
                         {
                            name = "SERVER_AUDIT_EVENTS"
                            value = "CONNECT,QUERY_DDL"
                         },
                         {
                            name = "SERVER_AUDIT_FILE_ROTATIONS"
                            value = "35"
                         }
                      ]
                   }
               ]
}
...
...
...

** --UPDATE 1-- **
I changed the brackets used from square brackets used for lists/tuples to curly braces in my variable definitions like so:

variable "options" {
  description = "A list of Options to apply"
  type        = any
  default     = {}
}

variable "option_group_map" {
  type = map
  default = {
    "mysql" = "var.mysql_standard_options"
    "mariadb" = "var.mysql_standard_options"
    "sqlserver-ee" = "var.sqlserver_standard_options"
    "sqlserver-ex" = "var.sqlserver_standard_options"
    "sqlserver-se" = "var.sqlserver_standard_options"
    "sqlserver-web" = "var.sqlserver_standard_options"
    "oracle-ee" = "var.oracle_standard_options"
    "oracle-se2" = "var.oracle_standard_options"
  }
}

variable "mysql_standard_options" {
  description = "A list of DB options to apply for MySQL instances"
  type        = any
  default     = {
                   option1 = {
                      # For auditing of connection attempts.
                      option_name = "MARIADB_AUDIT_PLUGIN"

                      option_settings = {
                         option_setting_1a = {
                            name = "SERVER_AUDIT_EVENTS"
                            value = "CONNECT,QUERY_DDL"
                         },
                         option_setting_1b = {
                            name = "SERVER_AUDIT_FILE_ROTATIONS"
                            value = "35"
                         }
                      }
                   },
               }
}

But still look to be getting issues with both variables passed to the merge function. Am now thinking maybe I need a for loop for this.

│ Error: Error in function call
│
│   on ../modules/db_option_group/main.tf line 4, in locals:
│    4:   merged_options = merge(lookup(var.option_group_map,var.engine_name),var.options)
│     ├────────────────
│     │ var.engine_name is "mysql"
│     │ var.option_group_map is map of string with 8 elements
│     │ var.options is empty tuple
│
│ Call to function "merge" failed: arguments must be maps or objects, got "string".

** --UPDATE 2-- **
If I add the "..." onto the end of the variable within the merge and remove the lookup it looks better I just need to work out a way to conditionally use a different variable depending upon the engine type.

-- from main.tf
  #merged_options = merge(lookup(var.option_group_map,var.engine_name),var.options...)
merged_options = merge(var.mysql_standard_options,var.options...)

** --UPDATE 3-- **
Ok think I've sorted now by splitting up the option group blocks per engine type and amending the count type rather than doing a lookup

locals {
  name        = var.use_name_prefix ? null : var.name
  name_prefix = var.use_name_prefix ? "${var.name}-" : null
  merged_mysql_options = merge(var.mysql_standard_options,var.options...)
  merged_postgres_options = merge(var.mysql_standard_options,var.options...)
  merged_sqlserver_options = merge(var.mysql_standard_options,var.options...)
  merged_oracle_options = merge(var.mysql_standard_options,var.options...)
  description = coalesce(var.option_group_description, format("%s option group", var.name))
  mysql_option = length(regexall(".*mysql*", var.engine_name)) > 0
  postgres_option = length(regexall(".*postgres*", var.engine_name)) > 0
  sqlserver_option = length(regexall(".*sqlserver*", var.engine_name)) > 0
  oracle_option = length(regexall(".*oracle*", var.engine_name)) > 0
}

resource "aws_db_option_group" "mysql" {
  count = var.create && local.mysql_option ? 1 : 0

  name                     = local.name
  name_prefix              = local.name_prefix
  option_group_description = local.description
  engine_name              = var.engine_name
  major_engine_version     = var.major_engine_version

  dynamic "option" {
    # for_each = var.options
    for_each = local.merged_mysql_options
    content {
      option_name                    = option.value.option_name
      port                           = lookup(option.value, "port", null)
      version                        = lookup(option.value, "version", null)
      db_security_group_memberships  = lookup(option.value, "db_security_group_memberships", null)
      vpc_security_group_memberships = lookup(option.value, "vpc_security_group_memberships", null)

      dynamic "option_settings" {
        for_each = lookup(option.value, "option_settings", [])
        content {
          name  = lookup(option_settings.value, "name", null)
          value = lookup(option_settings.value, "value", null)
        }
      }
    }
  }

  tags = merge(
    var.tags,
    {
      "Name" = var.name
    },
  )

  timeouts {
    delete = lookup(var.timeouts, "delete", null)
  }

  lifecycle {
    create_before_destroy = true
  }
}


text:
Q: Appending a dict to Dataframe from CSV is removing the values I'm trying to append some values to a CSV file using pandas. The problem is that when I read the CSV and append, the rows that previously was in the CSV are changed to NaN.
I read the file and printed every step to understand what happened, but I coudn't.
import pandas as pd
try:
    erro = pd.read_csv('C:\\TESTEPANDAS\\errot.csv', index_col=0,header=0)
except:
    erro = pd.DataFrame({'id':[],'cnj':[],'erro':[]})
print(erro)
erro.to_csv('C:\\TESTEPANDAS\\errot.csv',sep=';',index=False)

for i in range(5):
    erro = erro.append({'id':'id{}'.format(i),'cnj':'cnj{}'.format(i),'erro':'errotxt{}'.format(i)},ignore_index=True)

print(erro)
erro.to_csv('C:\\TESTEPANDAS\\errot.csv',sep=';',index=False)

When I try once, this is the result:
Empty DataFrame
Columns: [id, cnj, erro]
Index: []
    id   cnj      erro
0  id0  cnj0  errotxt0
1  id1  cnj1  errotxt1
2  id2  cnj2  errotxt2
3  id3  cnj3  errotxt3
4  id4  cnj4  errotxt4

If I try again:
Empty DataFrame
Columns: []
Index: [id0;cnj0;errotxt0, id1;cnj1;errotxt1, id2;cnj2;errotxt2, id3;cnj3;errotxt3, id4;cnj4;errotxt4]
    cnj      erro   id
0   NaN       NaN  NaN
1   NaN       NaN  NaN
2   NaN       NaN  NaN
3   NaN       NaN  NaN
4   NaN       NaN  NaN
5  cnj0  errotxt0  id0
6  cnj1  errotxt1  id1
7  cnj2  errotxt2  id2
8  cnj3  errotxt3  id3
9  cnj4  errotxt4  id4

A: The parameters for writing and reading the csv don't match. Look at the index of the second output - reading back the csv failed, as the separator wasn't given:
Index: [id0;cnj0;errotxt0, id1;cnj1;errotxt1...

The reading command should be:
erro = pd.read_csv('C:\\TESTEPANDAS\\errot.csv', sep=";")

Then you get back the same object that you saved in the previous iteration.


text:
Q: Java JAIN SIP Presence I am currently writing an application in java using the the JAIN SIP library, I've been trying for the past couple of days to implement presence using SUBSCRIBE and NOTIFY messages. I currently have NOTIFY messages which has a content type of "message/sipfrag;version=2.0", and need this to be XML and PIDF.
I'm aware I need to use an event header with "presence", and also a content type header.
Are there any places I can go to where there is information on this or are there any other specific headers or classes and/or methods needed to make this work? I already have a client which I can make calls on, but need to implement presence now.

A: FYI, rfc3863 only defines the basic structure/semantics of a presence document.  PIDF establishes a rudimentary presence document to be a status - with optional contact info, and other info (defined per the PIDF schema).  PIDF does not really prescribe presence protocol.  For those you need to review [RFC3265][1] and the details of the presence event package [RFC3856][2].  If we stick to a non-IMS network, the usual call-flow involves:

*

*SIP registration to the SIP/REGISTRAR user-agent-server (UAS) accessible to the client.  This also establishes the presence-entities (presentity) AoR (Address of Record) - who you are and how you can be reached - i.e. assuming you want to be contacted.

*SIP:PUBLISH - with 3 very key parts.  Firstly, an 'Event' header indicating support for the presence package, the content-type appropriately set to PIDF MIME-type and the correct body.
PUBLISH sip:bob@example.org SIP/2.0
...
Event: presence
Content-type: application/pidf+xml
Content-length: xyz

open

Once you have successfully published, you can then try a SUBSCRIBE method - to try and obtain status of another presence entity (e.g. user jane@example.org).  For a SIP SUBSCRIBE the minimal is defining an appropriate presentities SIP/URI and specifying the correct 'event-package'.  Look closely at the indicated RFCs - 3265 / 3856 will help guide you on basic behavior.
Best of luck.
[1]: https://www.rfc-editor.org/rfc/rfc3265#section-4
[2]: https://www.rfc-editor.org/rfc/rfc3856#section-5

A: There is more than one way to do presence in SIP. If you are sure PIDF is used then you should just use the RFC as reference https://www.ietf.org/rfc/rfc3863.txt. JSIP will work just fine as far as the SIP headers go, it will construct and parse the SIP messages correctly. The actual SIP message content parsing/construction is responsibility of the app. Jitsi is an open source client that has presence if you want to peek at some example code, but it may be totally different from your case.


text:
Q: Use logging in Bash script I have a bash script from which i need to write logs. currently i use block like the one below
#log stop request
            {
                local now=$(date +"%a %b %d %Y %H:%M:%S")

                printf "batch stop request successful. \n"
                printf "      Time            :: %s\n" "$now"
                printf "      PID of process  :: %s\n" ${PID[0]}"
            } >> "${mylogfile}"

where mylogfile variable will have name of the logfile.
The problem with this approach is that when 2 or more instances are running, the logs tends to get messed up with writes from instances coming interleaved.
Please note i used the block thinking that it would result in the log being written to file in one go, thus avoiding the problem.
I have seen logger command from Vivek Gite post. but the problem is it does not write to a file I can specify, rather does so to /var/log/message.
Any help is much appreciated.
Thanks and Regards
Sibi

A: POSIX (IEEE Std 1003.1-2001) does not define the behavior of concurrent write() syscalls sending data to the same file, hence you may obtain different results depending on your platform. You can try to merge all printfs into one in the hope that this will work, but even if it does there is no guarantee that it will in the future or on a different platform.
Rather than using concurrency control and flushing to ensure the writes are sequenced, you can send the messages to a third process which will write your log messages sequentially to a file on behalf on all the processes. In fact, this is what is done with logger and syslog in the post you cited. The logger command does not send the messages to /var/log/messages. It sends the log messages to syslog which can be configured to save the log messages anywhere you like. Changing this configuration usually requires administrative privileges, though.
If you can't or don't want to use syslog, you can also use netcat as a logging server. Run this to multiplex all incoming log messages from all scripts into the file (this job should remain running in the background all the time, you can also run it in a screen):
nc -luk localhost 9876 > shared_log_file &

(port 9876 is just an example) and log in each script this way:
printf "Log message\n" > /dev/udp/localhost/9876

You can also use a custom UDP server instead of netcat (e.g. like this one).

A: The block does not group the printfs in any way, as you have discovered.  What you could do, however, is do all of those commands in a sub-shell (between parenthesis) and then redirect the sub-shell's output!

A: Trying putting the 3 printfs as one string, i.e.
printf "Epsilon batch stop request successful. \n      Time            :: %s\n     PID of process  :: %s\n" "$now"  ${PID[0]}

You may still get interleaving.
Why not start each instance with its own log file, using the ${PID} on your logfile name to keep them separate? i.e.
 >> "${mylogfile}.${PID}"

Edit
As you're hoping for logger, check out the man page :
logger(1) - Linux man page

Name

logger - a shell command interface to the syslog(3) system log module

Synopsis
logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

Description

Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

Options:

    -i'         Log the process id of the logger process with each line.
    -s' Log the message to standard error, as well as the system log.
    -f file
        Log the specified file.

.....

That looks like what you want.
I hope this helps.

A: Depending on the nature of your logging, it might be well-suited for the system log instead of its private logfile. In this case, the logger program could be a very good alternative to hand-rolled logging.


text:
Q: Using config driven logic in createCriteria grails I have requirement in which i need some logic of criteria query to be config driven. Earlier i used to query like :
e.g.:
User.createCriteria().list{
     or{
        eq('username',user.username)
        eq('name',user.name)
     }
}

But, i need this to be configurable in my use case so, i try this code snippet.
def criteriaCondition= grailsApplication.config.criteriaCondition?:{user->
         or{
           eq('username',user.username)
           eq('name',user.name)
         }
}

User.createCriteria().list{criteriaCondition(user)}

But, This doesn't work for me. I am getting missing method exception for "or" I tried few solution from some sources but it didn't worked for me.
So, can anyone help me :
1) How to make the above given code work.
2) Any other better way for my use case.
Thanks in advance!!!

A: you have to pass criteriaBuilder object to the closure, something like this:
def criteriaCondition = grailsApplication.config.criteriaCondition ?: { cb, user ->
     cb.or{
       cb.eq('username',user.username)
       cb.eq('name',user.name)
     }
}

def criteriaBuilder = User.createCriteria()

criteriaBuilder.list{
    criteriaCondition(criteriaBuilder, user)
}

obviously, closure in the Config.groovy also has to have the same parameters list, including cb

A: The way the criteria builder mechanism works, the list method expects to be passed a closure which it will call, whereas your current code is calling the criteriaCondition closure itself rather than letting the criteria builder call it.  "Currying" will help you here: given
def criteriaCondition= grailsApplication.config.criteriaCondition?:{user->
         or{
           eq('username',user.username)
           eq('name',user.name)
         }
}

instead of saying
User.createCriteria().list{criteriaCondition(user)}

you say
User.createCriteria().list(criteriaCondition.curry(user))

(note the round brackets rather than braces).
The curry method of Closure returns you another Closure with some or all of its arguments "pre-bound" to specific values.  For example
def add = {a, b -> a + b}
def twoPlus = add.curry(2) // gives a closure equivalent to {b -> 2 + b}
println twoPlus(3) // prints 5

In your case, criteriaCondition.curry(user) gives you a zero-argument closure that you can pass to criteria.list.  You can curry as many arguments as you like (up to the number that the closure can accept).


text:
Q: $_SERVER not returning query string I'm simply trying to store the current page a user is viewing in a DB. When the page loads, I insert $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'] into my DB, but only the page (e.g. index.php?) is showing up, without the query string (I have verified that there IS a query string in the URL).
I tried $_SERVER['PHP_SELF'] with the same results.
EDIT TO ADD:
Here is the dump of $_SERVER:
Array
(
    . . .
    [REQUEST_METHOD] => GET
    [QUERY_STRING] => view=scores&yr=2010&wk=1
    [REQUEST_URI] => /index.php?view=scores&yr=2010&wk=1
    . . .
)

So the query string is present in the array, even as part of REQUEST_URI. So my query...
mysql_query("insert into clickstream
               (user_id, page)
             values
               (" . $_SESSION['user_id'] . ", '" . mysql_real_escape_string($_SERVER['REQUEST_URI']) . mysql_real_escape_string($_SERVER['QUERY_STRING']) . "');")
  or die('mysql error: ' . mysql_error());

...should actually insert the query string twice, instead of no times!
Thoughts?
ADDED THOUGHT: Is it possible the MySQL DB strips everything from the input beyond the ?? The field is varchar.
UPDATE W/ PARTIAL SOLUTION: Changing the SQL input to just $_SERVER['QUERY_STRING'] (without REQUEST_URI) successfully input the query string. Thus, it leads me to believe that either PHP or MySQL was stripping everything from the input string after the ?. So the input params were correct; the result just got truncated.
Does anyone know why this might be the case?

A: Different servers pass different $_SERVER globals to the page. I assume you are using Apache rather than NGINX where you might have to check that QUERY_STRING is defined in FASTCGI_PARAMS.
The solution is to to do like @hakre says and just see which $_SERVER key has what you want.
<?php
print '<pre>';
print_r($_SERVER);
print '</pre>';

A: Couldn't you just use $_SERVER['REQUEST_URI'] ? It has the query string as part of the output...

A: Thanks for the feedback, particularly @nachito. The problem has been isolated to MySQL, not PHP. The output from PHP is correct, but MySQL is stripping everything from the URL after ? upon insertion into the database.

A: Can you show us the definition of the table clickstream ?
If the page column were only 10 chars long, then we have spotted the problem :)
'index.php?' (10 chars)
To see the table structure you can issue this MySQL command:
SHOW CREATE TABLE clickstream;


text:
Q: How can inflate view personalized addmarker? gmaps The other day I asked, as fill from a cursor. I got on top of that focus all brands with the maximum zoom.
But now I have a problem and fill in the custom view, where there is title, description, and latitude and longitude.
It takes me head, I'm trying to look as filling sight, but each does so in a way. I am not able.
Here my code
info_windows_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#ffffff" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Esto es un titulo"
        android:id="@+id/tv_title"
        android:textStyle="bold"
        android:textSize="20dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="tv_descripcion"
        android:id="@+id/tv_descripcion"
        android:textSize="16dp" />

    <TextView
        android:id="@+id/tv_lat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="lat" />

    <TextView
        android:id="@+id/tv_lng"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="lang" />

</LinearLayout>

CajerosMaps
    public class CajerosMaps extends FragmentActivity implements OnMapReadyCallback {

        private GoogleMap mMap;
        Cursor cursor;
        MiCajeroOperacional mb;
        LatLngBounds.Builder builder;
        CameraUpdate cu;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_cajeros_maps);
            mb = MiCajeroOperacional.getInstance(getApplicationContext());
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            cursor = mb.listar();
            mMap = googleMap;
            LatLng mark = null;

            List<Marker> markersList = new ArrayList<Marker>();

    int i = 0;
        while (cursor.moveToNext()) {
            double lat = cursor.getDouble(cursor.getColumnIndex("lat"));
            double lng = cursor.getDouble(cursor.getColumnIndex("lng"));
            mark = new LatLng(lat, lng);
            Marker markCajero = mMap.addMarker(new MarkerOptions().position(mark).title("Sucursal Nº" + i).snippet(cursor.getString(cursor.getColumnIndex("direccion"))));
            // mMap.moveCamera(CameraUpdateFactory.newLatLng(mark), 15);
            markersList.add(markCajero);
            i++;
        }
        cursor.close();
        builder = new LatLngBounds.Builder();
        for (Marker m : markersList) {
            builder.include(m.getPosition());
        }
        int padding = 50;
        LatLngBounds bounds = builder.build();
        cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
        mMap.moveCamera(cu);
    }
}


text:
Q: Android - Statistics on OS Versions I have to know how many users are currently using my mobile app(production) in Android OS 4.1 and 4.2
how can i know from google play console.?

A: You can view the breakdown of users of your app by android version in the Statistics tab in the play developer console. On that page, scroll down below the graph to see how many users are on each version.

These statistics won't differentiate between build variants, but if you discount the number of developers/testers who are using your non-production variants, you can get a good idea of the production usage on different versions.


text:
Q: How do you execute a ./executable in Python? I have an executable that is a result of compiling and running a C program.
Let's Call it "file1".
Normally, this is how I'd execute it in Linux.
./file1

But now, I need to execute it from within Python.
I've tried
os.system("./file1")

-to no avail. Can someone please help me out?
P.S - Apologies for the bizzare spacing.

A: Use the subprocess module
>>> import subprocess
>>> subprocess.call(['./file1'])


text:
Q: SSIS package merge conflict resolved but causing etl Package load failure I was trying to merge two git branches and encountered Merge conflict error.
I tried to resolve them and saved it. But now the whole package is unable to load.
The error shown is " An item with the same key is already added"
The error msg is as below. I am unable to find out where exactly I should make the change.
Could anyone help me to resolve it?
Please let me know if I need to add more info for the troubleshooting to be easier.
   at Microsoft.SqlServer.Dts.Runtime.Project.OpenProject(IProjectStorage storage, String projectPassword, IDTSEvents events)
   at Microsoft.DataTransformationServices.Project.DataTransformationsProjectLoader.<>c__DisplayClass21_0.<LoadProject>b__0(String password, IDTSEvents events)
   at Microsoft.DataTransformationServices.Controls.ProjectProtectionUtils.LoadProjectWithPassword(Boolean askedPasswordOnce, ProjectLoader loader, IWin32Window dialogParent, String& password, ProjectProtectionEvents errorListener)
   at Microsoft.DataTransformationServices.Project.DataTransformationsProjectLoader.LoadProject(XmlNode manifestNode, String& projectPassword, ProjectProtectionEvents errorListener)
   at Microsoft.DataTransformationServices.Project.DataTransformationsProjectLoader.DeserializeManifestInProjectMode(XmlNode manifestNode)
   at Microsoft.DataTransformationServices.Project.DataTransformationsProjectLoader.ConstructProjectHierarchyFrom(ProjectSerialization projectSerialization)
   at Microsoft.DataTransformationServices.Project.DataTransformationsProjectLoader.Deserialize(TextReader reader)
   at Microsoft.DataWarehouse.VsIntegration.Shell.Project.Serialization.BaseProjectLoader.Load(IFileProjectHierarchy projectHierarchy)
   at Microsoft.DataWarehouse.VsIntegration.Shell.Project.FileProjectHierarchy.Load(String pszFilename, UInt32 grfMode, Int32 iReadOnly)

A: An SSIS package is an XML based file format.
Yes, you should absolutely use source control to version your packages. But you would be best off treating them as binaries because no source tool I am aware of knows how to merge XML documents.
The error you're experiencing is that you have an invalid package declaration. Without seeing the two files and the merge record, it's super hard to guess what's been done, much less rectify it.
SSIS Source Control guidance
After doing SSIS for nearly 20 years, I have a few thoughts on the matter.

*

*Design your packages to be as small and tightly focused on solving a single business problem (Populate Sales table from Excel)

*Use package orchestration to solve the dependent package problem (Run the Employee Package, then Customer, then Sales)

*Only one developer works on a package at a time. Decompose the package into smaller packages if the business problem supports it to get more developers working on a task

*If adding new packages to a project/solution, have a captain/leader create empty/shell packages and commit the project to source control - because the SSDT project artifacts are also XML and subject to the same botched merge logic.


text:
Q: Uploading files in a python WSGI app using AJAX and JQuery I am trying to create a WSGI app with python3 and JQuery.  I am almost there, but I can't seem to figure out how to upload a file (.txt) with an AJAX request.  This is as far as I've gotten, having consumed as much reading on the topic as I could locate.  My project directory looks like:
/chimera_quest
    view.py
    model.py
/static
    main.css
    main.js
/tmp
/templates
    main.html
WSGI_app.py

I have a form in my HTML with two radio buttons and a file upload.

Select an input file-type

<form id="user_input" name="user_input" method="post">

<input name="input_type" type="radio" value="coord" checked>Tab-delimited coordinate file</input>

<input name="input_type" type="radio" value="fcatcher">Fusion Catcher</input>

<input name="input_type" type="radio" value="tophat">Tophat</input>

<input name="input_type" type="radio" value="tophat-post">Tophat-post</input>

<input name="input_type" type="radio" value="rnastar">RNA-Star</input>

<input name="input_type" type="radio" value="fcatcher">Fusion Catcher</input>

<input name="input_type" type="radio" value="starfusion">Star Fusion</input>

Select a tissue type

<input name="tissue_type" type="radio" value="EPI">Epithelial</input>

<input name="tissue_type" type="radio" value="HEM">Hematopoietic</input>

<input name="tissue_type" type="radio" value="MES">Mesenchymal</input>

<input name="tissue_type" type="radio" value="AVG" checked>Other/Unknown</input>

Select a file to upload

<input type="file" id="input_file" name="input_file">
<input type="submit" class="submit" id="run_oncofuse" value="Run Oncofuse">
</form>

This is the Javascript/JQuery snip that I want to handle the AJAXy bit.
var fd = new FormData();
var user_input = $('#user_input').serialize();
var file_data = $('#input_file')[0].files[0];
fd.append( 'input_file', $( file_data ));

$.ajax({
  url: "../chimera_quest/view.py?" + user_input,
  data: fd,
  type: "POST",
  dataType: "json",
  processData: false,
  contentType: 'multipart/form-data',
  success: function(results, textStatus, jqXHR) {
      console.log(fd)
      console.log(results)
      console.log(file_data)
// do stuff with results
    }

I rigged the model script to send results without user input for testing.  The JSON blob is transferred correctly and the site behaves accordingly.  My browser's javascript console is correctly logging results and file_data does show information about the file I am attempting to upload.  I can not seem to find the file_data object within the FormData object (fd) in my console, but I assume that is because I don't know where to look.
This is the part of the view.py script that should receive the user input:
if environ['REQUEST_METHOD'] == 'POST':
    try:
        Q_S = cgi.parse_qs(environ['QUERY_STRING'])
        input_type = Q_S.get('input_type', [''])[0]
        tissue_type = Q_S.get('tissue_type', [''])[0]

        post_env = environ.copy()
        post_env['QUERY_STRING'] = ''
        post = cgi.FieldStorage(
            fp=environ['wsgi.input'],
            environ=post_env,
            keep_blank_values=True
        )
        input_file = post['input_file']

    except (TypeError, ValueError):
        request_body = "0"

I am getting the user input from the radio buttons from the url with no problem, I just can't seem to access the uploaded file in the POST request.  I've tried rewriting this as many ways as I could think of or find an example. I think the problem is either in creating the FormData object in the JavaScript or creating/accessing the FieldStorage object in the python, but I can't seem to nail this one down.
Any ideas?


text:
Q: Why I can get a instance of an class that is not referenced in this assembly? Background:
We have three assemblies:

*

*printing (Generates reports as pdfs)
-> Reference to businessObjects.interfaces

*businessObjects (contains all of our business objects) -> Reference to
businessObjects.interfaces

*businessObjects.interfaces (Here we declare the properties for the printing,
only properties that are needed are included)
-> No references
The object is implemented like this:
public interface IDeliveryNote // Assembly: businessObjects.interfaces
public partial class DeliveryNote : IDeliveryNote // Assembly:businessObjects
There is also a class 'Order' inside the DeliveryNote, holding a bool 'IsNeutralDelivery'
Problem:
Some report(DeliveryNoterReport) was buggy and we needed to include an existing property (IsNeutralDelivery) from the businessObjects.DeliveryNote.Order - object.
Actually we cant rollout the application (Dont ask :))
While debugging I noticed that from
IDeliveryNote dn = ((IDeliveryNote)this.DataSource);

i can access also the Order and the needed property (IsNeutralDelivery)
maybe just fancy visual studio magic, so i tried to get the property with reflection like this:
bool neutralDeliveryAddressIsNeutralDelivery = (bool)dn.GetType().GetProperty("Order").GetValue(dn).GetType().GetProperty("IsNeutralDelivery").GetValue(dn.GetType().GetProperty("Order").GetValue(dn));

And yes, I retrieved the value and with that I could fix the bug (Only replace the printing.dll)
Question:
Why I can get a instance of the DeliveryNote object when i got no references to the assembly that it belongs to.


text:
Q: Using AWS Lambda with Amazon DocumentDB Change Streams I am looking to populate an SQS queue via a lambda function by listening to DocumentDB change streams. I know this can be done with DynamoDB. Is there a way to achieve this with DocumentDB?

A: Yes, Amazon DocumentDB has a change streams feature and you can use a Lambda function to get the change events and write them to another destination like SQS. There isn't currently a built-in integration between DocumentDB Change Streams and Lambda, so your Lambda will need to poll for change events and store the last processed event id externally (something like another DocumentDB collection or DynamoDB table). Please see this video that provides more details on how this can be done.


text:
Q: Multiple strings search in consecutive lines in a log file I have a log file Input.log which records failed and successful login attempts made by different users and it keeps updating in real time. I am interested only in failed login attempt made by one user i.e. master. Whenever there is a failed login attempt by user master, following 3 fixed text strings will always come in 3 consecutive lines as shown below in sample Input.log file:
Authenticating the user "master" with the password
Failed to logon to the system due to something unexpected
SSCMPE-00102: Failed to authenticate user. Invalid credentials. Enter valid credentials

Input.log file sample for a failed login attempt by master:
[2021-05-14T04:18:41.378-06:00] [FoundationServices0] [NOTIFICATION] [01216] [oracle.bi.bifndnepm.bpmui.logon.CSSAuthenticate] [tid: 30] [userId: <anonymous>] [ecid: 00j8DrPuyNGB1FwDwFj8CW0001hC0004FL,0:1] [APP: WORKSPACE#11.1.2.0] [SRC_CLASS: com.hyperion.bpm.logon.CSSAuthenticate] [SRC_METHOD: authenticateUser:473] Authenticating the user "master" with the password "*********".
[2021-05-14T04:18:41.573-06:00] [FoundationServices0] [ERROR] [02601] [oracle.bi.bifndnepm.bpmui.logon.LogonServlet] [tid: 30] [userId: <anonymous>] [ecid: 00j8DrPuyNGB1FwDwFj8CW0001hC0004FL,0:1] [APP: WORKSPACE#11.1.2.0] [SRC_CLASS: com.hyperion.bpm.logon.LogonServlet] [SRC_METHOD: writeLogonCssException:206] Failed to logon to the system due to something unexpected.[[
SSCMPE-00102: Failed to authenticate user. Invalid credentials. Enter valid credentials.
    at com.hyperion.css.store.identity.IdentityStoreImpl.authenticate(IdentityStoreImpl.java:1845)
    at com.hyperion.css.spi.impl.nvdb.NativeProvider.authenticate(NativeProvider.java:74)
    at com.hyperion.css.facade.impl.CSSAbstractAuthenticator.authenticateUser(CSSAbstractAuthenticator.java:645)
    at com.hyperion.css.facade.impl.CSSAPIAuthenticationImpl.authenticate(CSSAPIAuthenticationImpl.java:69)

I want to create a monitoring script sothat as soon as we have these 3 text strings appeared in 3 consecutive lines, I should get an email alert about the failed login attempt made by user master.
I will schedule the script to run in Windows task scheduler. I'd like to make the script run continuously to detect the failed login attempts in real time. So it should read only freshly written entries in Input.log file from the previous run of the script.
So far I have below code that, in failed.log, gives me all the lines matching above three strings coming consecutively in three lines (what I actually want) but also many other unwanted lines matching the three strings individually in different lines (which I don't want).
$File = "C:\data\Input.log"

$EmailParam=@{
    To='usergroup@domain.com'
    From='user@domain.com'
    SmtpServer='smtp.serveraddress.com'
    Subject='Failed Login Attempt by the user Master'
    Body='Alert! Failed Login Attempt found for the user Master'
    Attachment='failed.log'
}

$String='Authenticating the user "master" with the password','Failed to logon to the system due to something unexpected','SSCMPE-00102: Failed to authenticate user. Invalid credentials. Enter valid credentials'

Get-Content $File | Select-string -Pattern $String | Set-Content failed.log | ForEach {
    Send-MailMessage @EmailParam
}

Would appreciate if you could guide me to fix it. Thanks!

A: a possible solution: the regex pattern looks at 3 consecutives lines
$pat1 = 'Authenticating the user "master" with the password'
$pat2 = 'Failed to logon to the system due to something unexpected'
$pat2 = 'SSCMPE-00102: Failed to authenticate user. Invalid credentials. Enter valid credentials'
$pat = $pat1 + ".*?`r?`n.*?" + $pat2 + ".*?`r?`n.*?" + $pat3

$path = "C:\Users\ThierryK\Documents\test.log"
$lines = Get-Content -Raw -Path $path

$option = [System.Text.RegularExpressions.RegexOptions]::Singleline

$pattern = [regex]::new($pat, $option)

$matches = $pattern.Matches($lines)

foreach($m in $matches){
   $m.Groups[0].Value
   #send your email
}

i suggest you to keep the time each time you scan the log to avoid to scan the same thing every time

A: *

*Use Get-Content's -Wait switch to keep waiting - indefinitely - for new lines to be added to the log file.

*Maintain state via a ForEach-Object call in which you can use -match, the regular-expression matching operator to examine the lines.
$matchingLineCount = 0
$matchingLines = @()

 Get-Content -Wait $File | ForEach-Object {
  if ($matchingLineCount -eq 2) { # 3rd line -> send email.
    $matchingLines += $_
    $matchingLines | Set-Content failed.log
    Send-MailMessage @EmailParam
  }
  elseif ($matchingLineCount -eq 0 -and $_ -match 'Authenticating the user "master"') {
    $matchingLines += $_
    ++$matchingLineCount
    return
  } elseif ($matchingLineCount -eq 1 -and $_ -match 'Failed to logon to the system due to something unexpected') {
    $matchingLines += $_
    ++$matchingLineCount
    return
  }
  $matchingLineCount = 0; $matchingLines = @()
}

Note:

*

*Given that only 3 lines must be collected, I'm defining $matchingLines as a  regular array (@()) and using += to "append" lines to it, for brevity and convenience.

*However, in general this approach to iteratively building a collection is inefficient, because every += causes a new array to be created behind the scenes - of necessity, given that arrays are immutable with respect to their element count - see this answer for more information.

*

*GitHub issue #5643 discusses switching PowerShell's default collection data structure from non-extensible arrays to an extensible collection type.


text:
Q: My program isn't sorting properly Im making a histogram from a file and I got it working however its not sorting them correctly. Meaning 100 90 50 etc.
Here is my code:
from collections import Counter
data=[]
with open("data.txt", 'r') as f:
    for line in f:
    line = line.strip()
    data.append(str(line))

counts = Counter(data)

for key, size in sorted(counts.items()):
    print('{}: {}'.format(key, int(size) * '*'))

This is the output:
100: ******
25: **
50: ***
60: *
65: *
70: **
75: *
80: ****
85: ****
90: ***

Any suggestions??
EDIT:
What I mean is that they go numerically in order. So insted of 100, 25, 50, .... I want it 100, 90, 85,.....

A: njzk2 is absolutely right, thanks!
One way you can do it is like this :
...
line = line.strip()
# casting to 'int' type just before populating in data table..
data.append(int(line))
...

then, you can
...
# applying reversed to reorder from ascending order to descending order.
for key, size in sorted(counts.items(), reverse=True):
...


text:
Q: Looking for one regex to replace my string I have problem with regex and need some help.
Current I have url has type
/search/:year/:month/:day/xxxx with :month and :day maybe exist or not . Now I need replace /search/:year/:month/:day patern on my url with empty string. Meaning get remain of url part. So this is some example below
1.'/search/2017/02/03/category/gun' => '/category/gun'
2.'/search/2017/02/03/' => '/'
3.'/search/2017/01/category/gun' => '/category/gun/'
4.'/search/2017/category/gun/' => '/category/gun/'
5.'/search/2018/?category=gun&type%5B%5D=sendo' => '/?category=gun&type%5B%5D=sendo/'
I try to use regex = /^\/search\/((?:\d{4}))(?:\/((?:\d|1[012]|0[1-9])))?(?:\/((?:[0-3]\d)))/
But it is failed for case /search/2017/category/gun/
const regex = /^\/search\/((?:\d{4}))(?:\/((?:\d|1[012]|0[1-9])))?(?:\/((?:[0-3]\d)))/
const testLink = [
  '/search/2017/02/03/category/gun/',
  '/search/2017/01/category/gun/',
  '/search/2017/category/gun/',
  '/search/2017/02/03/category/gun/',
  '/search/2018/?category=gun&type%5B%5D=sendo'

]

testLink.forEach((value, i) => {
  console.log(value.replace(regex, ''))
  console.log('-------------------')
})

A: Use this regex pattern (\/search\/.*\d+)(?=\/)
Demo

const regex = /(\/search\/.*\d+)(?=\/)/g;
const testLink = [
  '/search/2017/02/03/category/gun/',
  '/search/2017/01/category/gun/',
  '/search/2017/',
  '/search/2017/02/03/category/gun/',
  '/search/2018/?category=gun&type%5B%5D=sendo'
]

testLink.forEach((value, i) => {
  console.log(value.replace(regex, ''))
  console.log('-------------------')
})

A: Splitting on the following pattern seems to work:
\d{4}(?:/\d{2})*

This would place the target you want as the second element in the split array, with the first portion being what precedes the year-digit portions of the path.

input = '/search/2017/02/03/category/gun';
parts = input.split(/\d{4}(?:\/\d{2})*/);
console.log(parts[1]);
console.log('/search/2017/02/03'.split(/\d{4}(?:\/\d{2})*/)[1]);
console.log('/search/2017/01/category/gun'.split(/\d{4}(?:\/\d{2})*/)[1]);
console.log('/search/2017/category/gun/'.split(/\d{4}(?:\/\d{2})*/)[1]);

Whether you do or do not expect a final trailing path separator is not entirely clear.  In any case, the above answered can be modified per that expectation.

A: Here's one way:
strings = [
    '/search/2017/02/03/category/gun',
    '/search/2017/02/03/',
    '/search/2017/01/category/gun',
    '/search/2017/category/gun/',
]; for (var i = 0; i < strings.length; i++) {
    alert(strings[i].replace(/\/search\/[0-9\/]+(\/)(category\/[^\/$]+)?.*/,'$1$2'));
}

A: you can use the same regex but revers the order of this part (?:\d|1[012]|0[1-9])
 as following (?:\d|1[012]|0[1-9]) and make last group optional as following ((?:[0-3]\d)))?
const regex = /^\/search\/((?:\d{4}))(?:\/((?:0[1-9]|1[012]|\d)))?(?:\/((?:[0-3]\d)))?/
const testLink = [
  '/search/2017/02/03/category/gun/',
  '/search/2017/01/category/gun/',
  '/search/2017/category/gun/',
  '/search/2017/02/03/category/gun/'
]

output
/category/gun/
/category/gun/
/category/gun/
/category/gun/

if you are sure of date format so you can simplify your exp to be ^\/search\/\d{4}(?:\/\d{1,2}){0,2}


text:
Q: misunderstanding UPDATE FROM syntax Using PostGIS I have two tables, the first one contains the boundary of 250 cities and the second one contains the coundary of all country in the world.
I am trying to affect to each cities the country it belongs to. The following query allow me to get the result I desire.
SELECT DISTINCT ON (cities.id) cities.id, country.id
FROM cities
LEFT JOIN country ON st_intersects(country.geom, cities.geom)

But when I am using this query :
UPDATE cities
SET country_id=subq.id
FROM (SELECT DISTINCT ON (cities.id) country.id
    FROM cities
    LEFT JOIN country ON st_intersects(country.geom, cities.geom)) AS subq

The country_id column is full of the same number.
What did I miss in the using of the UPDATE FROM syntax ?

A: You need to relate the two queries with a join condition:
UPDATE cities
  SET country_id=subq.id
FROM (
  SELECT DISTINCT ON (cities.id) country.id
  FROM cities
    LEFT JOIN country ON st_intersects(country.geom, cities.geom)
) AS subq
  where subq.id = cities.id;

But I think you don't need the sub-select to begin with. You can join the country table directly to the cities table:
UPDATE cities
  SET country_id = country.id
FROM country
where st_intersects(country.geom, cities.geom)


text:
Q: React component doesn't render even when the path changes App.jsx
import "./../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./../node_modules/bootstrap/dist/js/bootstrap.bundle";
import React from "react";
import Projects from "./Projects";
import Contact from "./Contact";
import {Route} from "react-router-dom";
import Home from "./Home";
import Navbar from "./Navbar";
import {Routes,BrowserRouter as Router} from "react-router-dom";

const App = () => {
    return(
        <>

                <Navbar/>

                <Router>
                    <Routes>
                        <Route path="/" element={<Home/>}/>
                        <Route exact path="/contact/" element = {<Contact/>}/>
                        <Route exact path="/projects/" element = { <Projects/>}/>
                    </Routes>
                </Router>
        </>
    );

};
export default App;

Navbar.jsx
import React from "react"
import {NavLink,BrowserRouter as Router} from "react-router-dom";
const Navbar = ()=>{
   return(
<>
<Router>

      <NavLink  className="brand-name " style={{color:"white"}} strict to="/">Shriharsh's Colosseum</NavLink>
      <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            <NavLink  className="nav-link"  style={{color:"white"}} strict to="/">Home</NavLink>

            <NavLink  className="nav-link"  style={{color:"white"}}  strict to="/projects/">Projects</NavLink>

            <NavLink  className="nav-link"  style={{color:"white"}} strict to="/contact/">Contact</NavLink>

</Router>
   </>
   );
};

export default Navbar;

The problem associated and what the code is intended to do:
I have a app with a navbar rendered nicely,now,for it's utility,even when the links are clicked the page doesn't seem to render it,even when the link changes.I tried searching for the solution for the similar problem and came across many but all of them seem to have their own unique cases of causation.I tried to changed path from /path to /path/ to see if it would work by any change,it doesn't.Likewise,gave it a shot by changing the NavLink to Link,doesn't work.

A: Issue
You are rendering the Navbar component and links into one router and the routes you want to link to in another router. You need only one router to provide a routing context to an entire React app.
Solution
Remove the extraneous router the Navbar is rendering and move Navbar into the router that the App component is rendering.
Navbar.jsx
import React from "react"
import { NavLink } from "react-router-dom";

const Navbar = () => {
  return (
    // <-- Router removed

            <NavLink
              className="brand-name"
              style={{ color: "white" }}
              to="/"
            >
              Shriharsh's Colosseum
            </NavLink>
            <button ....>

            </button>

                  <NavLink className="nav-link" style={{ color: "white" }} to="/">
                    Home
                  </NavLink>

                  <NavLink
                    className="nav-link"
                    style={{ color: "white" }}
                    to="/projects"
                  >
                    Projects
                  </NavLink>

                  <NavLink
                    className="nav-link"
                    style={{ color: "white" }}
                    to="/contact"
                  >
                    Contact
                  </NavLink>

  );
};

export default Navbar;

App.jsx
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./../node_modules/bootstrap/dist/js/bootstrap.bundle";
import Projects from "./Projects";
import Contact from "./Contact";
import Home from "./Home";
import Navbar from "./Navbar";

const App = () => {
  return(
    <>

      <Router>
        <Navbar /> // <-- inside router
        <Routes>
          <Route path="/" element={<Home />}/>
          <Route path="/contact" element={<Contact />} />
          <Route path="/projects" element={ <Projects />} />
        </Routes>
      </Router>
    </>
  );
};

export default App;

Please also note that I removed the trailing "/" character on the routes.

A: As shown in the React Router dom v6 documentation the BrowserRouter wraps your app to store the current location of your app in the address bar, so your index.jsx should be like this:
import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>{/* The rest of your app goes here */}</BrowserRouter>,
  root
);

then, to properly setup routes you should write in your App.jsx file your routes using the Routes and Route components.
Here's how your App.jsx should look like:
import "./../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./../node_modules/bootstrap/dist/js/bootstrap.bundle";
import React from "react";
import Projects from "./Projects";
import Contact from "./Contact";
import { Route } from "react-router-dom";
import Home from "./Home";
import Navbar from "./Navbar";
import { Routes, Route } from "react-router-dom";

const App = () => {
  return (
    <>

      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route exact path="/contact" element={<Contact />} />
        <Route exact path="/projects" element={<Projects />} />
      </Routes>
    </>
  );
};
export default App;

Then, to navigate through the routes you declared in the App.jsx file you can use the Link component (here's the documentation for it)
So, your NavBar.jsx should look like this:
import React from "react";
import { Link } from "react-router-dom";
const Navbar = () => {
  return (
    <>

              <Link to="/" className="brand-name" style={{ color: "white" }}>
                Shriharsh's Colosseum
              </Link>
              <button
                className="navbar-toggler"
                type="button"
                data-toggle="collapse"
                data-target="#navbarSupportedContent"
                aria-controls="navbarSupportedContent"
                aria-expanded="false"
                aria-label="Toggle navigation"
              >

              </button>

                    <Link
                      to="/"
                      className="nav-link"
                      style={{ color: "white" }}
                    >
                      Home
                    </Link>

                    <Link
                      to="/projects"
                      className="nav-link"
                      style={{ color: "white" }}
                    >
                      Projects
                    </Link>

                    <Link
                      to="/contact"
                      className="nav-link"
                      style={{ color: "white" }}
                    >
                      Contact
                    </Link>

    </>
  );
};

export default Navbar;

Do note that I removed the Router component from the Navbar since not necessary.


text:
Q: Passing query parameters into an SSIS I have an SSIS package that queries data from a view using an SQL Command.
The SQL Command looks something like this:
SELECT from myView WHERE dateEntered >= GetDate() AND dateEntered < GetDate() + 1

Now I want to be able to specify the start and end dates such that the query behaves as:
SELECT from myView WHERE dateEntered >= startDate AND dateEntered < endDate

However, if start and end dates are not provided I need to use today's date and today's date + 1
What would be the best way to do this in an SSIS Package?
I can't change the view so it has to be done off the view or using variables in the SSIS.  I'm not too familiar with SSIS and not sure if there is something in the toolbox that would let me process a date variable and then use it in the SQL Command?

A: I ended up passing in parameters to dtexec using /SET.
Then I used a Script Task to process the date in order to take care of invalid or other cases.

A: Why don't you use an ISNULL check for the dates? Like,
SELECT *
FROM myView
WHERE dateEntered >= ISNULL(startDate,GETDATE())
    AND dateEntered < ISNULL(endDate,DATEADD(1,DAY,GETDATE()))

Then you can pass the start and end dates as parameters to the query from SSIS.
SELECT *
FROM myView
WHERE dateEntered >= ISNULL(?,GETDATE())
    AND dateEntered < ISNULL(?,DATEADD(1,DAY,GETDATE()))

You can specify these parameters at the Execute SQL task's parameters section.


text:
Q: ScrollTop not working in IE Anyone have any ideas why scrollTop isn't working in IE?
It works in Chrome fine, and I don't know about firefox. (The idea of this script is to have an autoscrolling page that resets once it hits the bottom of the page)
function getheight() {

                var myWidth = 0,
            myHeight = 0;
             if (typeof (window.innerWidth) == 'number') {
                    //Non-IE
                    myWidth = window.innerWidth;
                    myHeight = window.innerHeight;
                } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                    //IE 6+ in 'standards compliant mode'
                    myWidth = document.documentElement.clientWidth;
                    myHeight = document.documentElement.clientHeight;
                } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                    //IE 4 compatible
                    myWidth = document.body.clientWidth;
                    myHeight = document.body.clientHeight;
                }
                var scrolledtonum = window.pageYOffset + myHeight + 2;
                var heightofbody = document.body.offsetHeight;
                if (scrolledtonum >= heightofbody) {
                    document.body.scrollTop(0, 0);
                }
            }

            window.onscroll = getheight;

            function func() {
                window.document.body.scrollTop++;
            }

            window.document.onmouseover = function () {
                clearInterval(interval);
            };

            window.document.onmouseout = function () {
                interval = setInterval(func, 20);
            };

            var interval = setInterval(func, 20);

A: Try this
window.scroll(0,0) //x-axis, y-axis

A: Try:
document.documentElement.scrollTop = x // where x is some integer

A: The reason things like this don't work on one browser or another is usually due to something like:
window.document.body.scrollTop++;

You can't just do that because some browsers have that value as a string, e.g. "5px" and some have it as a number.

A: Solution for EDGE needs to set scrollTop on scrollingElement document property:
document.scrollingElement.scrollTop= x; // x is integer value

But you have to ensure, that CSS on HTML element has set overflow to default value (visible):
html {
    overflow: visible;
}

A: If you need it to work in IE and Edge:
document.body.scrollTop = x


text:
Q: three.js: How can I target object's position to another (grouped) object, while allowing rotation to follow AR camera? I'm using an augmented reality library that does some fancy image tracking stuff. After learning a whole lot about this project, I'm now beyond my current ability and could use some help. For our purposes, the library creates an (empty) anchor point at the center of an IRL image target in-camera. Then moves the virtual world around the IRL camera.
My goal is to drive plane.rotation to always face the camera, while keeping plane.position locked to the anchor point. Additionally, plane.rotation values will be referenced later in development.
const THREE = window.MINDAR.IMAGE.THREE;

document.addEventListener('DOMContentLoaded', () => {
  const start = async() => {
    // initialize MindAR
    const mindarThree = new window.MINDAR.IMAGE.MindARThree({
      container: document.body,
      imageTargetSrc: '../../assets/targets/testQR.mind',
    });
    const {renderer, scene, camera} = mindarThree;

    // create AR object
    const geometry = new THREE.PlaneGeometry(1, 1.25);
    const material = new THREE.MeshBasicMaterial({color: 0x00ffff, transparent: true, opacity: 0.5});
    const plane = new THREE.Mesh(geometry, material);

    // create anchor
    const anchor = mindarThree.addAnchor(0);
     anchor.group.add(plane);

    // start AR
    await mindarThree.start();
    renderer.setAnimationLoop(() => {
      renderer.render(scene, camera);
    });
  }
  start();
});

Everything I've tried so far went into the solutions already massaged into the (functioning draft) code. I have, however, done some research and found a couple avenues that might or might not work. Just tossing them out to see what might stick or inspire another solution. Skill-wise, I'm still in the beginner category, so any help figuring this out is much appreciated.

*

*identify plane object by its group index number;
drive (override lib?) object rotation (x, y, z) to face camera;

*possible solutions from dev:

*

*"You can get those values through the anchor object, e.g. anchor.group.position.  Meaning that you can use the current three.js API and get those values but without using it for rendering i.e. don't append the renderer.domElement to document."

*"You can hack into the source code of mindar (it's open source)."

*"Another way might be easier for you to try is to just create another camera yourself. I believe you can have multiple cameras, and just render another layer on top using your new camera."

A: I think it may be as simple as calling lookAt in the animation loop function:
// start AR
await mindarThree.start();
renderer.setAnimationLoop(() => {
  plane.lookAt(new THREE.Vector3());
  renderer.render(scene, camera);
});

This assumes the camera is always located at (0,0,0) (i.e., new THREE.Vector3()). This seems to be true from my limited testing. I found it helpful to debug by copy-pasting the MindAR three.js example into this codepen and printing some relevant values to the console.
Also note that, internally, MindAR's three.js module seems to directly modify the world matrix of the anchor.group object without modifying the position/rotation/scale parameters.


text:
Q: How can I get this XML Structure I have a web service that has an input object similar to the following.
public class MyInput
{
    [System.Xml.Serialization.XmlArrayItem("Demographic")]
    public DemographicsInfo[] Demographics {get; set;}
}

With the definition of the DemographicsInfo class like this.
public class DemographicsInfo
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name { get; set; }
    public string Value { get; set; }
}

Right now this generates an XML structure like this.
<Demographics>
    <Demographic Name="String">
        <value>string</value>
    </Demographic>
    <Demographic Name="String">
        <value>string</value>
    </Demographic>
</Demographics>

I need to get it into this
<Demographics>
    <Demographic Name="String">string</Demographic>
    <Demographic Name="String">string</Demographic>
</Demographics>

For the life of me, I cannot seem to find the proper attribute(s) to apply to get this format.  Does anyone have any advice?

A: If you know the structure you want, the simplest option is to work back from the xml; write the xml into a file (foo.xml in my case), then (at the command line):
xsd foo.xml
xsd foo.xsd /classes

Then look at foo.cs to see how it can be done; it turns out that you simply mark the value with [System.Xml.Serialization.XmlTextAttribute()].
Here's the xsd output:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.3053
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=2.0.50727.3038.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Demographics {

    private DemographicsDemographic[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Demographic", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
    public DemographicsDemographic[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class DemographicsDemographic {

    private string nameField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value {
        get {
            return this.valueField;
        }
        set {
            this.valueField = value;
        }
    }
}

A: Looking a bit on what Marc has, but I'm guessing a difference between Visual Studio 2005 and 2008.
I needed to add the following to the declaration of the "Value" element.
[System.Xml.Serialization.XmlText()]
public string Value { get; set; }

It looks like it works!


text:
Q: how use omnipay for paypale payement in Laravel 5.4 Please how i can make an checkout throw paypal from my website,
using Sabdbox & omnipay  package,
i'm using Laravel 5.4
i installed the omnipay package
and i created my sandbox account
please HELP

A: I don't believe that Omnipay is yet compatible with Laravel 5.4 because of the Symfony 3 dependency.  Either go back to an earlier version of Laravel or wait for Omnipay 3.0.
It might help for you to show the code that you currently have so we can comment on that.  If you look in the class docblocks for PayPal_Rest gateway in Omnipay you will see some usage examples as well as sample code.


text:
Q: Running a runtime compiled C# script in a sandbox AppDomain My application should be scriptable by the users in C#, but the user's script should run in a restricted AppDomain to prevent scripts accidentally causing damage, but I can't really get it to work, and since my understanding of AppDomains is sadly limited, I can't really tell why.
The solution I am currently trying is based on this answer https://stackoverflow.com/a/5998886/276070.
This is a model of my situation (everything except Script.cs residing in a strongly named assembly). Please excuse the wall of code, I could not condense the problem any further.
class Program
{
    static void Main(string[] args)
    {
        // Compile the script
        CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
        CompilerParameters parameters = new CompilerParameters()
        {
            GenerateExecutable = false,
            OutputAssembly = System.IO.Path.GetTempFileName() + ".dll",
        };
        parameters.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);

        CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, "Script.cs");

        // ... here error checks happen ....//

        var sandbox = Sandbox.Create();
        var script = (IExecutable)sandbox.CreateInstance(results.PathToAssembly, "Script");

        if(script != null)
            script.Execute();

    }
}

public interface IExecutable
{
    void Execute();
}

The Sandbox class:
public class Sandbox : MarshalByRefObject
{
    const string BaseDirectory = "Untrusted";
    const string DomainName = "Sandbox";

    public static Sandbox Create()
    {
        var setup = new AppDomainSetup()
        {
            ApplicationBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, BaseDirectory),
            ApplicationName = DomainName,
            DisallowBindingRedirects = true,
            DisallowCodeDownload = true,
            DisallowPublisherPolicy = true
        };

        var permissions = new PermissionSet(PermissionState.None);
        permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));
        permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

        var domain = AppDomain.CreateDomain(DomainName, null, setup, permissions,
            typeof(Sandbox).Assembly.Evidence.GetHostEvidence<StrongName>());

        return (Sandbox)Activator.CreateInstanceFrom(domain, typeof(Sandbox).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandbox).FullName).Unwrap();
    }

    public object CreateInstance(string assemblyPath, string typeName)
    {
        new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, assemblyPath).Assert();
        var assembly = Assembly.LoadFile(assemblyPath);
        CodeAccessPermission.RevertAssert();

        Type type = assembly.GetType(typeName); // ****** I get null here
        if (type == null)
            return null;

        return Activator.CreateInstance(type);
    }
}

The loaded Script:
using System;

public class Script : IExecutable
{
    public void Execute()
    {
        Console.WriteLine("Boo");
    }
}

In CreateInstance of SandBox, I always get null at the marked line. I tried various forms of giving the name, including reading the type name (or fuly qualified name) from results.CompiledAssembly using reflection.
What am I doing wrong here?

A: The first thing that i'll check is if there are compilation errors (i had several headache caused by this issues)
The second idea is about the resolution of assemblies. I always add as a security check an event handler for AppDomain.CurrentDomain.AssemblyResolve, where i seek on my known path for the missing Assemblies. When the not found assembly is the one i just compiled i add a static reference to it and return it.
What I usually do is this:

*

*Create the new Assembly on file system with the compiler

*Load its content with the File.ReadAllBytes

*Load the dll with the Assembly.Load in the AppDomain in which i will be using the object

*Add the AppDomain.CurrentDomain.AssemblyResolve event

Just in case (since i use this a lot) i created a small library to accomply this kind of things
The code and documentation are here: Kendar Expression Builder
While the nuget package is here: Nuget Sharp Template


text:
Q: Memory leak in android? Which is better tool (adb shell procmem  or adb shell showmap ) to check memory leak in native heap? And why?
I have used both but procmem is showing memory leak but showmap does not.


text:
Q: Optimising resetting of demo data In one of the apps we support we need to have "realistic demonstration data" for our salespeople to use in demoing and selling.
We currently have a rake task that resets this demo data once a day, however it's really quite inefficient and slow (it takes about 5 - 10minutes to run through)
There are definitely ways that I could optimise the code which generates the demo data (which I'm planning to do) but I'm thinking that there is probably a better way to do this altogether...
What I'm hoping to do is grab the output of the reset (i.e. grab the raw SQL). I'm hoping with this I can just make a scheduled task which resets the demo data directly to the DB everyday instead of having to load the whole Rails environment and execute a bunch of ruby methods.
This way I can only run the slow task when the nature of the demo data changes (which is quite rare) in order to update my SQL.
Is this the best approach? How can I grab the SQL in a nice format?

A: It seems to be a good solution! if you have no asset at all simple make a dump  a.e. in
mysql
mysqldump -uUSER -pPASSWORD [other params] DATABASE > yourdumpfile.sql

and to restore
mysql -uUSER -pPASS DATABASE < yourdumpfile.sql

here a usefull rake task that you could use.
bye

A: I can't tell by your question but is your rake task using some rails specific ways of creating the data? For example, a gem like faker? I'll answer assuming that you are.
If you're thinking of saving and re-running the sql that faker (or something similar) creates then I'd say that's a bad idea. You said the data rarely changes so on those rare occasions just use your rails environment.
But once you have the data you need go with what @andrea suggested and dump the data and restore it.


text:
Q: Protractor - unknown error: angular is not defined when using by.model I'm working on writing some protractor tests for my Angular component and keep getting an error "unknown error: angular is not defined" when I try to use by.model to select the input element.
Its odd because if I do this it works fine and pases:
it('should have an input element for searching', () => {
    var inputElement = element(by.model('searchText');
    expect(inputElement).toBeDefined();
});

But when I try to do something like this it fails with the angular undefined error:
it('should filter the search text', () => {
     var inputElement = element(by.model('searchText');
     expect(inputElement).toBeDefined();

     inputElement.clear()
     inputElement.click();
     inputElement.sendKeys('ICBC');

     var tableLengthRow = element.all(by.css('.animate-repeat').count();
     expect(tableLength).toBe(1);
});

If I replace this line:
var inputElement = element(by.model('searchText');

with this one:
var inputElement = element.all(by.tagName('input')).get(0);

and leave the rest as I have it the test passes.
Does anyone know why the first test above works with by.model but not the second one where I am actually clicking on the element?
And then how can I define angular on the page using Webpack and npm?
Thanks

A: by.model is not supported in Angular (angular2, angular4 and on).
The recommended alternative is by.css().
As per angular/protractor's current readme:

Protractor works with AngularJS versions greater than 1.0.6/1.1.4, and is compatible with Angular applications. Note that for Angular apps, the by.binding() and by.model() locators are not supported. We recommend using by.css().

Examples of the alternative at Angular Guide - E2E Tests:
Previous code               New code         Notes
by.model('$ctrl.query')     by.css('input')  The model matcher relies on AngularJS ng-model
by.model('$ctrl.orderProp') by.css('select') The model matcher relies on AngularJS ng-model


text:
Q: How can I place chart directly above the legend? (highcharts) Here is what I achieved so far
http://jsfiddle.net/9r6Lr5gr/3/
Highcharts.chart('container', {
chart: {
    type: 'bar'
},
title: {
    text: ''
},
exporting: {
        enabled: false
},
credits: {
        enabled: false
},
tooltip: {
        enabled: false
},
xAxis: {
        lineWidth: 0,
    title: {
            text: ''
    },
    labels: {
            enabled: false
    }
},
yAxis: {
        gridLineWidth: 0,
    title: {
            text: ''
    },
    stackLabels: {
        enabled: true,
        style: {
            fontWeight: 'bold',
            color: 'gray'
        },
        formatter: function(){
                return 'Total: ' + this.total;
        }
    },
    labels: {
            enabled: false
    }
},
legend: {
    reversed: true,
    align: 'left'
},
plotOptions: {
    series: {
        stacking: 'normal',
        pointWidth: 30,
        dataLabels: {
            enabled: true,
            color: 'white',
            style: {
                    fontWeight: 'none',
                    fontSize: 15
            }
        }
    }
},
series: [{
    name: 'Outstanding (due > 7 days)',
    data: [41]
}, {
    name: 'Outstanding (due < 7 days)',
    data: [32]
}, {
    name: 'Overdue',
    data: [15]
}]
});

I want to place the bar chart directly above the legend. Also, is it possible the little horizontal line just before the bar chart. Thanks.

A: Go through comment in code
Fiddle Demo
Highcharts.chart('container', {
    chart: {
        type: 'bar',
        marginBottom: -180, //make charts display at bottom
        events: {
            load: function () {
                // Draw the horizontal line
                var ren = this.renderer,
                    colors = Highcharts.getOptions().colors,
                    line = ['M', 550, 0, 'L', 0, 0, 'L', 0, 0, 'M', 0, 0, 'L', 5, 0];

                ren.path(line)
                    .attr({
                        'stroke-width': 2,
                        stroke: colors[1]
                    })
                    .translate(10, 335)
                    .add();

            }
        }

    },
    title: {
        text: ''
    },
    exporting: {
            enabled: false
    },
    credits: {
            enabled: false
    },
    tooltip: {
            enabled: false
    },
    xAxis: {
            lineWidth: 0,
        title: {
                text: ''
        },
        labels: {
                enabled: false
        }
    },
    yAxis: {
            gridLineWidth: 0,
        title: {
                text: ''
        },
        stackLabels: {
            enabled: true,
            style: {
                fontWeight: 'bold',
                color: 'gray'
            },
            formatter: function(){
                    return 'Total: ' + this.total;
            }
        },
        labels: {
                enabled: false
        }
    },
    legend: {
        reversed: true,
        align: 'left'
    },
    plotOptions: {
        series: {
            stacking: 'normal',
            pointWidth: 30,
            dataLabels: {
                enabled: true,
                color: 'white',
                style: {
                        fontWeight: 'none',
                        fontSize: 15
                }
            }
        }
    },
    series: [{
        name: 'Outstanding (due > 7 days)',
        data: [41]
    }, {
        name: 'Outstanding (due < 7 days)',
        data: [32]
    }, {
        name: 'Overdue',
        data: [15]
    }]
});