text:
Q: Al comparar dos variables numericas no reconoce cual es el valor mayor, por qué? Tengo una tabla donde muestra las facturas pendientes de pago por cliente, con su respectiva fecha de emision y su saldo al cancelar, en esta tabla, muestra un checkbox, cuya funcion es al clickear tomará el valor de la factura y lo considerará como pago, el detalle es que quiero ir descontando de un monto digitado en textbox type="number", pero al realizar la comparacion si el saldo del documento es menor al disponible lo toma como si fuera mayor o viceversa. Este codigo se genera en un archivo .js
Podrian ayudarme por favor.

{
       disponible = $('#dispopago').val(); //disponible = 12000

   $("input[type=checkbox]:checked").each(function(){
       montopago = $(this).val();                     // montopago = 9172.64
       numdoc = $(this).attr("at-pago");              // abc
   });
   if(montopago > disponible) {               //se cumple si montopago es menor, aun colocando el signo >
       alert('pago si es menor a disponible');
       valpago = montopago;
   }else if(montopago == disponible){
       alert('valor del pago es igual al disponible');
       valpago = disponible;
   else if(montopago < disponible){
       alert('valor del pago sera abono');
       valpago = disponible;
   }
}

A: Cuando obtienes un valor de un elemento con .val(), siempre será una string, lo que tendrías que hacer es transformar tus valores a numéricos para poder compararlos.
En este caso
disponible = parseFloat($('#dispopago').val());

y
montopago = parseFloat($(this).val());

Usamos el parseFloat() ya que tus valores manejan decimales pero hay otras funciones dependiendo del tipo de dato que quieras transformar.


text:
Q: Google App Engine singletons (Python) The standard way of doing singletons in Python is
class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

However, this doesn't work on App Engine, since there are may be many servers and we would get one instance per server. So how would we do it for an app engine entity?
Something like:
class MySingleton(db.models):
    def __init__(self):
        all = MySingleton.all()
        if all.count() > 0:
             return all.fetch(1).get()

        super(MySingleton, self).__init__ (*args, **kwargs)

This leads to a recusion error, since get() calls __init__.
How we're going to use it:
We just want to represent a configuration file, ie:
{ 'sitename': "My site", 'footer': "This page owned by X"}

A: Singletons are usually a bad idea, and I'd be interested to see what makes this an exception. Typically they're just globals in disguise, and apart from all the old problems with globals (eg. see http://c2.com/cgi/wiki?GlobalVariablesAreBad, in particular the bit at the top talking about non-locality, implicit coupling, concurrency issues, and testing and confinement), in the modern world you get additional problems caused by distributed and concurrent systems. If your app is potentially running across multiple servers, can you meaningfully have both instances of your application operate on the same singleton instance both safely and correctly?
If the object has no state of its, then the answer is yes, but you don't need a singleton, just a namespace.
But if the object does have some state, you need to worry about how the two application instances are going to keep the details synchronised. If two instances try reading and then writing to the same instance concurrently then your results are likely to be wrong. (eg. A HitCounter singleton that reads the current value, adds 1, and writes the current value, can miss hits this way - and that's about the least damaging example I can think of.)
I am largely unfamiliar with it, so perhaps Google App Engine has some transactional logic to handle all this for you, but that presumably means you'll have to add some extra stuff in to deal with rollbacks and the like.
So my basic advice would be to see if you can rewrite the algorithm or system without resorting to using a singleton.

A: If you aren't going to store the data in the datastore, why don't you just create a module with variables instead of a db.Model?
Name your file mysettings.py and inside it write:
sitename = "My site"
footer = "This page owned by X"

Then the python module effectively becomes a "singleton".  You can even add functions, if needed.  To use it, you do something like this:
import mysettings
print mysettings.sitename

That's how django deals with this with their DJANGO_SETTINGS_MODULE
Update:
It sounds like you really want to use a db.Model, but use memcached so you only retrieve one object once.  But you'll have to come up with a way to flush it when you change data, or have it have a timeout so that it gets get'd occasionally.  I'd probably go with the timeout version and do something like this in mysettings.py:
from google.appengine.api import memcache
class MySettings(db.Model):
   # properties...

def Settings():
    key = "mysettings"
    obj = memcache.get(key)
    if obj is None:
       obj = MySettings.all().get()  # assume there is only one
       if obj:
            memcache.add(key, zone, 360)
       else:
            logging.error("no MySettings found, create one!")
    return obj

Or, if you don't want to use memcache, then just store the object in a module level variable and always use the Settings() function to reference it.  But then you'll have to implement a way to flush it until the interpreter instance is recycled.  I would normally use memcached for this sort of functionality.

A: __init__ cannot usefully return anything: just like in the first example, override __new__ instead!

A: I don't think there's a real "singleton" object you can hold in a distributed environment with multiple instances running. The closest you can come to this is using memcache.
Perhaps it's better to think less in terms of singletons and more in terms of data consistency. For this App Engine provides transactions, which allow you to trap any changes in an entity that might happen while you're working with that entity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Zero-Padding in Output Text File with "{0:+03f}".format() Not Working I have created a program that calculates a variable-coefficient regression, and am attempting to output those coefficients to a text file. I am trying to use string formatting to pad zeros in order to have the output file line up correctly. The offending code is shown below:
output.write("N = 1 Regression:\n")
output.write("a    = {0:+03.6f}\n".format(T_fit_N1params[0]))
output.write("b1   = {0:+03.6f}\n".format(T_fit_N1params[1]))
output.write("tau1 = {0:+03.6f}\n".format(T_fit_N1params[2]))
output.write("R2   = {0:+03.6f}\n".format(R2(T_data, T_fit_N1)))

and its output is shown below:
N = 1 Regression:
a    = +11.685376
b1   = +75.493626
tau1 = +2.452343
R2   = +0.978152

I am instead expecting the following:
N = 1 Regression:
a    = +011.685376
b1   = +075.493626
tau1 = +002.452343
R2   = +000.978152

I know this is probably something simple, but I can't seem to figure it out even after visiting the documentation here: https://docs.python.org/3/library/string.html#string-formatting

A: The first number in the format is the total number of digits (including decimal point and sign), not the number to the left of the decimal point.  What you want is:
output.write("a    = {0:+011.6f}\n".format(T_fit_N1params[0]))

When the total width you specified isn't enough, it is automatically expanded to get everything to fit.


text:
Q: ошибка при объявление let = Uncaught SyntaxError: Unexpected number Есть два варианта строки.
первая выдает: a = 1 + 2, 3 + 4 // 3
вторая с ошибкой: let a = 1 + 2, 3 + 4 // Uncaught SyntaxError: Unexpected number
Подскажите пожалуйста, почему при let такой результат и почему тогда работает необъявленная переменная?
Спасибо.

A: Потому что существует синтаксис:
let a = 1, b = 2

А в первом случае, нет декларации, это оператор запятая, разделяющий 2 выражения:
(a = 1 + 2), (3 + 4)

3 + 4 можно просто удалить, оно не используется.
Хотя, как раз оно и является результатом всего выражения:

console.log((a = 1 + 2, 3 + 4)) // 7
console.log(a) // 3


text:
Q: Step through items in dictionary in python I have a dictionary like so:
{'AAAGGG': ['AGAGAGAA', 'AGAGAGAG'], 'AAAGGC': ['AGAGAGAG']})

I want to step through each key and then step through the chars of its corresponding values. So something like this:
for key in myDict:
    for eachValue in key:
        for char in eachValue:
            do something

Hopefully there is an easy way of doing this.

A: Python Tutorial: Looping Techniques
When you have the key, use the key to look up the value.  Don't iterate through the key.
for key in myDict:
    for eachValue in myDict[key]:
        for char in eachValue:
            do something

More efficiently, iterate through the items and avoid the extra lookup:
for key, value in myDict.items():
    for eachValue in value:
        for char in eachValue:
            do something

A: This should do it:
my_dict = {'AAAGGG': ['AGAGAGAA', 'AGAGAGAG'], 'AAAGGC': ['AGAGAGAG']})

for parent_value in my_dict.values():
    for sub_value in parent_value:
        for char in sub_value:
            do_something(char)

A: You're looking for chain.from_iterable:
from itertools import chain
print list(chain.from_iterable({'long_key': ["abc", "cdef"], 'another_key':['ZYC', 'hgt']}.keys()))
#  ['a', 'n', 'o', 't', 'h', 'e', 'r', '_', 'k', 'e', 'y', 'l', 'o', 'n', 'g', '_', 'k', 'e', 'y']


text:
Q: Artefacts in Interpolated Value Noise I'm trying to create a basic value noise function. I've reached the point where it's outputting it but within the output there are unexpected artefacts popping up such as diagonal discontinuous lines and blurs. I just can't seem to find what's causing it. Could somebody please take a look at it to see if I'm going wrong somewhere.
First off, here are three images that it's ouputting with greater magnification on each one.

//data members
float m_amplitude, m_frequency;
int m_period;  //controls the tile size of the noise
vector<vector<float> m_points; //2D array to store the lattice

//The constructor generates the 2D square lattice and populates it.
Noise2D(int period, float frequency, float amplitude)
{
    //initialize the lattice to the appropriate NxN size
    m_points.resize(m_period);
      for (int i = 0; i < m_period; ++i)
        m_points[i].resize(m_period);

    //populates the lattice with values between 0 and 1
    int seed = 209;
            srand(seed);
    for(int i = 0; i < m_period; i++)
    {
        for(int j = 0; j < m_period; j++)
        {
            m_points[i][j] = abs(rand()/(float)RAND_MAX);
        }
    }
}

//Evaluates a position
float Evaluate(float x, float y)
{
    x *= m_frequency;
    y *= m_frequency;

    //Gets the integer values from each component
    int xFloor = (int) x;
    int yFloor = (int) y;

    //Gets the decimal data in the range of [0:1] for each of the components for interpolation
    float tx = x - xFloor;
    float ty = y - yFloor;

    //Finds the appropriate boundary lattice array indices using the modulus technique to ensure periodic noise.
    int xPeriodLower = xFloor % m_period;
    int xPeriodUpper;
    if(xPeriodLower == m_period - 1)
        xPeriodUpper = 0;
    else
        xPeriodUpper = xPeriodLower + 1;

    int yPeriodLower = yFloor % m_period;
    int yPeriodUpper;
    if(yPeriodLower == m_period - 1)
        yPeriodUpper = 0;
    else
        yPeriodUpper = yPeriodLower + 1;

    //The four random values at each boundary. The naming convention for these follow a single 2d coord system 00 for bottom left, 11 for top right
    const float& random00 = m_points[xPeriodLower][yPeriodLower];
    const float& random10 = m_points[xPeriodUpper][yPeriodLower];
    const float& random01 = m_points[xPeriodLower][yPeriodUpper];
    const float& random11 = m_points[xPeriodUpper][yPeriodUpper];

    //Remap the weighting of each t dimension here if you wish to use an s-curve profile.
    float remappedTx = tx;
    float remappedTy = ty;

    return MyMath::Bilinear<float>(remappedTx, remappedTy, random00, random10, random01, random11) * m_amplitude;
}

Here are the two interpolation functions that it relies on.
template <class T1>
static T1 Bilinear(const T1 &tx, const T1 &ty, const T1 &p00, const T1 &p10, const T1 &p01, const T1 &p11)
{
    return Lerp(    Lerp(p00,p10,tx),
            Lerp(p01,p11,tx),
            ty);
}

template <class T1> //linear interpolation aka Mix
static T1 Lerp(const T1 &a, const T1 &b, const T1 &t)
{
    return a * (1 - t) + b * t;
}

A: Some of the artifacts are the result of linear interpolation.  Using a higher order interpolation method would help, but it will only solve part of the problem. Crudely put, sharp transitions in the signal can lead to artifacts.
Additional artifacts result from distributing the starting noise values (I.E. the values you are interpolating among) at equal intervals - in this case, a grid. The highest & lowest values will only ever occur at these grid points - at least when using linear interpolation. Roughly speaking, patterns in the signal can lead to artifacts. Two potential ways I know of addressing this part of the problem are either using a nonlinear interpolation &/or randomly nudging the coordinates of the starting noise values to break up their regularity.
Libnoise has an explanation of generating coherent noise which covers these problems & solutions in greater depth with some nice illustrations. You could also peek at the source if you need see how it deals with these problems. And as richard-tingle already mentioned, simplex noise was designed to correct the artifact problems inherent in Perlin noise; it's a little tougher to get your head around, but it's a solid technique.


text:
Q: MPEG-1 Video Compression Quantization MPEG-1 quantizes both inter-frames and intra-frames, however I am curious why the quantization table for inter-frames are all constants, whereas the default quantization table for intra-frames is not.

A: This is because inter-frames contains only error residuals after subtracting predicted image from source image. Such residuals have almost uniform frequency distribution (if prediction ie. motion estimation is made correctly). For these frames we use uniform quantization matrices.
In contrast, intra-frames have very high power of low frequencies, they are hard to compress because of they enormous amplitudes. For these unpredicted frames we use low-frequency centered quantization matrices.


text:
Q: How do I turn off permalinks only for *tags* in Wordpress? Is there any way to turn off "permalinks" only for tags in WordPress?
I'd like to keep the ?tag= structure and have the tags displayed without slashes, but also keep post and page URLs with nice permalinks.
For example:
With permalinks on I'd like to have tag linked like this: ?tag=carrot instead of /tag/carrot/
The reason for doing this is a bit long and complicated, but if you think it is relevant, I might include it in the replies.

A: You can use the term_link filter in WordPress, which filters the URL for any of the term links (tags, categories, custom taxonomies) to just change the links for tags to use the query instead of the permalinks. Adding the following to a plugin or your theme's functions.php file should do the trick.
function filter_tag_link($taglink, $tag, $taxonomy) {
    if ('post_tag' == $taxonomy) {
        $taglink = '?tag='.$tag->slug;
    }
    return $taglink;
}

add_filter('term_link', 'filter_tag_link', 10, 3);

There is no useful documentation yet for term_link filter on the WordPress Codex, but looking at the source may help if you want to explore further.


text:
Q: Retrieve values from JSON response, and create a drop-down I'm trying to get each of of the values inside my JSON file but when I run my API  I get [Object Object] instead of what is inside the JSON.
This is my API request:
getAllvalues(): Observable<string[]> {
    return this.http
      .get<string[]>(this.Url + 'api');
  }

my component.ts
this.ddvService.getAllvalues()
      .subscribe(response => {
        this.slots = response;
        console.log (this.slots)
      });

Example of my JSON response:
[
    {
        "AB": "http:"
    },
    {
        "DE": "http:"
    },
    {
        "CE": "http:"
    },
    {
        "HI": "http:"
    }
]

How can I get the value inside the JSON, and create a dropdown box with each of them?

A: Your example JSON is a pretty bad example: each object in the array in the JSON should have at least somewhat matching key names. In your case, the keys are "AB", "DE", "CE", "HI" - all different, which is quite uncommon in real-life. A more realistic JSON response would have matching key names, e.g.:
[
    {
        "id": "1",
        "description": "Some description"
    },
    {
        "id": "2",
        "description": "Another description"
    }
]

Now to answer your questions:
You are getting [Object Object] because you are trying to use an entire object as a literal value. Instead, you should access the individual keys/values of an object. For example: console.log(slots[0].id) - this should output 1.
Also, as indicated in the comments, replace Observable<string[]> with Observable<any[]> and get<string[]> with get<any[]>.
To create a drop-down in Angular, in your component template you can try this, assuming your slots value is the JSON above:
<select *ngIf="slots" name="slots">
  <option *ngFor="let slot of slots" value="slot.id">{{ slot.description }}</option>
</select>

Also, to print the entire object to console in a readable form, instead of just console.log(this.slots);, you can try console.log(JSON.stringify(this.slots));

A:
As mentioned in the comments above it is not ideal to have json like you have, my assumption is you might want to log keys instead of values, since value is same for all the objects in array. In that case you might want to try something like this.
  1. Add any[] instead string[].
  2.Add nested for loop to console.log your object array.

    getAllvalues(): Observable<string[]> {
       return this.http
    .get<any[]>(this.Url + 'api');
     }

   this.ddvService.getAllvalues()
     .subscribe(response => {
      this.slots = response;
      for(let i in this.slots)
       {
         let currentObj = this.slots[i]; // example of first in array { AB : "http:"}
          for ( let z in currentObj )
            {
             if(currentObj[z]=== "http:")  // we are trying to find key instead value
                {
                     console.log(z); // it will log AB, DE, CE, HI ..
                }
             }
        }
     });


text:
Q: limit uploaded files based on extensions in apache I have a site that has a place for upload files by I want to prevent users for upload files by .png and .gif files.
I test these config :
<FilesMatch "\.(png|gif)$">
allow from all
</FilesMatch>

<FilesMatch "\.(?<!png|gif)$">
deny from all
</FilesMatch>

Apache restrict file access to specific extensions, and allow directory index file to work also
but still can upload these extensions in my site.
could you please help?


text:
Q: Element wise matrix multiplication in Theano I could see element wise matrix multiplication using numpy can be done with * operator.
print np.mat(np.ones((10,10)))*np.mat(np.ones((10,10)))

But couldnt get it working under theano. The code I tried is
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x * y
f1 = theano.function([x, y], z)

print f1(np.mat(np.ones((10,10))),np.mat(np.ones((10,10))))

A: If I try the following (which is basically your code):
import theano
import theano.tensor as T

import numpy as np

x = T.dmatrix('x')
y = T.dmatrix('y')
z = x * y
f1 = theano.function([x, y], z)

print f1(np.mat(np.ones((10,10))),np.mat(np.ones((10,10))))

I get the following:
[[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]

So, it works for me.


text:
Q: SnakeYaml not using my setters I am trying to parse a YAML file with SnakeYaml in Java and I am struggling to make it build my model objects via the setters. What I understood from the SnakeYaml doc, is that when you use object that follow the JavaBean rules, SnakeYaml uses reflection to find setters and use them to instanciate members.
I shrunk down the code to the following minimalist version, and it still does not work as I would expect:
This is my model object :
public class Report {

    private String MainSourceFile;

    public Report() {
        super();
    }

    public String getMainSourceFile() {
        return this.MainSourceFile;
    }

    public void setMainSourceFile(String mainSourceFile) {
        this.MainSourceFile = mainSourceFile;
    }
}

This is the code that parses the YAML file :
Constructor constructor = new Constructor(Report.class);

Yaml yaml = new Yaml(constructor);
Report report = null;

try (InputStream str = new FileInputStream(file);) {
    report = (Report) yaml.load(str);
} catch (FileNotFoundException e) {
    throw new ParsingErrorException( String.format("Error while reading export file %s : file not found", file.getAbsolutePath()), e);
} catch (YAMLException e) {
    throw new ParsingErrorException(String.format("Error while parsing export file %s", file.getAbsolutePath()), e);
} catch (IOException e1) {
    Activator.logWarning(String.format("Error while closing file %s", file.getAbsolutePath()));
}

And this is the YAML file :
---
MainSourceFile:  /home/user/workspace/project/ex.c

The following error is thrown
Unable to find property 'MainSourceFile' on class: fr.xxx.xxx.model.Report
 in 'reader', line 2, column 18:
    MainSourceFile:  /home/user/workspace/project/ex.c
                     ^

    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:268)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.construct(Constructor.java:149)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructYamlObject.construct(Constructor.java:308)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructObjectNoCheck(BaseConstructor.java:207)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:196)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructDocument(BaseConstructor.java:161)
    at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:147)
    at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:524)
    at org.yaml.snakeyaml.Yaml.load(Yaml.java:452)
    at fr.xxx.xxx.ErrorParser.parseFixesExportFile(ErrorParser.java:116)
    ... 24 more
Caused by: org.yaml.snakeyaml.error.YAMLException: Unable to find property 'MainSourceFile' on class: fr.xxx.xxx.model.Report
    at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:189)
    at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:178)
    at org.yaml.snakeyaml.TypeDescription.discoverProperty(TypeDescription.java:240)
    at org.yaml.snakeyaml.TypeDescription.getProperty(TypeDescription.java:251)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:210)
    ... 33 more

If I declare the MainSourceFile member as public, the parsing works (that's why it begins with an upper case). But I'd prefer not to let it public and furthermore, I would like to use the setter.
I don't understand the reason why it does not use the setter : my Report class seems a legit JavaBean to me.
Is there anything else that I am missing?

A: MainSourceFile should be mainSourceFile.


text:
Q: Transforming lined data to grouped I have a question about transforming a data
if my data is like the following:
Variable A
130
130
130

Variable B
56
57
58

Variable C
1100
1200
1300

in a text file and I want to transform it into something like:
Variable A     Variable B    Variable C
130            56            1100
130  57   1200
130  58  1300

What should I do?

A: Your data is column centric, and SAS data sets are row centric, so a pivot will be required at some point.
The most generic process would:

*

*input data into many rows of name:value pairs

*

*compute a sequence value (row number) for each pair

*sort the input

*transpose by row.

Presuming all data is numeric, here is an example:
* construct a demonstration input data file;
* every data value in this construction is via +1 to allow
* examination of the reshaping;

filename havedata temp;

data _null_;
  file havedata;

  call streaminit(123);

  do varname = 'A', 'B', 'C', 'D', 'X', 'Y', 'Z';
    put 'Variable ' varname;
    do _n_ = 1 to 100 + rand('uniform',20);
      value + 1;
      put value;
    end;
  end;
run;

* read the demo file;

data want_input;
  infile havedata;

  length rownumber 8 name $32 value 8;
  retain name;

  input @;

  if _infile_ =: 'Variable' then do;                /* detect variable landmark in data file */
    rownumber = 0;
    name = substr(_infile_, length('Variable')+1);
    delete;
  end;

  rownumber + 1;
  input @1 value;
run;

proc sort data=want_input;
  by rownumber name;
run;

proc transpose data=want_input out=want(drop=_name_ rownumber);
  by rownumber;
  id name;
  var value;
run;

Things will more complicated if the data file variable 'blocks' are character or date representations.


text:
Q: Assign static IP in terraform vsphere_virtual_machine I am trying to add a vmware machine using vsphere, getting below error. I have followed this document. Terraform Document. I am giving default_ip_address. I am using latest version of terraform. Its a windows box. I am expecting this IP address associated with VM when provisioned. Template one network and IP related settings not valid as I am not using any template.
   resource "vsphere_virtual_machine" "vm" {

name             = var.name

resource_pool_id = var.resource_pool_id

datastore_id     = var.datastore_id

host_system_id   = var.host_system_id

folder = var.folder

cpu_hot_add_enabled = var.cpu_hot_add_enabled

enable_disk_uuid = "true"

enable_logging  = "true"

sata_controller_count = var.sata_controller_count

scsi_type = var.scsi_type

wait_for_guest_net_timeout = 5

wait_for_guest_ip_timeout  = 0

wait_for_guest_net_routable = true

default_ip_address = "172.16.16.109"

num_cpus = var.num_cpus

memory   = var.memory

memory_hot_add_enabled = var.memory_hot_add_enabled
network_interface {

network_id = data.vsphere_network.network.id

bandwidth_share_level  = var.bandwidth_share_level
}

disk {

label            = "disk0"

size             = var.disksize

thin_provisioned = "false"

eagerly_scrub    = var.eagerly_scrub

keep_on_remove   = "true"
}

cdrom {

client_device = var.client_device
}

custom_attributes = {

"${resource.vsphere_custom_attribute.attribute1.id}" = var.contact

"${resource.vsphere_custom_attribute.attribute2.id}" = var.application
}

}

Error: Computed attributes cannot be set
│
│ with vsphere_virtual_machine.vm,
│ on import.tf line 62, in resource "vsphere_virtual_machine" "vm":
│ 62: default_ip_address = "172.16.16.109"
│
│ Computed attributes cannot be set, but a value was set for
│ "default_ip_address".


text:
Q: Introduce branch into git history I have a repo that I would've liked to have branched a few commits again.
Let's say I have commits C1,C2,C3,C4,C5 on my master branch.
I want master to stop and C3 and C4 to start a new branch.
How would I go about making that happen? I've tried several different approaches but am not having any luck.

A: A branch is literally just a reference to a single commit.  Everything else you think about it is personfication.  Or arboreation.  If you want master to refer to commit C3, and a branch named "dev" to refer to commit C5, perhaps the easiest thing to do is:
git branch dev
git reset ${HASH_OF_C3}

The first command creates a branch at the current HEAD (C5).  The second resets the current branch (master) to commit C3.  After these commands, your working dir will be considered dirty (the contents of all the files are at commit C5, but you currently have the master branch checkout out, and it is at C3).  You can either checkout dev (git checkout dev), or clean it up (git reset --hard).  You could also add the --hard option when you first did reset.  Probably want to wind up with the 'dev' branch checked out, so maybe you instead want:
git checkout -b dev   # Create new branch at current commit
git branch -f master ${SHA_OF_C3}  # Make master refer to C3


text:
Q: When I submit a Spark job through Pyspark, how can I ensure which Python is used on the workers? Is it enough to make sure that PYSPARK_PYTHON is set in conf/spark-env.sh to point to the correct Python on those workers, or does something else need to be done as well?

A: sorry, I misunderstand your question...I think "PYSPARK_PYTHON" is good enough, if you want to double check then maybe you can try Chef or Puppet to deploy same environment (including python path) for all your masters and workers.

I'm not sure which version you are using, but latest 1.5.1, you can use web interface to monitor your job statusat
http://<server-url>:18080

http://<driver-node>:4040

You can access this interface by simply opening
  http://:4040 in a web browser. If multiple SparkContexts
  are running on the same host, they will bind to successive ports
  beginning with 4040 (4041, 4042, etc).

You can read more about Monitoring and Instrumentation


text:
Q: Using multiple iMacs (27 inch 2009) as displays I have 3 Apple iMacs (27 inch, 2009).
Is it possible to use two of those iMacs as displays for the other iMac?
If so, how do I achieve this?

A: It's possible to use an iMac as a secondary display of another iMac. You'll only be able to use one of your 'other' iMac's to do that.
To do so, you need to activate 'Target Display Mode' on the iMac you want to use as a display.

*

*Both iMac must be turned on and both must be logged 'in'.

*Connect the 'Mini DisplayPort' or 'Thunderbolt' cable between the two computers.

*Press 'Command + F2' on the keyboard of the iMac that you want to use as a
display.

Your target iMac will now display the desktop of the other, connected Mac. To exit TDM, just press Command + F2 again.
It will also exit if you disconnect the cable or shut down/sleep the other Mac.
Remark: this only works on iMacs up to 2014, The 5K Retina and newer ones don't support this.

A: If you are referring to Target Display mode, then you have to read Apple's website Use your iMac as a display with Target Display Mode. The system requirements are repleated below.


text:
Q: Android - Firebase FirebaseRemoteConfig#reset not working for A/B Testing config I create a Firebase A/B testing, and add a condition by UserProperty(eg: gender=male). When I change the condition (eg: gender=famale) and reset config cache with reset API, then fetchAndActive and call the getConfig function, value is still the previous value.
PS: Except clear data for this App, the config is always cache. I have a try with pure remote config and a user property condition, the same thing didn't happen.
Is reset API not working for A/B testing? how can I clear it.
Sample code:
    // 1. fetch the male config
    Firebase.analytics.setUserProperty("user_gender", "male")
    config.fetchAndActivate().addOnCompleteListener {
        val config = config.getString("test_by_gender")
        showText("fetchMaleConfig: $config(task success=${it.isSuccessful})")
        // will show male config
    }

    // 2. reset config
    config.reset()

    // 3. fetch the female config
    Firebase.analytics.setUserProperty("user_gender", "female")
    config.fetchAndActivate().addOnCompleteListener {
        val config = config.getString("test_by_gender")
        showText("fetchFemaleConfig: $config(task success=${it.isSuccessful})")
        // will show male config too
    }

My A/B testing config screenshot:


text:
Q: C64 loading screen thoughts I have made a loading screen (splash screen) just like the old C64.
I have used a series of picture boxes and just change the coloured image using a timer and a case statement.
switch (a)
{
    case 1:
        pictureBox1.Image = Properties.Resources.image1;
        pictureBox8.Image = Properties.Resources.image1;
        pictureBox10.Image = Properties.Resources.image1;
        pictureBox2.Image = Properties.Resources.image1;
        pictureBox11.Image = Properties.Resources.image1;
        pictureBox9.Image = Properties.Resources.image1;
        break;
    case 2:
        pictureBox1.Image = Properties.Resources.image2;
        pictureBox8.Image = Properties.Resources.image2;
        pictureBox10.Image = Properties.Resources.image2;
        break;
    case 3:
        pictureBox1.Image = Properties.Resources.image3;
        pictureBox8.Image = Properties.Resources.image3;
        pictureBox10.Image = Properties.Resources.image3;
        break;
    case 4:
        pictureBox1.Image = Properties.Resources.image4;
        pictureBox8.Image = Properties.Resources.image4;
        break;
    case 5:
        pictureBox1.Image = Properties.Resources.image5;
        pictureBox8.Image = Properties.Resources.image5;
        break;
    case 6:
        pictureBox1.Image = Properties.Resources.image6;
        pictureBox8.Image = Properties.Resources.image6;
        break;
    case 7:
        pictureBox1.Image = Properties.Resources.image7;
        pictureBox8.Image = Properties.Resources.image7;
        break;
    case 8:
        pictureBox1.Image = Properties.Resources.image8;
        pictureBox8.Image = Properties.Resources.image8;
        break;
}

its a bit nasty looking, how could I improve my code?

A: You could have a look at the Iterator design pattern.  You could create a class that represents a single stage, that class would have properties for each of the picture boxes and you would set the value of those properties to the relevant item in your resources file.
You then create instances of that object for each loading stage, put them in a collection and write an iterator to loop that collection.

A: There are a two things I'd improve:

*

*Store your images in an array, so you don't have to repeat case X/imageX every time.

*Handle the common stuff first, then concentrate on the special cases.
You can declare the array in your form as a "fake" constant, since it won't change:
private readonly static Image[] myImages = new[] {
    Properties.Resources.image1,
    Properties.Resources.image2,
    Properties.Resources.image3,
    Properties.Resources.image4,
    Properties.Resources.image5,
    Properties.Resources.image6,
    Properties.Resources.image7,
    Properties.Resources.image8
}

and then use the following code in your Timer hander:
Image image = myImages[a-1];

pictureBox1.Image = image;
pictureBox8.Image = image;

// special cases
if (a == 1)
{
    pictureBox2.Image = image;
    pictureBox11.Image = image;
    pictureBox9.Image = image;
}
if (a >= 1 && a <= 3)
{
    pictureBox10.Image = image;
}


text:
Q: Materialize CSS - Sidenav overlay covers all the page I am using Materialize css and I want to turn the navigation bar to sidenav in middle and small screens. I did it just like in the documentation. The problem is that when I click the menu button, sidenav is opened but it is like the image below

I am not able to click the links in the sidenav since the sidenav-overlay covers all the page even the sidenav itself. It is closing when I try to click a link. Any suggestions how to solve it?
HTML:

                menu

How It Works?

Technology

Pricing

More

<button class="waves-effect waves-light btn deep-orange">Request Demo</button>

How It Works?

Technology

Pricing

More

<button class="waves-effect waves-light btn deep-orange">Request Demo</button>

I realized that the navbar-fixed have z-index of 997 (where sidenav-overlay is also 997), and I think it may cause the problem. However, side-nav have fixed positioning and z-index of 999. Is it dependent to its parent even if it has fixed position?
Edit: I can solve it with changing the left property of sidenav-overlay, but I don't want to set it manually. I am looking for another solution.

A: I had the same problem.  Because
 is contained within
 and  the overlay has the same z-index, you will always have this problem when using navbar-fixed.
You can mess around with the z-indexes of the various elements, but they each result in less than ideal displays when the side-nav is activated.
To work around this, I put
 parallel in the document structure to
 and the problem resolved itself.  Like this:

How It Works?

Technology

Pricing

More

<button class="waves-effect waves-light btn deep-orange">Request Demo</button>

        menu

How It Works?

Technology

Pricing

More

<button class="waves-effect waves-light btn deep-orange">Request Demo</button>

A: Modify the materialize CSS file to change the #sidenav-overlay to
#sidenav-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 120vh;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 996;
    will-change: opacity;
}

A: Modify the materialize CSS file to change the z-index in #sidenav-overlay to be 990. This solved the problem for me.

A: I had the same problem, and the fix is far easier than messing with any z-index.  Simply make sure that your actual

content is outside of the  tags.  If it's inside the header tags, you will see the same behavior you posted here.
In my opinion this is the fault of the otherwise-great Materialize documentation.  They do make clear that the sidenav HTML should not be contained within the  tags, but don't indicate it won't work inside of the header tags.
In sum, your trigger needs to be within the  tags, and your actual sidenav content defined after the end of .  This is better than fiddling with z-index as that could break other things down the line and becomes a maintenance headache.


text:
Q: Getting connection refused error on authentication ASP.NET Core 5 I am following this tutorial to make google authentication with Angular and ASP.NET Core:
https://levelup.gitconnected.com/how-to-sign-in-with-google-in-angular-and-use-jwt-based-net-core-api-authentication-rsa-6635719fb86c
But I'm getting a "connection refused" error in the ASP.NET Core side.
Here is my Angular component:
import { Component } from '@angular/core';
import { SocialAuthService  } from 'angularx-social-login';
import { SocialUser } from 'angularx-social-login';
import { GoogleLoginProvider } from 'angularx-social-login';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user: SocialUser | null;
  hasApiAccess = false;

  constructor(private authService: SocialAuthService, private http: HttpClient)
  {
    this.user = null;
    this.authService.authState.subscribe((user: SocialUser) => {
      console.log(user);
      if (user) {
        this.http.post<any>('http://localhost:5001/user/authenticate', { idToken: user.idToken }).subscribe((authToken: any) => {
          console.log(authToken);

          let reqHeader = new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + authToken.authToken
          });
          this.http.get<any>('http://localhost:5002/secured', { headers: reqHeader }).subscribe((data: any) => {
            this.hasApiAccess = true;
          })
        })
      }
      this.user = user;
    });
  }

  signInWithGoogle(): void {
    this.authService.signIn(GoogleLoginProvider.PROVIDER_ID).then((x: any) => console.log(x));
  }

  signOut(): void {
    this.authService.signOut();
    this.hasApiAccess = false;
  }
}

The controller is as follows:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;

namespace GoogleAuthRest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SecuredController : Controller
    {
        [Authorize]
        [HttpGet]
        public string Test()
        {
            return "ok";
        }
    }
}

And the startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using Microsoft.Extensions.Options;

namespace GoogleAuthRest
{
    public class Startup
    {
        //configure barer token
        public class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions>
        {
            public void Configure(string name, JwtBearerOptions options)
            {
                RSA rsa = RSA.Create();
                rsa.ImportRSAPublicKey(Convert.FromBase64String(PUBLIC_KEY), out _);

                options.IncludeErrorDetails = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new RsaSecurityKey(rsa),
                    ValidateIssuer = true,
                    ValidIssuer = "AuthService",
                    ValidateAudience = true,
                    ValidAudience = "GoogleAuthRest",
                    CryptoProviderFactory = new CryptoProviderFactory()
                    {
                        CacheSignatureProviders = false
                    }
                };
            }

            public void Configure(JwtBearerOptions options)
            {
                throw new NotImplementedException();
            }
        }
        //end

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // configure Angular client
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAngularDevClient",
                  builder =>
                  {
                      builder
                      .WithOrigins("http://localhost:4200")
                      .AllowAnyHeader()
                      .AllowAnyMethod();
                  });
            });
            //end

            // Add authentication tokens
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer();
            //end

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "GoogleAuthRest", Version = "v1" });
            });

            // This is the tricky part to inject the configuration so the public key is used to validate the JWT
            services.AddTransient<IConfigureOptions<JwtBearerOptions>, ConfigureJwtBearerOptions>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "GoogleAuthRest v1"));
            }

            //app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors("AllowAngularDevClient");
            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        private const string PUBLIC_KEY = @"MIICCgKCAgEAtCR2Pii+q9C76P2E9ydHYxnBPjJFGT7MvHuQPKpcS9RImfrkobt0
        LPS/406eWm/tRBvnYD9nDpHJNKN3TjEenFQuDGR4RHcGK/e43SAhTAi7+s0tfAQd
        6BK4gznIwvs5cWyilh1B7c9sCnxhJ/EYLIe1N2yiD8mhvfojIF4vMYxONIMTGYXy
        87lnO9zRAdXAZ39YbtmFmQwK8gfXX5d/XVlKy0tc2y5bRY5iXn9kwqwvFlzL6O4v
        pjhqA5kwsJV7efhL9nU0ACR4dG3zwFR3SAOOSETXjnfmjH2ocga+oa65ToypUz2L
        1DwnNHt+M5CtDJ9um4dbYaqfBWkjWe3FuGB0GNPS8pbX2nVt76OfHA/QKmxTWvFd
        POZnjpg2QhDujyXgoIY731zx5bAklKVoKFma/qfWfCyCSTUzhgu1KQm9swipMsQy
        NYr9CjbnIlPn4EvrBIbGcIiaRNCLCIlcAuxE/GiH1zBUfeJxfJQmurejp6mBAtAS
        FY08DmUebBz8mlUbB+LXMYKHZ4GK6TecPy0WJU2qRMQ//PKfOa+wkesp4M53SQdp
        ItDp5akTzYUo4rXwk3HPCtemKaSNhyG+EYtZ1CAmPN5sEjU0/x0Dq7SU5o8KhogB
        m/5HRJ3M9dMRcwD3OcsMl0kW1PPUt04itboS3SlFav90V9uc2YNGpPsCAwEAAQ==";
    }
}

May be someone has read this article and is able to help me with that...
I also tried to comment out validateAudience. This did not help

A: Maybe your cors policy was not created the right way.
Use:-
services.AddCors(options =>
            options.AddPolicy("AllowAngularDevClient", builder => builder
                .WithOrigins("http://localhost:4200")
                .AllowAnyHeader()
                .AllowAnyMethod())
        );

instead of:-
services.AddCors(options =>
            {
                options.AddPolicy("AllowAngularDevClient",
                  builder =>
                  {
                      builder
                      .WithOrigins("http://localhost:4200")
                      .AllowAnyHeader()
                      .AllowAnyMethod();
                  });
            });

Or you can normally use:-
 services.AddCors();

then your configure service:-
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200"));

hope it will resolve your issue.


text:
Q: Elastic search bulk index with C# API I want to bulk index json records to elastic search with NEST or Elasticsearch.Net API
My json data is :
{"index":{"_index":"abc","_type":"abc","_id":1}},{"Name":"ApplicationFrameHost","CPU":1.25,"Company":null,"Product":null,"Path":null},{"index":{"_index":"abc","_type":"abc","_id":2}},{"Name":"Calculator","CPU":0.5,"Company":null,"Product":null,"Path":null},{"index":{"_index":"abc","_type":"abc","_id":3}},{"Name":"chrome","CPU":142.9375,"Company":null,"Product":null,"Path":null},{"index":{"_index":"abc","_type":"abc","_id":4}},{"Name":"chrome","CPU":3336.34375,"Company":null,"Product":null,"Path":null},{"index":{"_index":"abc","_type":"abc","_id":5}},{"Name":"chrome","CPU":7.1875,"Company":null,"Product":null,"Path":null}\n\n

my code:
 var connectionSettings = new ConnectionSettings(new
 Uri("http://localhost:9200/"));

        var client2 = new ElasticClient(connectionSettings);
       var jsonPostData = new PostData<object>(myJson);
        var bulkRequestParameters = new BulkRequestParameters
        {

        };
  Func<BulkRequestParameters, BulkRequestParameters> convert = delegate
  (BulkRequestParameters s)
        {
            s.ErrorTrace(true);

            return s.Refresh(Refresh.True);
        };

        var response = client2.LowLevel.Bulk<VoidResponse>("abc", "abc",
        jsonPostData, convert);

In the response elastic return success with no error but still, data is not available on elastic?
Debug info from elastic:Successful low level call on POST: /abc/abc/_bulk?error_trace=true&refresh=true
It would be very helpful if someone can provide any clue what I am doing wrong here?

A: Solved this by modifying input JSON format after each record-set it does not requires comma:
{"index":{"_index":"abc","_type":"abc","_id":1}}{"Name":"ApplicationFrameHost","CPU":1.25,"Company":null,"Product":null,"Path":null}{"index":{"_index":"abc","_type":"abc","_id":2}},{"Name":"audiodg","CPU":1.5625,"Company":null,"Product":null,"Path":null}{"index":{"_index":"abc","_type":"abc","_id":3}},{"Name":"Calculator","CPU":0.5,"Company":null,"Product":null,"Path":null}{"index":{"_index":"abc","_type":"abc","_id":4}},{"Name":"chrome","CPU":144.109375,"Company":null,"Product":null,"Path":null}{"index":{"_index":"abc","_type":"abc","_id":5}},{"Name":"chrome","CPU":3384.609375,"Company":null,"Product":null,"Path":null}


text:
Q: How to force the Sass interpreter to output non-css code? I need to include some non-css interpreter instructions in a css file (these will be substituted later by another parser at runtime to create valid css).
The file is written in scss, so I use ruby/node sass to compile the file. During this process, I want it to leave the interpreter instructions untouched, i.e. they should be simply treated as literals and outputted. The instructions contain symbols that are not valid in css, so the answer given here doesn't work for me.
What works fine is when the variable containing the insruction is referenced in a property value, so e.g. this compiles successfully:
$x: unquote("<<macro 'val1'>>");

a {
  b: $x; // compiles into:  b: <<macro 'val1'>>
}

This fails:
$x: unquote("<<macro 'val1'>>");

@media (max-width: #{$x}) { // throws an invalid css error
  .tc-sidebar-scrollable {
    .tmap-desktop-editor {
      display: none;
    }
  }
}

In both cases, the output will not be valid css but in case of the media query, it completely fails. My Sass version is 3.4.13 (Selective Steve).
How can I get this to work? The resulting file should look like:
@media (max-width: <<macro 'val1'>>) {
  .tc-sidebar-scrollable .tmap-desktop-editor {
    display: none;
  }
}

A: I did a cross post at the sass GitHub repo and was told that interpolation happens before the media query is parsed, which is why it doesn't work here.
A possible (but still unsatisfying) workaround that came up in the issue discussion was to use custom at-rules to "get around Sass' proprietary handling of @media". So you would write e.g.
@_media (max-width: #{$x})

and after sass compiled you run a replace script that transforms @_media into @media.
Another similar idea was to use a css-valid placeholder for the non-valid css itself and later replace it in a second run after sass finished with the desired string…


text:
Q: Debug node_module with source map in Create React App application I'm implementing a react library and bundling it with rollup, which is properly generating the source map and linking it to the bundle.
For testing purposes, I have a react application generated with create-react-app, which is making use of my library. And After npm installing my dependency, I can see the bundle and the source maps located in node_modules directory.
Problem comes when I run it with npm start. Apparently the browser doesn't have access to the source map and I can only debug using the bundled version of my library.
Is there a way to debug a node_module of a CRA application, using its original source map without having to eject?


text:
Q: How can I call a dictionary with user input I'm new to programming. My project is a credit card award points optimizer written in Python 3. I have a few dictionaries based on spending categories, with the keys/values representing my credit cards and their point multiplier for that category.
After showing the user the categories, it asks them to input which one they want to make a purchase in, and here's where I'm getting an error because the input is a string and my dictionary is a variable.
How can I convert the string into a variable, so that I can print the keys/values?
Example category and list of categories
dining = {'amex': '4x points'}
categories = ['dining', 'grocery']

input and call script
purchase_type = input('Which category is it?: ')
for category in categories:
            if purchase_type == category:

A: You can put your various category dictionaries into a dictionary themselves. Then you can just plug the input like selected = categories[theirInputVariable]


text:
Q: how to configure aws code deploy with jenkins In Jenkins, I want to deploy the code automatically when the build is success. I had installed aws code deploy plugin in Jenkins but not able to configure with Jenkins. Any idea?

A: After building and installing the plugin, some simple configuration is needed for your project.
*Open up your project configuration
*In the Post-build Actions section, select "Deploy an application to AWS CodeDeploy"
*Application Name, Deployment Group, Deployment Config, and region are all required options.
*For authentication, there are two options. Either option requires that the associated role has, at minimum, a policy that permits codedeploy:* and s3:Put*. The plugin will pick up global credential from the jenkins instance.


text:
Q: How to get AD information for an AWS EC2 instance from AWS sdk for .NET When importing AWS ec2 instances from AWS using their SDK, there is a unique field called the Instance ID. This information is specific to Amazon. Some of these instances can be part of the domain too. Can I get the AD Object GUID during this AWS import?
Or is there another field that I can use to link the AWS instance imported from AWS with the instance imported from AD?

A: I am sure you cannot get the AD GUID using AWS SDK unless you store it as an instance tag. Because all instance attributes are specific to AWS. Without knowing how AD GUID is linked to AWS instance id, it is difficult to comment.
The simplest solution is to tag the instance (like tag:AD_GUID=<GUID>) when launching (or after launching) the instance. Then using AWS SDK, you can get the AD GUID of the instance form instance's attributes.


text:
Q: Normalize an array of numbers to specific range How can I normalize an array of values (e.g., {0, 3, 4, 7, 9, 13, 22}) to a range of [12, 24]?

A: @NickCox already provided an answer in the comments, I will only elaborate on it step-by-step and try to provide some intuition.
You have a range on numbers ranging from $x$ to $y$ and you want to transform it into some interval $x_{new}$ to $y_{new}$.
You can think about this in three steps:

*

*1st transform the numbers to have a range from 0 to $z$.

*2nd transform the range 0 to $z$ into a range 0 to 1.

*3rd transform the range 0 to 1 to $x_{new}$ to $y_{new}$.

1st step
Subtract the minimum value from each number in your array. This will force the minimum to become 0. Note that it works even if your data has negative numbers! If your minimum number is -10 after subtracting -10 it will become 0 and all the others will be higher than 0.
2nd step
Now your numbers have a range of 0 to some positive number $z$. 2nd step is dividing all the numbers by $z$. Since the maximum number is $z$ - when you divide it by $z$ it will become 1. And your minimum number is 0 and when you divide 0 it will remain 0. So after this procedure all your numbers will be in a range of 0 to 1.
3rd step
We are transforming to a range from $x_{new}$ to $y_{new}$. This will involve two steps: First is to transform the range we have now (0 : 1) to (0 : ($y_{new} - x_{new}))$. And then we will add $x_{new}$ to obtain the final result of $x_{new}$ to $y_{new}$
Example
Let's transform your numbers ${0, 3, 4, 7, 9, 13, 22}$ to a range $12-24$.
First we see that the minimum number is $0$. We subtract $0$ from every number and we get the same numbers as a result.
Second - the maximum is $22$ - so we divide every number by $22$ and we get these numbers: $${0.00, 0.14, 0.18, 0.32, 0.40, 0.59, 1.00}$$
Third - we transform them at first to a range of $0-12$ (the idea is that after this we add $12$ and we get a range $12-24$). To do that - we multiply every number by $12$. And we get these numbers: $${0.00,  1.64,  2.18,  3.82,  4.91, 7.09, 12.00}$$
Finally we add 12 to all the numbers and the final result is:
$${12.00, 13.64, 14.18, 15.82, 16.91, 19.09, 24.00}$$


text:
Q: Class Library Connection String Confusion I have managed to confuse myself... not difficult, I know, and am looking for some guidance...
I have written a dll which I am now starting to use in my Winforms UI.
This is a follow on question to this:
Class Libray Connection String - How to change?
As told in that post, I have added the identical connection string settings from the app.config in the dll to my App.config in my UI.
In my UI, I have a text box where the user can enter the connection string and hit "Save", which runs the following code:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString = txtConnectionString.Text;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

Which seems to update the string in the file correctly.
But, and this is where the previous posting confuses me...
That setting only gets read when the software starts. Somehow I need to change the setting which Belogix has explained I should do like this:
var connectionString = "Data Source=MegaServer;Initial Catalog=MyDb; .. etc ..";
using (var db = new MyDataContext(connectionString))
{
   // This will connect to MegaServer...
}

But, I am calling functions in my dll like this:
List<Page> pages = Database.getlistOfPagesToScan();

How do I tell that call to start using the newly saved connection string from the UI's App.config?
Can anyone shed any light?
Thanks

A: You should get the connection string from the settings in the dll. Your answer is actually in the question you post.
Use this:
var connectionString = config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString;

You can also use this:
string s = Properties.Settings.Default.ConnectionStr;
Console.WriteLine("Connection string from main app: " + s);

//
// When setting access modifier on Class library to `public`
//
s = ClassLibrary1.Properties.Settings.Default.ConnectionStr;
Console.WriteLine("Connection string from dll: " + s);

A: Assuming you are using ConfigurationManager to retrieve the application connection strings, try:
ConfigurationManager.RefreshSection("connectionStrings");


text:
Q: While using the google_mlkit_object_detection package i'm able now to detect objects in an image and using the image package i can crop them but While using the google_mlkit_object_detection package i'm able now to detect objects in an image and using the image package i can crop them but whats happening that the image package force me to add an image in order to add the cropped one to it. and that's the problem because i have one image with 3 objects for example the result should be 3 cropped images with the help of image package but this package is asked me to add image for the cropped one to add.
 void addRectImages() {
for (int i = 0; i < finalCroppedImage.length; i++) {
  File i = File(mainImage!.path);
  addFiles.add(i);
}

// File one = File(croppedImage!.path);
// addFiles.add(one);
// File two = File(mainImage!.path);
// addFiles.add(two);

for (int i = 0; i < finalCroppedImage.length; i++) {
  // print(finalCroppedImage[i].height);
  addFiles[i].writeAsBytesSync(encodePng(finalCroppedImage[i]));
  // addFiles[1].writeAsBytesSync(encodePng(finalCroppedImage[1]));

}

}
and what's happening finally that the all cropped images will be the same result because i used the same image first here (File i = File(mainImage!.path);)


text:
Q: Streaming JSON data saving as Parquet in S3 I've a Kinesis stream producing JSON and wanted to use Storm to write to S3 in Parquet format. This approach will require conversion from JSON --> Avro --> Parquet during stream processing. Also, I need to deal with schema evolution in this approach and keep updating avro schema and avsc generated java classes.
Another option is directly writing JSON in S3 and use Spark to convert stored files to parquet. Spark can take care of schema evolution in this case.
I would like to get pros and cons of both of the approaches. Also, is there any other better approach that can deal with schema evolution in json-->avro-->parquet conversion pipeline?


text:
Q: Server-Side Paging MVC 6.0 I have MVC project with WCF service.
When I display a list of data, I do want to load everything from the database/service and do a client paging. But I do want a server-side paging. If I have 100 records and my page size is 10, then when a user clicks on page 1, it will only retrieve the first 10 records from the database and if a user clicks on Page 3, then it will only retrieve the corresponding ten records.
I am not using Angular or any other bootstrap.
Can someone guide me how to do it?
  public ActionResult Index(int pageNo = 1)
    {
        ..
        ..
        ..

        MyViewModel[] myViewModelListArray = MyService.GetData();

        //when I create this PageList, BLL.GetData have to retreive all the records  to show more than a single page no.
        //But if the BLL.GetData() was changed to retrieve a subset, then it only shows a single page no.
        //what I wanted to do is, show the correct no of pages (if there are 50 records, and pageSize is 10, then show
        //page 1,2,3,4,5 and only retrieve 10 records at a time.
        PagedList<MyViewModel> pageList = new PagedList<<MyViewModel>(myViewModelListArray, pageNo, pageSizeListing);
        ..
        ..
        ..
        return View(pageList);
    }

A: The best approach is to use LINQ to Entities operators Skip & Take.
For example, to page
int items_per_page = 10;
MyViewModel[] myViewModelListArray = MyService.GetData().OrderBy(p => p.ID).Skip((pageNo - 1) * items_per_page).Take(items_per_page).ToArray();

NOTE: The data must be ordered, so the pages have some consistency (but I did by an arbitrary field ID). Also some databases required 'order by' to apply 'limit' or 'top' (which is how Take/Skip are implemented).
I put it that way, because I dont know how you are retrieving the data.
But instead retrieving the full list with GetData and then filtering out, better include the pagination in the query inside GetData (so you don't retrieve unnecessary data).

A: Add paramters page size and page number to your service method and make the result an object which returns TotalCount and a List Items (Items being the items on the current page). Then you can use those values to create the PagedList.
Inside your business logic code you will do two queries one for the count of items and one for the items on the page.
Also if you are starting the project now do yourself a favor and remove the useless WCF service from your architecture.


text:
Q: Button click calls panel method without arguments I have JFrame and inside that I have JPanel and inside of that I have one button. And when I click I want it call some method with I specify. Is that somehow possible without parameters?
This is how I have done it until now:
JFrame frame = new JFrame("");
JPanel container = new JPanel();
frame.add(container);

JButton button = new JButton("Button");
button.addActionListener( e -> mySpecialMethod());  // I have to create action performed method with has ActionEvent as parameter.

...
Is there a simpler way? It seems redundant to do it all the time. Something like button.addActionListener(Foo::bar); and public void bar(){....}

A: You can use method reference here only if your method has an ActionEvent parameter:
button.addActionListener( this::mySpecialMethod );

void mySpecialMethod( ActionEvent e ) { ... }

If your method has no parameter, then interface signature and method signature don't match, so you will have a compilation error. Probably that's a matter of taste, but for me e -> mySpecialMethod() looks not very redundant (especially compared to anonymous classes I had to use prior to Java 8).


text:
Q: UnsatisfiedLinkError when using GvrLayout I'm developing a Google VR app with the NDK and my activity includes the following code:
if (gvrLayout.setAsyncReprojectionEnabled(true)) {
  AndroidCompat.setSustainedPerformanceMode(this, true);
}

This compiles, but when I try to run the app, I get the following error:
java.lang.UnsatisfiedLinkError: No implementation found for
  boolean com.google.vr.ndk.base.GvrApi.nativeUsingVrDisplayService(long)
    (tried Java_com_google_vr_ndk_base_GvrApi_nativeUsingVrDisplayService
     and Java_com_google_vr_ndk_base_GvrApi_nativeUsingVrDisplayService__J)
  at com.google.vr.ndk.base.GvrApi.nativeUsingVrDisplayService(Native Method)
  at com.google.vr.ndk.base.GvrApi.usingVrDisplayService(SourceFile:952)
  at com.google.vr.ndk.base.GvrLayout.setAsyncReprojectionEnabled(SourceFile:610)

When I remove that section of code, the app runs without a problem. I'm including sdk-common-1.10.0.aar in my build. Do I need something else?


text:
Q: Sequelize And / Or Operators I want to reproduce this query in Sequelize:
SELECT name FROM table WHERE id = 5 AND (login = 1 OR register = 1)

I was looking on docs and here's my currently code:
Model.findOne({
        where: Sequelize.and({
            id: 5
            }, Sequelize.or({
                login: 1,
                register: 1
            })
        )
    })

But it's not working. I'm pretty new in Sequelize, hope anyone can help me.

A: try like this:
Model.findOne({
    where: Sequelize.and({
        id: 5
        }, Sequelize.or(
               {login: 1},
               {register: 1}
           )
    )
})


text:
Q: XAMPP access forbidden issues Having issues with XAMPP and access forbidden problems.
Started using laravel, complete noob to anything MVC but thought I'd give it a go.
Started having issues with page routing, index page works fine, yet non of my routes work, all come up with a 404 error.
Have a little search around the internet, find out it could be due to my xampp/Apache config.
Had a play with the
Allow from all

and
Require all granted

options, but no dice.
This is my vhosts entry:
<VirtualHost *:80>
    DocumentRoot "C:\Users\xxx\Desktop\Projects\xxx\Website-3.0\Website\public"
    ServerName gw3.dev
    <Directory "C:\Users\xxx\Desktop\Projects\xxx\Website-3.0\Website\public">
        Allow from all
        Require all granted
        Options Indexes
    </Directory>
</VirtualHost>

and this is what I edited in the httpd.conf file.
<Directory />
    Require all granted
    Options FollowSymLinks
    AllowOverride All
    Allow from all
</Directory>

Made sure that the root directory is not read only.
Yet all I get are 403 - forbidden access errors.
Running Windows 10, fyi.
Not really sure where I'm going wrong here. Is there something I'm missing?

A: This section
<Directory />
    Require all granted
    Options FollowSymLinks
    AllowOverride All
    Allow from all
</Directory>

Provides the basic security for the disk that Apache is installed on. Basic practice is deny access to everything and then allow access to only those directories that Apache should have access to. Also you are using Pache 2.2. and 2.4 syntax together, bad.
So change that back to :-
<Directory />
    AllowOverride none
    Require all denied
</Directory>

In the definition of the virtual host you are using both Apache 2.2 and 2.4 syntax. Thats not a good idea it can cause Apache to get confused. Also you are using the DOS back slash and that should be the unix forward slash.
So try this
<VirtualHost *:80>
    DocumentRoot "C:/Users/xxx/Desktop/Projects/xxx/Website-3.0/Website/public"
    ServerName gw3.dev
    <Directory "C:/Users/xxx/Desktop/Projects/xxx/Website-3.0/Website/public">
        AllowOverride All
        Options Indexes FollowSymLinks
        Require all granted
    </Directory>
</VirtualHost>

If you dont actually intend to allow anybody in the universe to access this site then you can use
Require local

Or if you want to access the site from another device in your local network you could try
Require ip 192.168.1

Note use of only 3 of the 4 quartiles of the IPV4 ip address. This allows access from any ip in that subnet.
Also make sure that you have added gw3.dev to your HOSTS file for both IPV4 and IPV6 addresses
127.0.0.1 gw3.dev
::1  gw3.dev

Retart Apache and try that.

A: You need
 AllowOverride All

too in vhost
also dont forget to reboot the server


text:
Q: How to get timezone offset from the date getting from client side? I am working with nodejs. I am getting the startDate as
startDate: '2020-06-14T18:30:00.000Z'

from the client side. I need to get the timezone offset from the above date. It should be +05:30. How can I get that?
Edit:
Server always works on UTC. So can I get the timezone offset by subtracting the date coming from the client by the UTC one?
i.e.
'2020-06-14T18:30:00.000Z' - moment.utc().startOf("day") = +05:30

A: If the node.js syntax is the same as plain JS; declare a date object with:
var date = new Date();

then use the getTimezonOffset method to get the difference in minutes to GMT.:
var difInMinutesToGMT = date.getTimezoneOffset();

From there on it's a matter of converting the positive/negative minutes into the format you want.

A: the date you have is in universal central timezone UTC supposing you have that datestring  on your client, you can use
from moment.js moment.utc(datestring).utcOffset()
to get the offset from that string, I think the return value is in minutes.
Edit: thank you for clarifying, the Z at the end of your datestring means that the date is already in UTC time zone. If you want to have a timezone offset, you will always get 0. you could possibly send as well the locale from the client using moment.tz.guess() and send the timezone as well to the server. or simply like others have stated, use on client side the Date.prototype.getTimezoneOffset method:

The getTimezoneOffset() method returns the time zone difference, in
  minutes, from current locale (host system settings) to UTC.

A: You can use this below method in order to get the offset in the required format.

let d = '2020-06-14T18:30:00.000Z'
let date = new Date(d);
let offsetInMinutes = date.getTimezoneOffset()
let formattedOffset = `${parseInt(offsetInMinutes/60)}:${Math.abs(parseInt(offsetInMinutes%60))}`
console.log(formattedOffset)

A: You cannot get the user's time zone.
User/Client sent you date-time in ISO8601 format, or to be more precise Zulu time (UTC).
You might consider 2 options:

*

*Forcing clients to send you time in a format which will include their timezone and grab it from there ('2020-06-14T19:30:00.000+01:00') - more like a workaround

*Or to have user preferences in you database where you will have their zone (somehow stored there, via dedicated endpoint or so...) - cleaner solution

Answering to edit:
moment(''2020-06-14T18:30:00.000Z').substract(moment.utc().startOf("day")).toHours() == 18.5

moment('2020-06-14T19:30:00.000+01:00').substract(moment.utc().startOf("day")).toHours() == 18.5

So, the timezone flag (Z, 01:00...) will just give info about timezone of given date-time. The client can send any of variation and it's valid. And in the end you still don't know clients timezone.
My 1st is just a workaround, but I wouldn't suggest you do that, that might be a hotfix, but 2nd is a more appropriate solution.
Anyway:
Sometimes, server/API/be doesn't have to know users timezone at all, if that is used just for read/write (because client app, will adjust ZULU time to the client zone in the UI and vice versa), but when you have some logic, for example google calendar features you will need user timezone for sure.


text:
Q: What photo management application can I migrate to that would preserve iPhoto's face detection data? I've used iPhoto for many years and found that it was suitable for what I wanted to do. Since Apple has discontinued iPhoto and Aperature in favor of their new Photos application, I'm seriously considering switching applications for my photo management since I'm just not happy with the direction they're taking the software. All well and good, but the annoying thing is that I've spent hours of my time working with the face detection feature of iPhoto and I'd hate to lose all the work tweaking the exception cases (i.e. iPhoto couldn't make out who someone was and I had to manually tell it).
For what its worth, I'm still on iPhoto '09 as iPhoto '11 didn't seem like that much of an improvement to me; in fact, the removal of the LAN sharing and obfuscated context menu items (e.g. reveal in finder type functions) stopped me from upgrading.
Are there any applications out there which I can migrate to which would preserve all the face data from iPhoto '09?

A: I haven't used it yet, but apparently the new Photos app will continue the face detection or 'Faces' work they've had for some time in iPhoto and Aperture:
http://www.cheatsheet.com/technology/how-apple-is-reinventing-iphoto-with-the-new-mac-photos-app.html/?a=viewall


text:
Q: compute complex laplacian using computer program I want to compute the laplacian of some complicate function, for example $|f''(z) + f'(z)\frac{1}{1-|f|^2}|\frac{1-|z|^2}{1-|f|^2}$ assuming $f$ is smooth and then evaluate it at $0$. I wonder whether there is some computer software that can help me with this.
We know that laplacian $\Delta$ is just multiples of $\partial_{\bar z z}$, then one approach would just be that denote the conjugate of $f(x)$ by $g(y)$, and then ask wolfram alpha to compute $\partial_{y x}$, this works out fine if we only have some simple functions, when the function becomes a little bit more complex, wolfram alpha will not give you any output.
One problem with matlab is that you have to specify the function.

A: I would consider looking at MatLab. I know they have a free trial that you could use to try it out. I have never tried though so I'm sorry if this doesn't help.


text:
Q: create a timer using react hooks I'm going to building a count down timer in my website.
my end time comes from server (it's a number like this: 10500 (which means it's 10500 minutes till the timer finish))
i can't do this, is there anybody who can help me?
const [times, setTimes] = useState({ days: 0, hours: 0, minutes: 0, seconds: 0 });
const [timeToReserve, setTimeToReserve] = useState(props.reserveData.ToReserve);

React.useEffect(() => {
    timeToReserve > 0 && setTimeout(() => checkTime(), 1000);
}, [timeToReserve]);

const checkTime = () => {
    let minutesToReserve = timeToReserve - 1
    setTimeToReserve(minutesToReserve)

    let days = Math.floor(minutesToReserve / (1000 * 60 * 60 * 24));
    let hours = Math.floor((minutesToReserve % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((minutesToReserve % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((minutesToReserve % (1000 * 60)) / 1000);

    setTimes({ days, hours, minutes, seconds })
}

A: Something like this should work:
import React, {useState, useEffect} from 'react';

const CountDown = ({ reserveData }) => {
    const [secondsLeft, setSecondsLeft] = useState(reserveData.ToReserve * 60);

    useEffect(() => {
        const countDownTimeout = setTimeout(() => {
            // Stop in case the time is over
            if (secondsLeft > 0) {
                return setSecondsLeft(seconds => seconds - 1);
            }
            clearTimeout(countDownTimeout);
        }, 1000);

        // Clean up if unmounted
        return () => clearTimeout(countDownTimeout);
    }, [secondsLeft]);

    const days = Math.floor(secondsLeft / (60 * 60 * 24));
    const hours = Math.floor((secondsLeft % (60 * 60 * 24)) / (60 * 60));
    const minutes = Math.floor((secondsLeft % (60 * 60)) / 60);
    const seconds = Math.floor(secondsLeft % 60);
    return (
        <p>
            {days} days, {hours}:{minutes}:{seconds}
        </p>
    );
};

export default CountDown;

You could use this component like:
<CountDown
    reserveData={{ToReserve: 24 * 6 * 60}}
/>


text:
Q: Difference between ng-bind, ng-bind-html, ng-bind-html-unsafe in AngularJS? I want to know difference between ng-bind, ng-bind-html and ng-bind-html-unsafe.
Also when I run below code, I am getting error which is as mentioned below :
Code :
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTML Injection Security in AngularJS</title>

    Normal Text

Error :

Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
      http://errors.angularjs.org/1.3.11/$sce/unsafe
          at REGEX_STRING_REGEXP (https://www.angularapprj.com:4443/js/angular.js:63:12)
          at htmlSanitizer (https://www.angularapprj.com:4443/js/angular.js:15053:13)
          at getTrusted (https://www.angularapprj.com:4443/js/angular.js:15217:16)
          at Object.$get.sce.(anonymous function) [as getTrustedHtml] (https://www.angularapprj.com:4443/js/angular.js:15897:16)
          at Object.ngBindHtmlWatchAction [as fn] (https://www.angularapprj.com:4443/js/angular.js:20449:29)
          at Scope.$get.Scope.$digest (https://www.angularapprj.com:4443/js/angular.js:14230:29)
          at Scope.$get.Scope.$apply (https://www.angularapprj.com:4443/js/angular.js:14493:24)
          at bootstrapApply (https://www.angularapprj.com:4443/js/angular.js:1449:15)
          at Object.invoke (https://www.angularapprj.com:4443/js/angular.js:4182:17)
          at doBootstrap (https://www.angularapprj.com:4443/js/angular.js:1447:14)

What does it mean? I know using declarative code within imperative code is not good practice, though I was just trying with Hello World in ng-bind-html directive.

A: After searching I got below information from https://docs.angularjs.org/guide/migration#ngbindhtmlunsafe-has-been-removed-and-replaced-by-ngbindhtml: In Angular version 1.3 they have migrated from ng-bind-html-unsafe to ng-bind-html, though one point of question is remaining,Why I am getting error which is mentioned in post ?


text:
Q: Import path was added as an Endpoint I am a newbie in Javascript. How can I import in javascript with node js?.
I imported A custom Element:
import UserView from "./Component/UserView";

window.customElements.define("user-view", UserView);

Then get this error:
GET http://localhost:4000/Component/UserView net::ERR_ABORTED 404 (Not Found)

I can just use res.sendfile in node js to send the file (if its possible). It seems the path was added as an endpoint instead. I would like to import it directly but instead I got the error. Any help would be appreciated.

A: Instead of import try require.resolve() on the path you're requesting. I'm still pretty sure what you're trying cannot work though.


text:
Q: How to use Binding like proxy? <Setter Property="IsChecked">
    <Setter.Value>
        <MultiBinding>
            <!-- Get value for property -->
            <Binding Path="IsPressed" RelativeSource="{RelativeSource Self}" Mode="OneWay"/>
            <!-- Set value to ViewModel's property -->
            <Binding Path="Shift" Mode="OneWayToSource"/>
        </MultiBinding>
    </Setter.Value>
</Setter>

I need to use 2 bindings for property: one to get value for property and one to set value to ViewModel's property.
How I can realize this scenario?

A: You can create a couple of attached properties. One will be the target of your binding, and second will contain binding for your proxy. Example:

Then in ProxySource OnChange implementation you will get TextBox as UIElement, there you can read value from ProxySource and write it to ProxyTarget.
This is not a very clean aproach, but it should work.
If you can't get it working, I can write a complete sample later.
Ok, I've implemented everything, here's complete source:
public class ViewModel : ViewModelBase
{
    string sourceText;
    public string SourceText
    {
        get { return sourceText; }
        set
        {
            if (sourceText == value) return;
            sourceText = value;
            System.Diagnostics.Debug.WriteLine("SourceText:" + value);
            RaisePropertyChanged("SourceText");
        }
    }

    string targetText;
    public string TargetText
    {
        get { return targetText; }
        set
        {
            if (targetText == value) return;
            targetText = value;
            System.Diagnostics.Debug.WriteLine("TargetText:" + value);
            RaisePropertyChanged("TargetText");
        }
    }
}

public static class AttachedPropertiesHost
{
    public static object GetProxySource(DependencyObject obj)
    {
        return obj.GetValue(ProxySourceProperty);
    }

    public static void SetProxySource(DependencyObject obj, object value)
    {
        obj.SetValue(ProxySourceProperty, value);
    }

    public static readonly DependencyProperty ProxySourceProperty =
            DependencyProperty.RegisterAttached(
                "ProxySource", typeof(object), typeof(AttachedPropertiesHost),
                new UIPropertyMetadata(null, ProxySourcePropertyPropertyChanged)
            );

    private static void ProxySourcePropertyPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        dependencyObject.Dispatcher.BeginInvoke(
                new { Dp = dependencyObject, NewValue = e.NewValue },
                args => SetProxyTarget(args.Dp, args.NewValue)
            );
    }

    public static object GetProxyTarget(DependencyObject obj)
    {
        return obj.GetValue(ProxyTargetProperty);
    }

    public static void SetProxyTarget(DependencyObject obj, object value)
    {
        obj.SetValue(ProxyTargetProperty, value);
    }

    public static readonly DependencyProperty ProxyTargetProperty =
            DependencyProperty.RegisterAttached("ProxyTarget", typeof(object), typeof(AttachedPropertiesHost));
    }

<TextBox Text="{Binding SourceText, UpdateSourceTrigger=PropertyChanged}"
             WpfDataGridLayout:AttachedPropertiesHost.ProxySource="{Binding RelativeSource={RelativeSource Self}, Path=Text, UpdateSourceTrigger=PropertyChanged}"
             WpfDataGridLayout:AttachedPropertiesHost.ProxyTarget="{Binding TargetText, Mode=OneWayToSource}"
             />

And the output from console while editing textbox:
SourceText:f
TargetText:f
SourceText:fh
TargetText:fh
SourceText:fhh
TargetText:fhh

A: Please dont design your solution around IsPressed, thats actually what some call a flash data which means it changes back to a default value (false) sooner. Also contextually Binding will have dedicated target, source and mode. In MultiBinding acheiving one way IsPressed (from a Source) and other way saving back to another Target is not supported. For two way update to occur, all bindings have to be TowWay.
Although a Hack to this could be using MultiConverter having a Target itself as one of the values.
     <MultiBinding Converter="MyMultiBindingConverter">
          <!-- Get value for property -->
         <Binding Path="IsPressed"
                  RelativeSource="{RelativeSource Self}" Mode="OneWay"/>
          <!-- Set value to ViewModel's property -->
         <Binding BindsDirectlyToSource="True"/>
     </MultiBinding>

    MyMultiBindingConverter.Convert()
    {
        var myViewModel = values[1] as MyViewModel;
        var isPressed = bool.Parse(values[0].ToString());
        if (isPressed)
        {
            myViewModel.Shift = !myViewModel.Shift;
        }
    }

But this is strongly NOT recommended.


text:
Q: Writing XML metadata with Python? Some Python software I have written generates raster files via GDAL. I would like the software to create an XML metadata file for each raster so that I can include details about how the raster was made, who made it, and so-on.
I understand that ISO 19115 is the international geospatial metadata standard. I really have no idea where to start with generating a metadata file, though. Can GDAL do this from scratch? Or would it be better to work with a dedicated XML library in Python?

A: THis post got me started to create a needed XML-file with Python: https://stackoverflow.com/questions/3605680/creating-a-simple-xml-file-using-python
in my case, this code:
##############################
#Create the necessary XML file
##############################
root = ET.Element("OGRVRTDataSource")
OGRVRTLayer  = ET.SubElement(root, "OGRVRTLayer")
OGRVRTLayer.set("name", AMSRcsv_shortname)

SrcDataSource = ET.SubElement(OGRVRTLayer, "SrcDataSource")
SrcDataSource.text = AMSRcsv

GeometryType = ET.SubElement(OGRVRTLayer, "GeometryType")
GeometryType.text = "wkbPoint"

GeometryField = ET.SubElement(OGRVRTLayer,"GeometryField")
GeometryField.set("encoding", "PointFromColumns")
GeometryField.set("x", "lon")
GeometryField.set("y", "lat")
GeometryField.set("z", "brightness")

tree = ET.ElementTree(root)
tree.write(AMSRcsv_vrt)

creates such files:
<OGRVRTDataSource>
   <OGRVRTLayer name="GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H">
      <SrcDataSource>G:\AMSR\GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H.csv</SrcDataSource>
      <GeometryType>wkbPoint</GeometryType>
      <GeometryField encoding="PointFromColumns" x="lon" y="lat" z="brightness" />
   </OGRVRTLayer>
</OGRVRTDataSource>


text:
Q: Get AWS Lambda url from cdk and insert it into a frontend application I have an aws cdk stack i am writing in typescript. It consists of a react app stored in an s3 bucket (via s3 bucket deployment). I also have an api gateway running a websocket api. I now need to join the two together, by telling the react app the url of the api gateway, ideally via the deploy step.
I have tried writing the token to a file before deploying, but the string is still tokenised, so i end up with wss://${Token[TOKEN.243]}..., so the write is too early. I have tried writing the file via cdk deploy -O but at that point its too late to ship it with the deploy.
How can I inform my react application of the web api url?

A: When I do this pattern, I will use CloudFront to proxy /api/* to my API Gateway and everything else to the S3 bucket website url.  Then the react code just has to make requests on /api

A: You can divide your Stack in 2 parts.

*

*Api Stack

*ReactApp stack

Deploy Api Stack first with -O options to write api url into some json file in directory getting deployed to s3.
Now you have json having api url in json file and you can deploy ReactApp Stack now.
Note: In your react app you can should read  the url from the file that will be generated by cdk deploy -O <filename>.json.


text:
Q: Azure data factory- Azure function to connect sql database does not work I have a copy activity in ADF. On completion I wanted to update a table.
Stored proc is not an option for us.
Would like to know all other options to run the update query post copy.
Tried Azure function to connect to sql database and update the table.
Works fine separately with time trigger .
What trigger to be used for the Azure function for this scenario in ADF?
Thanks in advance,
Aruna

A: Per my understanding, you want to execute a function to update a table after a copy activity and you don't want to use time trigger. Currently Azure function supported as a step in Azure Data Factory pipelines. So we just need to drag the azure function to pipeline in Azure Data Factory and provide the info of your function(such as the name, url...).

For further information, you can refer to this tutorial: https://azure.microsoft.com/en-us/blog/azure-functions-now-supported-as-a-step-in-azure-data-factory-pipelines/

A: As a work-a-round: within lookup you can define a sql query and execute quiete a lot of logic. There is a limit of ~2MB of data returned on the lookup (not listed as a limitation of ADF).


text:
Q: 7812 minimum input voltage? On the datasheet it doesn't mention an input voltage. Must the input voltage be higher than the output voltage or does it increase to 12 V if I input 8 V for example?
If so, what is the current like that it outputs?

A: A 7812 is a linear regulator, and does not step up the input voltage if the input is below the output (for that you need a DC-DC boost regulator).  The input voltage must be above the output.  All linear regulators have a minimum dropout voltage, or difference.
The 7812 is not a LDO (low-dropout regulator), as the typical dropout voltage is around 2 volts.  (An LDO might have a dropout voltage of 0.7 volts).
On page 6 of the datasheet, the maximum dropout voltage Vd is listed as 2.5 volts, meaning you need a minimum of 14.5 volts input to the device to guarantee an output of 12 volts..

A: Voltage regulators basically can be divided in two big groups: linear regulators and SMPSs, short for Switch-Mode Power Supplies, aka "switchers". Switchers are the most versatile, they allow you to go from a lower voltage to a higher one or vice versa, and they often do so with high efficiency, often > 90%. That means that when your load consumes 10W the switcher will only dissipate 1W.
Linear regulators are different. They are like a variable series resistor between input and output, causing a voltage drop across the regulator.

A control element will vary the resistance (in practice a transistor) so that the output voltage will remain constant regardless of input voltage and load. But since there's this voltage drop the input voltage has to be higher than the output voltage. How much higher depends on the type of regulator. There are LDOs (Low Drop-Out) which still can regulate the output if the input is only a few hundreds of mV higher and there are even ultra low drop-out types which only need a few tens of mV.
The 7812 is a non-LDO linear regulator, which means it needs a higher input voltage. The datasheet does say how much it needs, but you may have to look for it. This is a snapshot of page 8:

All parameters are specified under certain conditions, and for the output voltage we can see that the condition is that the input voltage is minimum 14.5V. The 2.5V dropout is typical for a three-legged linear regulator. If we look further we can see two values for line regulation; it appears that this is best if the input voltage is at least 16V.
So you won't find a parameter "minimum input voltage", but it is mentioned as a condition for proper operation within certain limits.
A note on dissipation:
From the above it may look like you best make your input voltage a lot higher than the 12V output, but that's not true. The current to your load flows through the regulator and is the same current as will be drawn from the input voltage. So if you have a 12W load it will draw 1A from the regulator. If you have an input voltage of 20V the same 1A will be drawn from that 20V. So the 20V delivers 20W, while the load only consumes 12W. The difference of 8W will be dissipated in the regulator. That's a lot. Therefore it's best to keep the input voltage just above the minimum to prevent the regulator to become overheated.


text:
Q: mysql character set conversion I have the following UTF-8 table:
CREATE TABLE `table` (
  `id` int(11) NOT NULL DEFAULT '0',
  `description` mediumtext,
  `description_info` mediumtext,
  `rights` mediumtext,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

inside a UTF-8 database:
CREATE DATABASE `DB` /*!40100 DEFAULT CHARACTER SET utf8 */

in this table there are rows with LATIN1 characters, like: è or ò
My question is: how can I convert those characters?
THX!

A: Use a CONVERT:
SELECT
    description,
    CONVERT(description USING utg8)
FROM
    `table`

A: I have found a solution here: http://www.percona.com/blog/2013/10/16/utf8-data-on-latin1-tables-converting-to-utf8-without-downtime-or-double-encoding/
Those are the steps I have applied to convert latin1 text inside the 'description' column to UTF8:
ALTER TABLE table CONVERT TO CHARACTER SET latin1 -- this is because my table is in UTF8
ALTER TABLE table CHANGE description description BLOB;
ALTER TABLE table CONVERT TO CHARACTER SET utf8, CHANGE description description mediumtext;

I don't know if this is the most effective method to this... but it works!


text:
Q: Date in vba vlookup The following code shows the Range("b2") is equal to #8/28/2018# and the first vlookup runs successfully, but the second vlookup returns an error.
Can anyone explain why it happens? Thanks.
Sub vlup()
Dim idx As Double
Dim dt As Date

If Range("b2") = #8/28/2018# Then
    MsgBox "They are equal. "
End If

dt = WorksheetFunction.VLookup(Range("b2"), Range("b1:b11"), 1, False)
MsgBox "The 1st search is valid. "

dt = WorksheetFunction.VLookup(#8/28/2018#, Range("b1:b11"), 1, False)
MsgBox "The 2nd search is valid. "

End Sub

The excel table


text:
Q: db2 query which shows records repeated for each value in another table I need to insert records into e.g. table 1 by creating a new instance of each existing record in the table for every record in one of the reference tables e.g. ref table 1.
So, for example...
Table 1
ID = 1, Name = John, Ref Table 1 ID = null

Ref Table 1
ID = 1, Name = Grade 1
ID = 2, Name = Grade 2

Wanted result from SQL
Table 1
ID = 1, Name = John, Ref Table 1 ID = 1
ID = 2, Name = John, Ref Table 1 ID = 2

or even
ID = 1, Name = John, Ref Table 1 ID = null
ID = 2, Name = John, Ref Table 1 ID = 1
ID = 3, Name = John, Ref Table 1 ID = 2

Is this possible using standard SQL?
Looking to get it all in one query as at the moment it looks like I'll have to repeat it for each ref table 1 record.
Thanks

A: Try something like this:

*

*Create table for insert results:
CREATE TABLE to_insert(
   ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
  ,Name VARCHAR(100)
  ,Ref_Table1_ID INTEGER
  ,PRIMARY KEY(ID)
  ,FOREIGN KEY(Ref_Table1_ID) REFERENCES(ref_table_1)
);

*Execute insert query:
INSERT INTO to_insert(Name, Ref_Table1_ID)
 SELECT t1.Name, COALESCE(t1.Ref_Table1_ID, rt1.ID) Ref_Table1_ID
 FROM table_1 t1 FULL OUTER JOIN ref_table_1 rt1 ON (t1.Ref_Table1_ID = rt1.ID)

A: Maybe I'm missing something, but why not just do:
SELECT * FROM tbl_1, tbl_2

Result would be:
tbl_1.ID    tbl_1.Name  Ref Table ID    tbl_2.ID    tbl_2.Name
1           John                        1           Grade 1
1           John                        2           Grade 2

Where tbl_1
ID  Name    Ref Table ID
1   John    NULL

and tbl_2
ID  Name
1   Grade 1
2   Grade 2

At last, just select the required columns.


text:
Q: How to automatically run a transcompiler when a JS file is changed/saved I'm coding an ES6 project with WebStorm (trial) at the moment which has a tool called 'File Watchers', which also conveniently includes a Traceur watcher transcompiling ES6 files when they change.
Is there an equivalent functionality to the WebStorm 'File Watchers' tool incorporated into NetBeans?  Or a technique otherwise to execute a program when a source code file is changed/saved.

A: You can use Grunt for such thing (daily NetBeans builds also have Gulp support). Define Grunt task that executes command (using grunt exec) and setup file watcher using (watch task) to invoke the exec task on file change


text:
Q: Xamarin forms app with listview and detailed view I am looking for a solution, to have a list view with items in the list, that is working, and I would like to make it so if I click on an item on the list, I would get the detailed view of the item.
So my problem is, to how to bind the detail view to the selected item.
this is where my data comes for now
public class Friend
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public int PhoneNumber { get; set; }
    public string Email { get; set; }
    public Uri Picture { get; set; }
    public string GPS { get; set; }
    public Uri URL { get; set; }

    public override string ToString()
    {
        return Name + " Address: " + Address + " Phone Number: " + PhoneNumber;
    }
    //firend data
    public static List<Friend> GetList()
    {
        var friends = new List<Friend>();
        friends.Add(new Friend { Id = 1, Name = "t1", Email = "t1@t1.com", Address = "xx", GPS = "22t,e33", PhoneNumber = 523254854, Picture = new Uri(""), URL = new Uri("") });
        friends.Add(new Friend { Id = 2, Name = "t2", Email = "t1@t1.com", Address = "xx", GPS = "22t,e35", PhoneNumber = 222222, Picture = new Uri(""), URL = new Uri("") });
        friends.Add(new Friend { Id = 3, Name = "t3", Email = "t1@t1.com", Address = "xx", GPS = "22t,e38", PhoneNumber = 111111, Picture = new Uri(""), URL = new Uri("") });

        return friends;
    }
}

this is my mainview
     public partial class MainPage : ContentPage
    {
    public MainPage()
    {
        InitializeComponent();

        MainListView.ItemsSource = Friend.GetList();

    }

    private async void MainListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        if (e.SelectedItem != null)
        {
            var PhotoPage = new Page1(e.SelectedItem);
            await Navigation.PushAsync(PhotoPage);
            ((ListView)sender).SelectedItem = null; // de-select the row
        }

    }
}

Thanks
link to project on git

A: Jason is correct there your code is correct, but maybe this can clear your mind:
private async void MainListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
    if (e.SelectedItem != null)
    {
        Friend friend = e.SelectedItem as Friend;
        await Navigation.PushAsync(new FriendPage(friend));
        ((ListView)sender).SelectedItem = null;
    }
}

//Where
//FriendPage:

public class FriendPage : ContentPage
{
    public FriendPage(Friend friend)
    {
        //... friend parameter will have the selected list item.
    }
}