text:
Q: Invalid Operation Exception I created a WCF Serice that worked fine when hosted on IIS.
now, I took the same service, and created a host application in WPF, and when trying to start the service from that application, I get this exception :
The HttpGetEnabled property of ServiceMetadataBehavior is set to true and the
HttpGetUrl property is a relative address, but there is no http base address.
Either     supply an http base address or set HttpGetUrl to an absolute address.

A: The error is quite clear - you're using HTTP, you have enabled HttpGetEnabled on your ServiceMetadata behavior, but you have not provided a base address in your config.
In IIS, base addresses are neither needed, nor used, since the location of the *.svc file defines your service address. When you're self-hosting, you can and should use base addresses.
Change your config to look something like this:
<system.serviceModel>
  <services>
    <service name="YourService">
      <host>
        <baseAddresses>
           <add baseAddress="http://localhost:8080/YourService" />
        </baseAddresses>
      </host>
      <endpoint address="mex" binding="mexHttpBinding"
                contract="IMetadataExchange" />
      ..... (your own other endpoints) ...........
    </service>
  </services>
</system.serviceModel>

Now, the "HttpGetEnabled" has a base address http://localhost.8080/YourService to go to to get the metadata from.
Or if you don't like this, again, the error message is quite clear on your alternative: define an absolute URL for the HttpGetUrl in your ServiceMetadata:
  <serviceBehaviors>
    <behavior name="Default">
      <serviceMetadata
           httpGetEnabled="true"
           httpGetUrl="http://localhost:8282/YourService/mex" />
    </behavior>
  </serviceBehaviors>

The clients can get your metadata from your "mex" endpoints, either at a fixed URL defined as in this second example, or they will go to the base address of the service for the metadata (if there is one).
If you're coming from IIS and haven't adapted anything, you'll have neither a base address, nor an explicit, absolute URL for your Metadata exchange endpoint, so that's why you get the error you're seeing.
Marc

A: I faced this error when I tried to use net.pipe binding.In my case, the default service behavior published the service metadata, This is the cause of my error. My solution is to use different behavior for your services. , then I changed my config file according to @marc_s answer and make different service behaviors as follows:
<serviceBehaviors>
        <!--Default behavior for all services (in my case net pipe binding)-->
        <behavior >

          <serviceMetadata   httpGetEnabled="false" httpsGetEnabled="false" />

          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <!--for my http services -->
        <behavior name="MyOtherServiceBehavior">

          <serviceMetadata   httpGetEnabled="true" httpsGetEnabled="true" />

          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>

A: Check that the service class is correct.
It's solved my problem
// Create a ServiceHost for the CalculatorService type and
// provide the base address.
serviceHost = new ServiceHost(typeof(ServiceClass));


text:
Q: Método __str__ es ignorado Tengo un problema y es que utilizo el método __str__(self) en una clase para que cuando la imprima no me salga de esta forma aeroport.Aeroport object at 0x00000237425DA588, sin embargo cuando imprimo el diccionario me imprime de esta forma cuando debería salir los atributos de la clase.
defino la clase Aeropuerto (fichero 1) así:
 class Aeroport:
    def __init__(self, IATA, Nom, latitud, longitud, conecciones):
        self.IATA = IATA
        self.Nom = Nom
        self.latitud = latitud
        self.longitud = longitud
        self.Conecciones = conecciones

    def __str__(self):
        return str(self.get_IATA())+' '+str(self.get_nom())+' Latitud:'+str(self.get_latitud())+' Longitud:'+str(self.get_longitud())+' Conecciones:'+str(self.Conecciones)

este es otro fichero (fichero2):
from aeroport import Aeroport

def cargar_dadas(fichero):
    try:
        file = open(fichero, 'r')
        dic_aeropueto={}
        for text in file:
            dic_conection = {}
            values = text.split(',')
            l_conection = values[-1].split()
            for clave in range(0,len(l_conection),2):
                dic_conection[l_conection[clave]]=l_conection[clave+1]
            values = values[:-1]
            aero = Aeroport(values[0], values[1], values[2], values[3], dic_conection)
            dic_aeropueto[aero.get_IATA()]=aero

        file.close()
        print(str(dic_aeropueto))

    except FileNotFoundError:
        print('Fichero inexistente')

cargar_dadas('Dades.txt')

datos en fichero (.txt):
  BCN,Barcelona,41.289182,2.0746423,MAD 00:55 CDG 01:25 OSL 03:02 ZRH 01:25 MLA 01:52 AGP 01:18 VIE 02:02
  MAD,Madrid,40.472222,-3.560833,BCN 00:55 OSL 03:19 FRA 01:40 AMS 02:09 LIS 01:00 OPO 00:51 GLA 02:28 HEL 03:58

A: Según el modelo de datos de Python tenemos a nuestra disposición dos métodos  para representar un objeto en forma de cadena:
Método __str__
Retorna una una cadena que es la representación "informal" del objeto, es una representación "bonita" destinada al usuario final. Debe ser lo más legible posible.
Dicho método es llamado por el builtin str() y por print(). Si no se implementa __str__ se llama directamente a __repr__.
Método __repr__
Retorna una cadena que es la representación formal del objeto. Debería ser (si es posible) un argumento válido para eval de forma que este pueda reconstruir el objeto en base a la cadena.
Al contrario que en el caso se __str__ lo principal es que debe ser lo menos ambigua posible, dejando totalmente claro la procedencia, tipo del objeto y composición. Es una salida destinada para el desarrollador, no para el usuario final.
Es llamada por repr(), durante la conversión de cadenas y cuando el objeto es un item de un contenedor y se imprime el contenedor. Obviamente es una representación menos amigable y si el objeto es complejo puede ser también bastante compleja en el intento de eliminar toda ambigüedad.
¿Por qué al imprimir un contenedor se llama al método __repr__ de sus items?
Python intenta ser siempre lo menos ambiguo y más legible posible. con un ejemplo podemos ver muy claro esto:
Para int o float __repr__ y __str__ generan lo mismo:
>>> str(1)
'1'
>>> repr(1)
'1'

>>> str(2.3)
'2.3'

>>> repr(2.3)
'2.3'

La razón es que no hay posibilidad de confusión en este caso, pero ¿qué pasa con str por ejemplo? Aquí ya cada una retorna algo distinto:
>>> str("Hola\tStackOverfow\n")
'Hola\tStackOverfow\n'

>>> repr("Hola\tStackOverfow\n")
"'Hola\\tStackOverfow\\n'"

Como vemos __repr__ escapa las secuencias de escape y añade las comillas para dejar claro que es una cadena.
Esto es importante, imaginemos que tenemos una lista de cadenas y otra de enteros:
l1 = ["1", "2", "3"]
l2 = [1, 2, 3]

si se usa __str__ al imprimir la lista de cadenas la salida sería:
[1, 2, 3]

que es exactamente lo mismo que si imprimimos la de enteros... Por lo tanto, si vemos lo anterior ¿estamos ante una lista de enteros o de cadenas? ¿que hay de eval/ast.literal_eval?, ¿siempre construiría una lista de enteros...?
¿Cómo solucionas tu "problema"?
La opción obvia es implementar también __repr__ (sobrescribir más bien ya que deriva de object) y hacer que retorne lo mismo que __str__, algo como:
class Aeroport:
    def __init__(self, IATA, Nom, latitud, longitud, conecciones):
        self.IATA = IATA
        self.Nom = Nom
        self.latitud = latitud
        self.longitud = longitud
        self.Conecciones = conecciones

    def __str__(self):
        return (
            f"{self.get_IATA()} {self.get_nom()} "
            f"Latitud:{self.get_latitud()} "
            f"Longitud:{self.get_longitud()} "
            f"Conecciones:{self.Conecciones}"
            )

    def __repr__(self):
        return self.__str__()

Ahora bien, no es buena idea porque lo ya comentado. Siempre es buena idea implementar __repr__ pero de forma adecuada para lo que está pensada:
def __repr__(self):
   return (f'{self.__class__.__name__}('
           f'{self.IATA!r}, {self.Nom!r}, {self.latitud!r}, '
           f'{self.longitud!r}, {self.Conecciones!r})')

Si quieres imprimir el diccionario, siempre puedes crear una función accesoria que te lo imprima como quieres:
def pprint_dict(diccionario):
    print("{", ",\n ".join(f"({str(item)})" for item in diccionario), "}", sep="")

pprint_dict(dic_aeropueto)

Por cierto, print(str(dic_aeropueto)) es redundante, print ya  usa __str__ como se ha comentado.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ImportError: cannot import name 'is_scalar' I am importing the Basemap package from mpl_toolkits.basemap.
from mpl_toolkits.basemap import Basemap

Tried: Updating the version of matplotlib
But still, it throws an error:
ImportError: cannot import name 'is_scalar'

A: I found this on GitHub, maybe one of these solutions will work for you.

A: I had the same problem, it appears to have been fixed in a newer version of basemap. After compiling from source it worked for me
git clone https://github.com/matplotlib/basemap.git
cd basemap
pip install .

After doing this, you can test your basemap installation to verify it works correctly:
cd examples
python simpletest.py


text:
Q: How to capture self because calling super.init? How to capture self because calling super.init?
public class Var<T> {
    let _get : Void -> T
    init(_ f : Void -> T) {
        _get = f
    }
    public var value : T {
        get {
            return _get()
        }
    }
}

public class Value<T> : Var<T> {
    var _val : T
    public init(_ t: T) {
        _val = t
        super.init({ [unowned self] in self._val })  // <--- Error
    }
}

Error:
error: 'self' used before super.init call
    super.init({ [unowned self] in self._val })

I know I can override getter but it is irrelevant in this question

A: public class Value<T> : Var<T> {
    var _val : T
    public init(_ t: T) {
        _val = t
        var v:(()->T)!
        super.init({ v() })
        v = { [unowned self] in self._val }
    }
}

OR
public class Value<T> : Var<T> {
    var _val : T
    public init(_ t: T) {
        _val = t
        weak var _self:Value<T>!
        super.init({ _self._val })
        _self = self
    }
}


text:
Q: HasFlag always returns True There is a way to check if I got a flag in a series of flag?
Example:
[Flags]
Enum TestEnum
{
  ALIVE, DEAD, ALMOSTDEAD, HURT, OTHERS

}
// check if is alive and has been hurt
TestEnum aTest = TestEnum.ALIVE | TestEnum.HURT
bool aTest2 = aTest.HasFlag(TestEnum.ALIVE)

But a.Test.HasFlag always returns true, even without the TestEnum.ALIVE

A: You can certainly use Enum.HasFlag like everyone has suggested. However, its important to make sure that your enumeration falls in powers of two. Powers of two have a single bit set, so your enumeration should look like this:
Enum TestEnum
{
    ALIVE = 1, DEAD = 2, ALMOSTDEAD = 4, HURT = 8, OTHERS = 16
}

The reason this is important is because you are comparing the bit flags. In memory, your enum flags will look like this:
ALIVE      = 00001
DEAD       = 00010
ALMOSTDEAD = 00100
HURT       = 01000
OTHERS     = 10000

When you do a bitwise compare, like DEAD | ALMOSTDEAD, you are doing this:
DEAD       = 00010
           OR
ALMOSTDEAD = 00100
------------------
RESULT     = 00110

Since the Result is > then 0, its true.

A: If you want to use this as FLAGS I believe your declaration is wrong. Check out this previous post. Because of the default incrementing, HasFlag won't work as you expect unless you set the values to powers of 2.
What does the [Flags] Enum Attribute mean in C#?

A: I think you are making a game, so you should make a class for this issue
public class Player
{
    bool isAlive;
    bool isHurt;
...
}

Later you could check your states like this:
if (player.isAlive && player.isHurt)
{
 //dosomething
}

A: You can do bitwise operation like this:
var alive = TestEnum.Alive;
var hurt = TestEnum.Hurt;
var aliveAndHurt = alive & hurt;

A: You can use Enum.HasFlag to check for this.
bool aTest2 = aTest.HasFlag(TestEnum.ALIVE);


text:
Q: MS Teams bot events I have a notification-only bot, and I would like to send a welcome message to users only when the bot is added to a personal conversation.
I listen to 'conversationUpdate' events as stated here, though I keep receiving the same event multiple times one after the other for the same user, all events identical (except the event ID and timestamp).
I respond to the event with HTTP status 200 (I handle them via REST).
Does anyone have an idea why I would receive the same events multiple times and how to avoid it? Is it some kind of retry due to an unexpected response on my end?
It even says here: "For personal scoped bots, your bot will only ever receive the conversationUpdate event a single time, even if the bot is removed and re-added."


text:
Q: Unable to find API's for BigQuery Routine using Node Module I am unable to find any operations related to 'Routine' using Node library. I don't see any note in official documentation https://www.npmjs.com/package/@google-cloud/bigquery. Can someone please let me know any link which mentions Node library doesn't supports 'Routines'

A: You need to visit official BigQuery API routines documentation, where you can read more about following methods:

*

*delete

*get

*insert

*list

*update

Additionally, you can call this method on live data by typing projectId, datasetId, routineId. It will allow you to see the API request and response.
Moreover, to find examples of using specific routine methods: create, delete, exists, get, getMetadata, setMetadata, please have a look at Google BigQuery Client Library for Node.js documentation.


text:
Q: Procedurally create/read from nbt object/dictionary I'm working on a project that requires creating nbt dictionaries from another nbt array.
Essentially, the scenerio is as follows
I have array [1,2,3,4] and I would like to create a dictionary {1:2, 3:4}
These are just example values and will be generated at runtime
However, I can't figure out a way to create a dictionary procedurally, as the only way I know is to do /data modify storage <name> <key> set value <value>
I know I can do set from instead, but the main issue is the hardcoded <key>. I can't figure out a way to procedurally create/remove a key from a dict.

A: Dynamic keys are not a thing in NBT.
You'll have to use this slightly more complex format for a key-value pair dictionary:
{
  Database: [
    {key: 1, value: "one"},
    {key: 2, value: "two"},
    {key: 3, value: "three"}
  ]
}

…and read/write to it with these commands:

*

*New K/V pair (static):
data modify storage test:main Database append value {key: 4, value: "four"}

*Read value from key (static):
tellraw @a {"nbt":"Database[{key: 4}].value"}

*Overwrite new value (dynamic) to a key (static):
data modify storage test:main Database[{key: 4}].value …

Commands to do the same operations but with dynamic keys will be much harder but not impossible.
Here is a starter for adding a new key-value pair with dynamic key and value:
data modify storage test:main Database append value {key: "temp", value: "temp"}
data modify storage test:main Database[-1].key set value 5
data modify storage test:main Database[-1].value set value "five"


text:
Q: nomenclature references to wrong page I am adding acronyms and using the nomenclature package, it is somehow however on click referencing to the list of tables page instead of the nomenclature page. What is the problem?
I am also getting the error (Option clash for package nomencl.)
I tried removing the second package which might be a duplicate, the same problem occurs, any fix?
Thanks!
I am using in my preamble:
\usepackage{nomencl}
\usepackage[stdsubgroups,nocfg]{nomencl}
\makenomenclature```


text:
Q: SQL Server factors that can contribute to high CPU usage I am trying to figure out or enlist factors that contribute to persistent high CPU utilization related to SQL Server
Here are few that I came up with
a) Compilation or Frequent Recompilation of stored procs or queries
b) Poor performing queries that perform huge sort or ended up using Hash Join
c) Parallelism (multiple threads are span so it can keep CPU busy)
d) Looping construct in T-SQL for e.g. WHILE Loop or use of CURSOR
e) Missing or inappropriate indexes that leads to table scan
What are other SQL server operations can lead for a high CPU use?

A: Data compression is relatively CPU-intensive.  Encryption is another operation that can cause high CPU utilization.

A: Use of scalar user-defined functions uses a lot more CPU than you might think.


text:
Q: Modular arithmetic does not work in Threshold signature (TSS) implementation I was implementing threshold signatures protocol described in this paper and I run into a case where it fails and I don't understand reasons why. In the end, u and x should be the same, but they are not. I would appreciate any advice that will help me to find the bug.
This is JS code, it can be executed in browser console
/// TSS 2-of-2 case
// Field modulus, secp2561k
n = 115792089237316195423570985008687907852837564279074904382605163141518161494337n

// party 1 Polynomial coeff of degree 1
coeff_1 = 103808273981011494448342588544071102049904991793672697167547228275701563388858n
// coeff_1 = 10380827398101149444834258854407110204990499179367269716754722827570156338885n // Working coeff

// party 1 Polynomial coeff of degree 1
coeff_2 = 49961718147812071312795198333632033669565055597187655909241672498689891015278n
// coeff_2 = 4996171814781207131279519833363203366956505559718765590924167249868989101527n // Working coeff

// Party 1 secret
u_1 = 6989964936015280241594720270850184250394589151026058230978623558313385587815n

// Party 2 secret
u_2 = 91492373973552717359377053249757253672786176158857596037729237022345023720795n

// Party 1 Shamir points
y1_x = 1n
y1_1 = (y1_x * coeff_1 + u_1) % n
// 110798238917026774689937308814921286300299580944698755398525851834014948976673n
y1_2 = (y1_x * coeff_2 + u_2) % n
// 25662002884048593248601266574701379489513667476970347564365746379516753241736n

// Party 2 Shamir points
y2_x = 2n
y2_1 = (y2_x * coeff_1 + u_1) % n
// 98814423660722073714708912350304480497367008459296548183467916968198350871194n
y2_2 = (y2_x * coeff_2 + u_2) % n
// 75623721031860664561396464908333413159078723074158003473607418878206644257014n

// Party 1 point (y1_x, y1)
y1 = (y1_1 + y1_2) % n

// Party 2 point (y1_x, y1)
y2 = (y2_1 + y2_2) % n

// Common secret
u = (u_1 + u_2) % n

// Same secret, that went though Shamir schema
x = (y1*2n - y2) % n

// Checking calculations, should be 0
u - x
```

A: Your code is almost correct, just missing the final modulus at the end. Change the last line to
(u - x) % n;

The (u -x) is exactly n.
115792089237316195423570985008687907852837564279074904382605163141518161494337


text:
Q: How to use Select2 in Django custom SimpleListFilter I've created a custom SimpleListFilter class (code below) and managed to have the options be displayed as a select input. What I'd like to add is the functionality that Select2 offers, namely being able to search for options within the select input.
Can anyone tell me how to achieve this?
Custom SimpleListFilter class:
class AnswerTreeKnowledgeCodeListFilter(admin.SimpleListFilter):
    template = 'admin/dropdown_filter.html'
    title = _('Kenniscode')

    parameter_name = "knowledge_code"

    def lookups(self, request, model_admin):
        return [(instance.pk, str(instance)) for instance in AnswerTreeRepository.filter_by_level(0)]

    def queryset(self, request, queryset):
        # Custom queryset filtering here

dropdown_filter.html: (copied from source that I forgot, so I take no credit for this code)
{% load i18n %}

{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}

{% if choices|slice:"4:" %}

    <select class="form-control" style="width: 95%;margin-left: 2%;"
        onchange="go_from_select(this.options[this.selectedIndex].value)">
    {% for choice in choices %}
        <option{% if choice.selected %} selected="selected"{% endif %}
         value="{{ choice.query_string|iriencode }}">{{ choice.display }}</option>
    {% endfor %}
    </select>

{% else %}

    {% for choice in choices %}

            {{ choice.display }}

    {% endfor %}

{% endif %}

A: Django Admin Autocomplete Filter seems to be what you're looking for, if you're on Django 2 or newer. I haven't used it, but if you haven't found a solution yet, this might be worth trying.
https://github.com/farhan0581/django-admin-autocomplete-filter


text:
Q: Android input events handling in OS level Can some on point how the EventHub.cpp signals the JNI in the later android versions. Before there was a KeyInputQueue.java where all input events were queued. I got the latest android sources and now the KeyInputQueue.java is gone so I am trying to find the JNI/Java class where events are dispatched to android.
Tanks:
T.

A: The InputManager creates the EventHub and makes one thread for InputReader and one for InputDispatcher.
The InputReader gets the event from EventHub by getEvent() in EventHub. Then, it processes them and sends these cooked events to the InputDispatcherQueue maintained by InputDispatcher.
Then, InputDispatcher dispatches these events to the targets.


text:
Q: Why does terraform create an empty directory in the s3 bucket? I have a Terraform set up that creates an s3 bucket and sub directories in the bucket.
For some reason the bucket is created with an empty / and in each directory.
s3_bucket:
-/
-folder1:-/
         -some file
-folder2:-/

And so on for every directory, there is an empty /.
This causes issues in my next few steps, why is it created this way? how can I create the s3 and folders without the empty / ?
resource "aws_s3_bucket_object" "object" {
  bucket = "${aws_s3_bucket.s3_ob.id}"
  key    = "folder1/"
  source = "dummy.txt"
}

resource "aws_s3_bucket_object" "object2" {
  bucket = "${aws_s3_bucket.s3_ob.id}"
  key    = "/folder2/"
  source = "dummy.txt"
}

A: This happens because your keys end with a /. What your code does is to write contents of dummy.txt to the keys at folder1/ and folder2/. S3 is a key value objects storage and not a file system. Concept of directories is just something we bring on logically by splitting the keys with slash characters / and calling every step a directory, so in this case yes, a folder1 and folder2 has been created and since there's nothing after the slash the file name is practically empty.
I assume what you want to do is to just give your files some names in the traditional file system sense, as in don't end your key names with a /.
resource "aws_s3_bucket_object" "object" {
  bucket = "${aws_s3_bucket.s3_ob.id}"
  key    = "folder1/dummy.txt"
  source = "dummy.txt"
}

resource "aws_s3_bucket_object" "object2" {
  bucket = "${aws_s3_bucket.s3_ob.id}"
  key    = "/folder2/dummy.txt"
  source = "dummy.txt"
}


text:
Q: How to use R littler with docker to install installable source files? I would like to install some specific version of a R package. According to the documentation littler recognise installable source files. So I assumed that may work:
FROM r-base:latest

RUN apt-get update \
      && install.r --error digest_0.6.8.tar.gz

The output looks as follows and at least here does not contradict my assumption
            [+] Building 9.3s (6/6) FINISHED
            => [internal] load build definition from Dockerfile                                                                                0.0s
            => => transferring dockerfile: 138B                                                                                0.0s
            => [internal] load .dockerignore                                                                                0.0s
            => => transferring context: 2B                                                                                0.0s
            => [internal] load metadata for docker.io/library/r-base:latest                                                                                0.3s
            => CACHED [1/2] FROM docker.io/library/r-base:latest@sha256:c3808f786a44ef1b2ed727166ac3daed1d47b1894c6858869a2bb6f97b7a1da9                                                            0.0s

            => [2/2] RUN apt-get update         && install.r --error digest_0.6.8.tar.gz                                                                                8.7s
            => exporting to image                                                                                0.2s
            => => exporting layers                                                                                0.2s
            => => writing image sha256:a8781141095c3edef0618ebf1b2be8de435cdc62eacae6c617f2b512c7df68f5                                                                                0.0s
            => => naming to docker.io/library/test_install_r

However when running the container digest is not installed.
When using install2.r
FROM r-base:latest

RUN apt-get update \
      && install2.r --error digest_0.6.8.tar.gz

where throws an error:
        => ERROR [2/2] RUN apt-get update         && install2.r --error digest_0.6.8.tar.gz                                                                                8.3s
        ------
        > [2/2] RUN apt-get update         && install2.r --error digest_0.6.8.tar.gz:
        #5 0.440 Get:1 http://deb.debian.org/debian testing InRelease [129 kB]
        #5 0.537 Ign:2 https://eddelbuettel.github.io/ppaR400 ./ InRelease
        #5 0.669 Get:3 http://deb.debian.org/debian experimental InRelease [75.4 kB]
        #5 0.711 Get:4 https://eddelbuettel.github.io/ppaR400 ./ Release [1,204 B]
        #5 0.822 Get:5 http://cdn-fastly.deb.debian.org/debian sid InRelease [165 kB]
        #5 0.826 Get:6 http://deb.debian.org/debian testing/main amd64 Packages [8,260 kB]
        #5 0.837 Ign:7 https://eddelbuettel.github.io/ppaR400 ./ Release.gpg
        #5 0.980 Get:8 https://eddelbuettel.github.io/ppaR400 ./ Packages [26.4 kB]
        #5 1.144 Get:9 http://cdn-fastly.deb.debian.org/debian sid/main amd64 Packages [8,881 kB]
        #5 3.522 Get:10 http://deb.debian.org/debian experimental/main amd64 Packages [392 kB]
        #5 5.783 Fetched 17.9 MB in 5s (3,289 kB/s)
        #5 5.783 Reading package lists...
        #5 8.186 Error: package 'digest_0.6.8.tar.gz' is not available for this version of R
        #5 8.186
        #5 8.186 A version of this package for your version of R might be available elsewhere,
        #5 8.186 see the ideas at
        #5 8.186 https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
        #5 8.186 In addition: Warning message:
        #5 8.186 package 'digest_0.6.8.tar.gz' is not available for this version of R
        #5 8.186
        #5 8.186 A version of this package for your version of R might be available elsewhere,
        #5 8.186 see the ideas at
        #5 8.186 https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages

I guess Im missing something here and appreciate any suggestions!


text:
Q: How to check macros defined in .so? I'd use nm to check the function, is there a way to do the same for macros? I have a code like this in mylib.h, and then I use it to create mylib.so.
Is there a way to check how MY_MACROS is defined in .so?
#ifdef SWITCH_CONDITION
    #define MY_MACROS       0
#else
    #define MY_MACROS       1
#endif

If that would be a function, I'd simply do
nm mylib.so | grep myfunction

Is there a way to do the same for macros?
P.S. There should be because of
> grep MY_MACROS mylib.so
> Binary file mylib.so matches

A: In general there is no way to do this sort of thing for macros.  (But see more below.)
Preprocessor macros are theoretically a compile-time concept.  In fact, in the early implementations of C, the preprocessor was -- literally -- a separate program, running in a separate process, converting C code with #include and #define and #ifdef into C code without them.  The actual C compiler saw only the "preprocessed" code.
Now, theoretically a compiler could somehow save away some record of macro definitions, perhaps to aid in debugging.  I wasn't aware of any that did this, although evidently those using the DWARF format actually do!  See comments below, and this answer.
You can always write your own, explicit code to track the definition of certain macros.  For example, I've often written code elong the lines of
void print_version()
{
    printf("myprogram version %s", VERSION_STRING);
#ifdef DEBUG
    printf(" (debug version)");
#endif
    printf("\n");
}

Some projects have rather elaborate mechanisms to keep track of the compilation switches which are in effect for a particular build.  For example, in projects managed by a configure script, there's often a single file config.status containing one single record of all the compilation options, for posterity.

A: Yes, but it requires debugging info.
You can compile your code with -g3:
$ gcc -g3 -shared -fPIC test.c -o test.so

and then run strings on the resulting binary:
$ strings test.so
...
__DEC32_EPSILON__ 1E-6DF
MY_MACROS 1
__UINT_LEAST32_TYPE__ unsigned int


text:
Q: How can I get this Cover Page/ Title Page to work in my LaTeX file? I am making my very first LaTeX typeset thesis. I am planning on printing two versions of this thesis (Onesided for corrections and two-sided for final submission).
I want to incorporate this exact format for Cover Page and Title Page which I found on Page 6 of the document 'Writing a Thesis with LaTeX' by Lapo F. Mori'.
I've given this a go -
``
\documentclass[a4paper,12pt,titlepage,oneside]{book}
 \usepackage[DIV=14,BCOR=2mm,headinclude=true,footinclude=false]{typearea}
 \usepackage{setspace}
 \setstretch{1.1}
 \KOMAoptions{DIV=last}

\makeatletter
\if@twoside
   \newlength{\myoffset}
   \setlength{\myoffset}{12mm}
   \addtolength{\hoffset}{\myoffset}
   \addtolength{\evensidemargin}{-2.0\myoffset}
\fi
\makeatother

\usepackage{babel}
\usepackage{csquotes}
\usepackage[T1]{fontenc}
\usepackage{charter}
\usepackage{eso-pic}
\usepackage{graphicx}
%\graphicspath{{images/}}
\usepackage{xcolor}

\definecolor{tcdblue}{RGB}{14,115,185}
\definecolor{tcdgrey}{RGB}{83,86,90}

\begin{document}

\AddToShipoutPictureBG*{\includegraphics[width=\paperwidth]{logo1}}

\centering
\textbf{Firstname Surname}
\vspace{5cm}
\textbf{\LARGE{NAME of THESIS IN ALL CAPITAL LETTERS}}
\vspace{0.5cm}
\textbf{A Thesis in Doctor of Philosophy}
\vspace{11cm}
\textbf{Name of University}
\vspace{1cm}
Month 2019
\begin{titlepage}
\begin{center}
% \vspace*{1cm}
\includegraphics[width=0.2\textwidth]{logo1} \\

\textcolor{tcdgrey}{\textrm{\textbf{\textsc{Name of University}}}} \\
\textcolor{tcdgrey}{Name of University in Local Language} \\
\textcolor{tcdblue}{Department/Faculty Name} \\

\hrulefill\par

\textrm{A dissertation submitted in partial fulfillment of the requirements for the degree of Doctor of Philosophy in Biochemistry \& Immunology}

\vspace{1.5cm}
NAME of THESIS IN ALL CAPITAL LETTERS
\vspace{1.5cm}

Thesis/Dissertation by \\
\vspace{0.2cm}
\textbf{Author Name}
\vspace{1.5cm}

\begin{flushleft}
Examiners \\
\vspace{0.2cm}
Prof 1 Firstname SURNAME \dotfill \\
Prof 2 Firstname SURNAME \dotfill \\
\vspace{0.5cm}
Candidate \\
\vspace{0.2cm}
Firstname SURNAME
\end{flushleft}
\vfill
\hrulefill\par
Academic Year 2019/2012 \\
Country \\
Date
\end{center}
\end{titlepage}
\end{document}

``
And this is the output that I get -

How can I make my output exactly similar to the one in the linked PDF (while implementing my own fonts which is CharterBT and not CMR)? I have colour logos and I want these to show up in Greyed out Watermark style (only for the cover page background). I am unsure how to implement the code shown on page 6 of the linked pdf.
The rest of my thesis is showing up correctly with the code in the preamble (especially when I implement the twosided option in the document class). I want the Cover Page, Title Page to show up correctly (even when the twosided option is chosen and with an empty page after the Title Page) so that when it is sent out to print, it comes out as intended.
This is one of the last bits of my thesis I am trying to figure out. Any help is greatly appreciated.


text:
Q: How to make batch file run from group policy? I am trying to make a batch file that calls an executable named idlelogoff after a certain amount of idle time. I can see the process in task manager however the computer doesn't sign out.
However when I run the process as an administrator manually it works. I thought the system account was supposed to have all privileges. Very confused as to why this isn't working. Any help would be appreciated.
Below is my batch file contents.
start "IdleLogOff" /d C:\ /b idlelogoff.exe  10 logoff

A: I found an answer to this by using local group policy instead of domain policy . I used user configuration->windows settings-> and then logon scripts and had it run on an user logon. The script works from here but did not work from domain group policy for whatever reason

A: look into taskmanager- i suppose that the process runs under system-account when using domain-gpo- no matter if activated/linked in user or workstation context.
So the exe would check if the system-account is idle.
A solution could be putting the exe into autostart-folder or create a run-key into registry or with an scheduled task -> all can be done with a gpo


text:
Q: What is "Real coordinate space"? What is the Real Coordinate Space in the discussion of vectors?
How does it relate to Cartesian Coordinate System and Euclidean Space?
P.S. Please, use naive terms.

A: In my experience the expression "real coordinate space" emphasizes that we are not working over the complex numbers, i.e. the space is $\mathbb R^n$, not $\mathbb C^n$.
You can use Cartesian coordinates (and a whole bunch of other coordinate systems) on these spaces.
The spaces $\mathbb R^n$ are called Euclidean spaces, so they are the same as real coordinate spaces.


text:
Q: Typing escape character in Cypress stopped working after upgrade I updated Cypress from ^3.1.0 to ^3.1.5, and I have a set of 4 tests that fail.  They all do the same thing.  Send escape to the body element, and assert that the close handler triggered.  Here is one of the tests:
describe('Dialog', () => {
  let closed;
  const onClose = () => {
    closed = true;
  };

  beforeEach(() => {
    closed = false;
    mount(
      <Dialog open onClose={onClose}>

Test

      </Dialog>
    );
  });

  it('closes when clicking the backdrop', () => {
    cy.get('[data-cy=dialog-backdrop]')
      .click({force: true})
      .then(() => {
         cy.expect(closed).to.equal(true);
      });
  });

  it('closes when pressing the escape key', () => {
    cy.get('body')
      .type('{esc}', {force: true})
      .then(() => {
        cy.expect(closed).to.equal(true);
      });
  });
});

The first test passes, the second test fails.  The only thing that changed was upgrading jest, babel7, and cypress.  What else should I be looking at to solve this?
mount.js
import React from 'react';
import 'react-virtualized/styles.css';
import {MuiThemeProvider, createGenerateClassName, jssPreset} from
'@material-ui/core/styles';
import {SheetsRegistry} from 'react-jss/lib/jss';
import {create} from 'jss';
import JssProvider from 'react-jss/lib/JssProvider';
import {createMemoryHistory} from 'history';
import {MockedProvider} from 'react-apollo/test-utils';
import {Router} from 'react-router-dom';
import theme from '../../src/theme';
import HistoryProvider from '../../src/components/history';

const stylesCache = new Map();
const sheetsRegistry = new SheetsRegistry();

// NOTE: Copied and modified from https://github.com/bahmutov/cypress-react-unit-test/blob/master/lib/index.js

function getAppIframeHead() {
  const parentDocument = window.parent.document;
  const projectName = Cypress.config('projectName');
  const appIframeId = `Your App: '${projectName}'`;
  const appIframe = parentDocument.getElementById(appIframeId);
  return appIframe.contentDocument.querySelector('head');
}
  const copyStyles = component => {
  const hash = component.type.name;

  let styles = document.querySelectorAll('head style');
  if (styles.length) {
    console.log('injected %d styles', styles.length);
    stylesCache.set(hash, styles);
  } else {
    console.log('No styles injected for this component, checking cache');
  if (stylesCache.has(hash)) {
    styles = stylesCache.get(hash);
  } else {
    styles = null;
  }
}

if (!styles) {
  return;
}

  styles.forEach(style => {
    getAppIframeHead().appendChild(style);
  });
};

function setXMLHttpRequest(w) {
  window.XMLHttpRequest = w.XMLHttpRequest;
  return w;
}

function setAlert(w) {
  window.alert = w.alert;
  return w;
}

function forwardEventListeners(w) {
  window.addEventListener = (...params) => {
    w.addEventListener(...params);
  };
}

function wrapJsx(jsx, mocks, history, styleNode) {
  const generateClassName = createGenerateClassName();
  const jss = create({
    ...jssPreset(),
    insertionPoint: styleNode
  });
  const sheetsManager = new Map();
  return (
  <JssProvider registry={sheetsRegistry} generateClassName= .
{generateClassName} jss={jss}>
  <MuiThemeProvider theme={theme} sheetsManager={sheetsManager}>
    <MockedProvider mocks={mocks} addTypename={false}>
      <Router history={history}>
        <HistoryProvider>{jsx}</HistoryProvider>
      </Router>
    </MockedProvider>
  </MuiThemeProvider>
</JssProvider>
  );
}

export default (jsx, mocks = []) => {
const html = `

`;

const doc = cy.state('document');
doc.write(html);
doc.close();

const history = createMemoryHistory();
cy.window({log: false})
  .then(setXMLHttpRequest)
  .then(setAlert)
  .then(forwardEventListeners)
  .its('ReactDOM.render')
  .then(render => {
  const styleNode = document.createElement('noscript');
  styleNode.setAttribute('id', 'jss-insertion-point');
  getAppIframeHead().appendChild(styleNode);
  const toRender = wrapJsx(jsx, mocks, history, styleNode);
  render(toRender, doc.getElementById('app'));
  copyStyles(jsx);
  return cy.wrap({history});
});
return {history};
};

package.json
{
  "name": "MyApp",
  "version": "1.0.0",
  "description": "AppInsights",
  "main": "index.js",
  "license": "UNLICENSED",
  "private": true,
  "dependencies": {
    "@babel/core": "^7.0.0",
    "@babel/plugin-proposal-decorators": "^7.0.0",
    "@babel/register": "^7.0.0",
    "@material-ui/core": "^3.0.0",
    "@material-ui/icons": "^3.0.0",
    "apollo-cache-inmemory": "^1.2.10",
    "apollo-client": "^2.4.2",
    "apollo-link-context": "^1.0.9",
    "apollo-link-http": "^1.5.5",
    "axios": "^0.18.0",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.4.2",
    "babel-plugin-dynamic-import-webpack": "^1.0.2",
    "classnames": "^2.2.6",
    "clean-webpack-plugin": "^0.1.19",
    "connected-react-router": "^4.3.0",
    "dotenv": "^6.0.0",
    "dotenv-webpack": "^1.5.5",
    "formik": "^1.5.0",
    "graphql": "^0.13.2",
    "graphql-tag": "^2.9.2",
    "history": "^4.7.2",
    "html-webpack-plugin": "^3.2.0",
    "jest": "^24.1.0",
    "jest-junit": "^5.2.0",
    "jwt-decode": "^2.2.0",
    "lodash": "^4.17.10",
    "material-ui-popup-state": "^1.0.1",
    "mixpanel-browser": "^2.22.4",
    "moment": "^2.22.2",
    "prop-types": "^15.6.2",
    "query-string": "^6.1.0",
    "react": "^16.3.0",
    "react-apollo": "^2.2.4",
    "react-clamp-lines": "^1.1.0",
    "react-dom": "^16.3.0",
    "react-infinite-scroll-component": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "react-text-mask": "^5.4.3",
    "react-virtualized": "^9.21.0",
    "regenerator-runtime": "^0.13.1",
    "uglifyjs-webpack-plugin": "^1.2.5",
    "uuid": "^3.2.1",
    "webfontloader": "^1.6.28",
    "webpack": "^4.9.1",
    "webpack-dev-middleware": "^3.1.3",
    "webpack-hot-middleware": "^2.22.2",
    "webpack-merge": "^4.1.2"
  },
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "^7.0.0",
    "@babel/plugin-proposal-do-expressions": "^7.0.0",
    "@babel/plugin-proposal-export-default-from": "^7.0.0",
    "@babel/plugin-proposal-export-namespace-from": "^7.0.0",
    "@babel/plugin-proposal-function-bind": "^7.0.0",
    "@babel/plugin-proposal-function-sent": "^7.0.0",
    "@babel/plugin-proposal-json-strings": "^7.0.0",
    "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0",
    "@babel/plugin-proposal-numeric-separator": "^7.0.0",
    "@babel/plugin-proposal-optional-chaining": "^7.0.0",
    "@babel/plugin-proposal-pipeline-operator": "^7.0.0",
    "@babel/plugin-proposal-throw-expressions": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/plugin-syntax-import-meta": "^7.0.0",
    "@babel/plugin-transform-modules-commonjs": "^7.0.0",
    "@babel/plugin-transform-runtime": "^7.3.4",
    "@babel/runtime-corejs2": "^7.3.4",
    "@babel/polyfill": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "@cypress/webpack-preprocessor": "^3.0.0",
    "babel-eslint": "^9.0.0",
    "babel-loader": "^8.0.0",
    "babel-plugin-dynamic-import-node": "^1.2.0",
    "css-loader": "^2.0.0",
    "cypress": "^3.1.5",
    "eslint": "^4.19.1",
    "eslint-config-airbnb": "^16.1.0",
    "eslint-config-prettier": "^2.9.0",
    "eslint-config-react": "^1.1.7",
    "eslint-plugin-import": "^2.12.0",
    "eslint-plugin-jsx-a11y": "^6.0.3",
    "eslint-plugin-prettier": "^2.6.0",
    "eslint-plugin-react": "^7.8.2",
    "ini": "1.3.5",
    "jss": "^9.8.7",
    "mockdate": "^2.0.2",
    "prettier": "^1.13.0",
    "react-hot-loader": "^4.2.0",
    "react-jss": "^8.6.1",
    "react-test-renderer": "^16.4.0",
    "style-loader": "^0.23.1",
    "webpack-cli": "^3.1.1",
    "webpack-dev-server": "^3.2.1"
  },
  "scripts": {
    "build": "webpack --config webpack.prod.js",
    "dev": "webpack-dev-server --open --config webpack.dev.js",
    "format": "prettier --write --single-quote --print-width=120 --tab-width=2 \"src/js/**/*.{js,jsx,json}\"",
    "lint": "eslint \"**/*.{js,jsx}\"",
    "watch": "webpack --watch --config webpack.dev.js",
    "test": "jest",
    "testWatch": "jest --watch",
    "cy:open": "cypress open",
    "cy:run": "cypress run",
    "cy:verify": "cypress verify"
  },
  "jest": {
    "modulePathIgnorePatterns": [
      "cypress/",
      "__tests__/utils/"
    ],
    "reporters": [
      "default",
      "jest-junit"
    ]
  },
  "jest-junit": {
    "output": "./results/jest/junit.xml"
  }
}


text:
Q: How does one go about installing flash 11 (64bit)? How does someone install the new beta version of flash 11?

A: Install Flash-Aid and run the extension Wizard. Flash-Aid allows to install Flash 64bit from Adobe Labs (32bit from repos and Chrome too), it removes conflicting plugins and apply performance tweaks. Additionally, it has a plugin update checker, so you can be notified about new beta versions.

A: As shown here http://www.webupd8.org/2011/07/adobe-releases-flash-player-11-beta.html you can use the following commands:

sudo mkdir /usr/lib/kde4
sudo add-apt-repository ppa:sevenmachines/flash
sudo apt-get update
sudo apt-get install flashplugin64-installer

You can also follow the manual installation as shown in the link above

A: The sevenmachine ppa is the best bet to keep up-to-date with flash 64 bit. Otherwise download the tar archive for linux from here.
extract it and save the libflashplayer.so file on mozilla plugin path. Either locally or on /usr/lib/mozilla/plugin. You can copy the files mentioned inside the tar on respective places .i.e inside /usr folder avoiding the kde ones if you don't use kde


text:
Q: List of CdnFallbackExpression There are a lot of open source JS libraries available on CDNs. Using the bundle feature of ASP.NET MVC it is possible to define the fallback if a CDN fails.
The CdnFallbackExpression is a useful feature, however, I cannot seem to find any list of the expressions to use for libraries other than jquery. There a few listed in this blog post:
http://geekswithblogs.net/cskardon/archive/2014/07/04/cdnfallbackexpression-for-jquery-jquery.ui-modernizr-and-bootstrap.aspx
If I don't know the fallback expression, how can I find it out?
UPDATE:
For anyone else looking, here are the ones I've managed to find so far:
## Library ##      ## Expression ##
jQuery             window.jQuery
jQuery.UI          window.jQuery.ui
Modernizr          window.Modernizr
Bootstrap          $.fn.modal
jquery.transit     $.transit
jquery.validate    $.validator
json2              JSON.stringify
webfont            WebFont
jquery.blockUI     $.unblockUI()
respond            window.respond
moment             window.moment

I'm still missing the expressions for
      wow.js
      uploadify.js
      jcrop.js
      form.js
      TweenMax.js
      ScrollToPlugin.js


text:
Q: Excel macro to copy data from one sheet to another based on specific matching conditions I have two sheets, one of which contains data for all of the match codes (Master Sheet) and another that contains data for only some match some codes. These codes link to a data number (as well as other values) that I need to bring in from the "Master Sheet" to the other sheet. I used index match initially to bring over the values and data number, however I unfortunately did not notice that there are duplicate match codes that correspond to different values and data numbers, so I want to be able to go in and copy paste any data where the match codes link up, but the data number does not. For example:
 Master Sheet

Match Code  Value 1   Value 2   Rate   data number
11111       1500      1200     2700      656565
11111       1800      1800     3600      688888
11112       1500      1100     2600      818987
11112       1500      150      1650      986773
12343       200       800      1000      785942

Sheet 2

Match Code  Value 1   Value 2   Rate   data number
11111       1500      1200     2700      656565
11112       1500      150      1650      986773

As can be seen, Sheet 2 has Match codes 11111 and 11112 as does the Master Sheet, however I need to bring over all of the data that has corresponding match values but different data numbers. I however cannot copy over the entire master sheet because the Master sheet contains Match values not found in Sheet 2 such as 12343. Thus, sheet 2 would look like this after completed:
Sheet 2

Match Code  Value 1   Value 2   Rate   data number
11111       1500      1200     2700      656565
11111       1800      1800     3600      688888
11112       1500      1100     2600      818987
11112       1500      150      1650      986773

Is there a way to make a macro to check the Match values in Sheet 2, and for every corresponding match value between the sheets, if that exact row is not already in Sheet 2, then copy over the entire row and paste it into sheet 2?
I have the following, but it isn't doing what I want it to:
Sub pasteLoop()

'Iterator Worksheet 1, is the counter for the ws1 column
Dim iWS1 As Integer
'Iterator Worksheet 2, is the counter for the ws2 column
Dim iWS2 As Integer
'Switch New Row, is the switch if the next value need a new row
Dim sNR As Integer
'Maximal Row Count, need to be extend when new rows are added
Dim MaxRows As Integer
'valueHolder, is the holder for the orginal value, the orginal value might be replaced on the sheet
Dim valueHolder As Long

'Worksheet1
Dim ws1 As Worksheet
'Worlsheet2
Dim ws2 As Worksheet

Set ws1 = ActiveWorkbook.Worksheets("Sheet 2")
Set ws2 = ActiveWorkbook.Worksheets("Master Sheet")

'Set iWS1 to the first row
iWS1 = 1
'Get MaxRows
MaxRows = ws1.Cells(Rows.Count, 1).End(xlUp).Row

'Loop through the Rows on WS1 setting switch to 0 and store the value from the ws1 row in the holder
While iWS1 <= MaxRows
sNR = 0
valueHolder = ws1.Cells(iWS1, 1).Value

'Loop through the Rows on WS2, searching for a value that match with the value from ws1
For iWS2 = 1 To ws2.Cells(Rows.Count, 1).End(xlUp).Row
    'When it matches, then look if there was already a match with the value, if not replace it on the ws1 and increase the sNr to 1
    If valueHolder = ws2.Cells(iWS2, 1).Value Then
        If (sNR < 1) Then
            ws1.Cells(iWS1, 1).Value = ws2.Cells(iWS2, 2).Value
            sNR = sNR + 1
        'When the sNR is already > 0, increase the Iterator for the ws1 that he will point on the new line
        'increase the maxrows because we got one more soon, finally insert the new row and store the value from ws2 in it
        Else
            iWS1 = iWS1 + 1
            MaxRows = MaxRows + 1
            Range(ws1.Cells(iWS1, 1), ws1.Cells(iWS1, 1)).EntireRow.Insert
            ws1.Cells(iWS1, 1).Value = ws2.Cells(iWS2, 2)
        End If
    End If
Next iWS2
iWS1 = iWS1 + 1
Wend

End Sub

A: *

*Build a dictionary of match codes and filter on those.

*Copy everything filtered over to the second worksheet.

*Remove duplicates based on match code and data number.

*[optional] Sort the new data.

BTW, your original code shows Sheet 2, not Sheet2.
Option Explicit

Sub same_old_same_old()
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim d As Long, dMNUMs As Object

    Set ws1 = ActiveWorkbook.Worksheets("Master Sheet")
    Set ws2 = ActiveWorkbook.Worksheets("Sheet 2")
    Set dMNUMs = CreateObject("Scripting.Dictionary")
    dMNUMs.CompareMode = vbBinaryCompare

    '1. Build a dictionary of match codes and filter on those.
    With ws2
        For d = 2 To .Cells(Rows.Count, "A").End(xlUp).Row
            dMNUMs.Item(CStr(.Cells(d, "A").Value2)) = .Cells(d, "E").Value2
        Next d
    End With

    '2. Copy everything filtered over to the second worksheet.
    With ws1
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Cells(1, 1).CurrentRegion
            .AutoFilter Field:=1, Criteria1:=dMNUMs.keys, Operator:=xlFilterValues
            With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
                If CBool(Application.Subtotal(103, .Cells)) Then
                    .Cells.Copy _
                      Destination:=ws2.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                End If
            End With
        End With
        If .AutoFilterMode Then .AutoFilterMode = False
    End With

    '3. Remove duplicates based on match code and data number.
    '4. [optional] Sort the new data
    With ws2
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=Array(1, 5), Header:=xlYes
            .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
                        Key2:=.Columns(5), Order2:=xlAscending, _
                        Orientation:=xlTopToBottom, Header:=xlYes
            End With
    End With

    dMNUMs.RemoveAll: Set dMNUMs = Nothing

End Sub


text:
Q: Java class path in manifest not starting libraries I have compiled a .jar file and I edited the archive of the MANIFEST.MF to add the Class-Path
I have a couple libraries that I need to be in the class-path in order to run the application, here is my classpath:
Class-Path: lib\commons-net-3.1.jar lib\org.eclipse.swt-3.1.jar lib\prompt.jar lib\zip4j_1.3.2.jar

the folder config is like so:
Root directory ('dist'):
-lib folder
-myProgram.jar
So what am I doing wrong for the class-path not to recognize the libraries in the lib folder?

A: You should use slashes instead of backslashes. Also make sure that the manifest ends with an empty line.

A: Use
  lib/org.eclipse.swt-3.1.jar

instead of
  lib\org.eclipse.swt-3.1.jar

when adding libs in manifest
  Class-Path: lib/commons-net-3.1.jar lib/org.eclipse.swt-3.1.jar lib/prompt.jar lib/zip4j_1.3.2.jar


text:
Q: No actualizar un campo updateOrCreate Laravel Estoy utilizando el metodo updateOrCreate de laravel y para un caso necesito insertar un valor si no existe.
$newproduct = PendingDocument::updateOrCreate(
 ['docentry' => $docentry],
 ['documento' => $documento,
 'cardname' => $cardname,
 'doctotal' => $doctotal,
 'totaldeuda' => $doctotal,
 'tipodecobro' => 'Vencimiento en 30 días',
 'deleted' => "ACTUALIZADO",
 ]
);

Para este caso necesito insertar un valor cuando no existe el registro, e insertar en el tipocobro el valor vencimiento en 30 dias ahora si existe este docentry en mi base de datos no inserte nada, se salte este campo, como debo cambiar mi codigo para esto? es posible poner una condicional aqui? de ser asi como seria el codigo? he probado con un if asi
if('tipodecobro' == null){'tipodecobro' => 'Vencimiento en 30 días'},  pero esto me da error...

A: lo que debes hacer es un condicional de una sola linea con el codigo que tienes arriba te debe de quedar algo asi:
$newproduct = PendingDocument::updateOrCreate(
        [
            'docentry' => $docentry
        ],
        [
            'documento' => $documento,
            'cardname' => $cardname,
            'doctotal' => $doctotal,
            'totaldeuda' => $doctotal,
            'tipodecobro' => $docentry ? null : 'Vencimiento en 30 días',
            'deleted' => "ACTUALIZADO",
        ]
    );

esto lo que hace es validar (con un if de una sola linea) si la variable $docentry es null el campo tendra Vencimiento en 30 días si no el campo quedara null
Espero haberte ayudado saludos.


text:
Q: How is it that the same find command can give two different results? This has happened to me twice (EDIT: many times and I can replicate it) now.  I'm working on a Raspberry Pi, looking for a file I already know exists and so I type this command:
sudo find / -iname 'firefox_binary.py'

The first time I type it, it runs without errors, but it doesn't find the file. However, when I run the same command only seconds later, it finds it.
It's the same command, run in the same terminal window, under the same path, on the same system, with the same file structure, with only a few seconds separating the first run from the second run. How is this result even possible?

A: Given the findings above, as workaroud you could try to either restrict the search to /usr
sudo find /usr -iname 'firefox_binary.py'

or skip /sys in one of the following ways, whatever suits your use case best:
sudo find / -mount -iname 'firefox_binary.py'

sudo find / -not -path '/sys/*' -iname 'firefox_binary.py'

Another, but IMHO more ugly workaround would be to try triggering the population of the problematic dir(s) before searching, e. g. with
ls /sys/kernel/debug/tracing/options

or
cat /sys/kernel/debug/tracing/options/<some_file>

or whatever it takes.
I also suggest you file a bug report with the maintainers of your find (probably either busybox or findutils). I think find shouldn't just exit the recursion in this case, and at least it mustn't without an error message.

A: This is a real bug found in find version 4.4.2, but the bug has been fixed in find version 4.6.0.


text:
Q: unicode equal comparison failed to convert both arguments to unicode I need to use Flask for a school project:
I have installed Python 2.7.10 and pip
When trying to install Flask using: pip install flask, I get the following error:
unicode equal comparison failed to convert both arguments to unicode

Any ideas about what the problem might be?
I'm on Windows by the way.
Thank you


text:
Q: Fading in a UIView shadow while resizing I am attempting to scale my UIView at the same time as I fade in a shadow, using the following:
    myController.view.layer.shadowOffset = CGSizeMake(0, 3);
    myController.view.layer.shadowColor = [UIColor blackColor].CGColor;
    myController.view.layer.shadowOpacity = 0.0;
    myController.view.layer.shadowPath = [UIBezierPath bezierPathWithRect:myController.view.bounds].CGPath;

    [UIView animateWithDuration:0.3
                     animations:^{
                         //shrink the view
                         myController.view.transform = CGAffineTransformMakeScale(0.8, 0.8);

                         //fade in the shadow
                         myController.view.layer.shadowOpacity = 0.8;
                     }
                     completion:^(BOOL finished){
                          ...etc

The view resizes correctly but the shadow appears immediately instead of fading in.
Am I doing something wrong? I thought the shadowOpacity was animatable?

A: You have to use Core Animations to animate a views layer property:
#import <QuartzCore/CAAnimation.h>

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"shadowOpacity"];
animation.fromValue = [NSNumber numberWithFloat:1.0];
animation.toValue = [NSNumber numberWithFloat:0.8];
animation.duration = 1.0;
[myView.layer addAnimation:animation forKey:@"shadowOpacity"];
myView.layer.shadowOpacity = 0.0;


text:
Q: how to retrieve Apache ignite cached Cassandra table in sorted format in JAVA? I am using spring-boot code for loading data from Cassandra table called "test". I have defined group index and mentioned the order of persistence but when I am trying to get all records using "findAll()" method the data is not coming in a sorted way.
please let me know am I going in a wrong way. Because I am not sure how to retrieve cache table data in a sorted way.
cassandra table:
create table test(key int primary key, city text, location text, subscribers int);

java object:
public class Test {

    @QuerySqlField(orderedGroups = { @QuerySqlField.Group(name = "city_subscriber_location", order = 0) })
    String city;
    @QuerySqlField(orderedGroups = {
            @QuerySqlField.Group(name = "city_subscriber_location", order = 1, descending = true) })
    int subscribers;
    @QuerySqlField(orderedGroups = { @QuerySqlField.Group(name = "city_subscriber_location", order = 2) })
    String location;
}

xml file:
<persistence keyspace="ignite" table="test" ttl="86400">
    <keyspaceOptions>
        REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : 1}
        AND DURABLE_WRITES = true
    </keyspaceOptions>
    <tableOption>
        comment = 'Cache test'
        AND read_repair_chance = 0.2
    </tableOption>
    <keyPersistence class="java.lang.Integer" strategy="PRIMITIVE" column="key"/>
    <valuePersistence class="com.cache.business.model.Test" strategy="POJO"/>
</persistence>

configuration:
public Ignite igniteInstance() {
    IgniteConfiguration cfg = new IgniteConfiguration();
    cfg.setIgniteInstanceName("ignite-1");
    cfg.setPeerClassLoadingEnabled(true);
    cfg.setMetricsLogFrequency(0);

    DataSource dataSource = new DataSource();

    dataSource.setContactPoints(environment.getProperty("cassandra.contact-points"));
    RoundRobinPolicy robinPolicy = new RoundRobinPolicy();
    dataSource.setLoadBalancingPolicy(robinPolicy);
    dataSource.setReadConsistency("ONE");
    dataSource.setWriteConsistency("ONE");

    CacheConfiguration<Integer, Test> ccfg2 = new CacheConfiguration<>("test");// table name
    ccfg2.setIndexedTypes(Integer.class, Test.class);
    //ccfg2.setWriteBehindEnabled(true);
    ccfg2.setReadThrough(true);
    ccfg2.setWriteThrough(true);

    CassandraCacheStoreFactory<Integer, Test> f2 = new CassandraCacheStoreFactory<>();
    f2.setDataSource(dataSource);

    KeyValuePersistenceSettings persistenceSettings = new KeyValuePersistenceSettings(
            new ClassPathResource("test.xml"));// corresponding xml file

    f2.setPersistenceSettings(persistenceSettings);

    ccfg2.setCacheStoreFactory(f2);

    cfg.setCacheConfiguration(ccfg, ccfg2);

    /**
     * Start Ignite server and load cache for all the cache configurations
     */
    Ignite ignite = Ignition.start(cfg);

    IgniteCache<Integer, Test> cache = ignite.getOrCreateCache("test");

    cache.loadCache(null);

    return ignite;
}

output:
[
  {
    "city": "mumbai",
    "subscribers": 986,
    "location": "marthalli"
  },
  {
    "city": "mumbai",
    "subscribers": 427,
    "location": "centra"
  },
  {
    "city": "mumbai",
    "subscribers": 739,
    "location": "krmarket"
  },
  {
    "city": "hyd",
    "subscribers": 637,
    "location": "krmarket"
  },
  {
    "city": "bgr",
    "subscribers": 575,
    "location": "krpuram"
  }

I am not getting output in sorted format. please help me to solve the issue.

A: we shouldn't use findAll method of ignite repository.
use below way to query
@Query("SELECT subscribers FROM test where city = ?")
    List<Integer> selectAll(String city);


text:
Q: zf2: Pass dynamic data to Select in FormCollection i try to work with zf2 form collection.
After uploading an exam i got an array of ExamQuestion objects and i want to provide a form where the user can select the subject for each of these questions.
The available subjects come from the database.
My first problem is, that i don't know how to set the dynamic value_options for the Select elements in the Zend\Form\Element\Collection fieldsets. If you read the following simplified code you will get my idea for a solution:
class ExamController {
    public function questionAction() {
        // parse exam ...

        $questions = $parser->getQuestions();
        $subjects = Subject::sorted()->get();

        $form = new ExamQuestionForm($questions, $subjects);
        $this->viewModel->setVariable('form', $form);
        return $this->view();
    }
}

class ExamQuestionForm {
    public function __construct($questions, $subjects) {
        parent::__construct('examquestionform');

        $this->add(array(
            'type' => 'Zend\Form\Element\Collection',
            'name' => 'questions',
            'options' => array(
                'label' => 'Prüfungsfragen',
                'count' => count($questions),
                'should_create_template' => true,
                'allow_add' => true,
                'target_element' => array(
                    'type' => 'Application\Form\QuestionFieldset',
                ),
            ),
        ));

        $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                'value' => 'Speichern',
                'id' => 'submitbutton',
            ),
        ));

        /*
         * The following code does not work.
         * $collection->getFieldsets() returns an empty array.
         * But the form is rendered if i remove that so the fieldsets must be there?
         */
        $collection = $this->get('questions');
        $questionFieldsets = $collection->getFieldsets();
        for ($i = 0; $i < count($questions); $i++) {
            $questionFieldsets[$i]->setQuestion($questions[$i]);
            $questionFieldsets[$i]->setSubjects($subjects);
        }
    }
}

class QuestionFieldset extends Fieldset {
    public function __construct($name = null) {

        parent::__construct('question');

        /*
         * Here should be a plain text element for the question text.
         */

        $this->add(array(
            'name' => "subject",
            'type' => 'Select',
            'options' => array(
                'label' => 'Fach',
                'value_options' => array(),
            ),
        ));
    }

    /**
     * Prepares the fieldset with question data.
     *
     * @param \ExamQuestion $question
     */
    public function setQuestion($question) {
        $this->setLabel('Frage '.$question->number);
        // Here the plain text element from above should be added ...
    }

    /**
     * Adds passed subjects as options in subject select element.
     *
     * @param array $subjects Subject objects.
     */
    public function setSubjects($subjects) {

        $valueOptions = array();
        foreach ($subjects as $subject) {
            $valueOptions[$subject->id] = $subject->name;
        }
        $this->get('subject')->setValueOptions($valueOptions);
    }
}

The template is simple:
<?php
$form = $this->form;
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formCollection($form->get('questions'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>

This seems not to be the right way to do this. And even it does not work.
Can anyone explain how to handle this task correctly?

A: Finally i got a solution by myself.
Firstly the $collection->getFieldsets() method only works correctly if you call $form->prepare() before. So its not a good way to pass data to your collection fieldsets because prepare() function should be called in the view template.
A possible solution is not to configurate the collection and manipulate its fieldsets afterwards but to create and prepare the fieldsets by yourself in the code and add them to an empty collection. Be aware that each of the fieldsets needs a unique name.


text:
Q: Swipe button doesn't show at cell I have a UIViewController with tableView and custom cell. I want to add swipe delete button to cell. When i used UITableViewController and define editActionsForRowAtIndexPath swipe button works well. But now it doesn't appear. Swipe action is working, but button is not appear. What i'm doing wrong ?
    class CartViewController: UIViewController,  UITableViewDataSource, UITableViewDelegate {
        @IBOutlet weak var tableView:UITableView!

        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            ...
            return items_count
        }
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

              ...
        }

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
        let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete",handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
                ...
            })
        return [deleteAction]
    }

}


text:
Q: SQL Server : select columns not by name Is it possible in SQL Server 2008 to select columns not by their names, but in the order as they appear in the table?
The reason is that i want to select the first 5 oder 6 columns of a table, no matter what's the content, because it is possible that their names or the columns self can be changed or moved.

A: For the first 5 columns you can try this:
select column_name,ordinal_position
  from information_schema.columns
 where table_schema = ...
   and table_name = ...
   and ordinal_position <= 5

Hope this works now.
Solution found here.
Edit: Updated answer - old one only selected first 5 rows, not columns.


text:
Q: How to use Angular's limitTo in conjunction with bootstrap responsiveness? I'm building an application using the responsive utilities provided by Bootstrap backed by AngularJS. Consider the following scenario. I'm displaying information in a grid like fashion. On larger displays, the grid has dimensions of 2 x 3. On medium displays, the grid dimensions switches to 2 x 2, and on smaller displays, it switches to 1 x 2. Pagination is implemented to allow paging through more items.
As you can see, due to the dimensional changes, the number of items I am displaying at any given time may change (6 items in large, 4 in medium, and 2 in small).

Items constructed by:
var breakOn = 3;  // This could vary depending on dimensions
var items = [];
for (var i = 0; i < data.length; i += breakOn) {
  items.push(data.slice(i, i + breakOn));
}

I default to showing 6 items (2 x 3), so obviously in smaller form factors, the items begin to overflow because it's attempting to render too many.
My question is: is it possible to use something like limitTo to somehow limit the number of items I am showing (depending on the dimensions)? Does a pattern exist to handle a situation such as this?

A: BootStrap will happily go to the next row for you. Just leave all your items in a flat array (allItems), and use

        {{ item }}

Suppose you have 8 items. On large displays, they will look like
1 2 3
4 5 6
7 8

on medium displays, they will look like
1 2
3 4
5 6
7 8

A: I'm trying to solve this exact situation. This works to hide extra items on smaller displays:
@media (max-width: @screen-sm-max) {
    li:nth-child(n+5) {
        display: none;
    }
}

So I have 6 elements in the array being used by ng-repeat: on md and lg all are displayed, but on sm and xs displays only the first 4 items will be visible.
This is not ideal as it doesn't fully solve the problem. Say I want to only display full rows - so on lg displays it will have either one row of 3 items or two rows of 3 items, on sm screen it will have either one row of 2 items or two rows of 2 items.
We can do this:
@media (max-width: @screen-sm-max) {
    // hide any more than 4 items on small screens
    li:nth-child(n+5) {
        display: none;
    }

    // if we have 3 items, only display the first 2
    ul.count-3 li:nth-child(n+3) {
        display: none;
    }
}

@media(min-width: @screen-md-min) {
    // if we have 4 or 5 items, hide any more than the first 3
    ul.count-4, ul.count-5 {
        li:nth-child(n+4) {
            display: none;
        }
    }
}

Then in the angular template:


text:
Q: Show that the determinant of jordan normal form wtih spatial weight matrix by its eigenvalues I try to figure out the proof of determinant of matrix by eigen decomposition,
$$det(I_n-\lambda W)=det(QQ^{-1}(I_n-\lambda W))$$
$$=det(Q(I_n-\lambda W)Q^{-1})$$
$$=(1-\lambda \upsilon_1)(1-\lambda \upsilon_2)...(1-\lambda \upsilon_n)$$
where $\lambda$ is spatial autoregressive coefficient, $W$ is normalized weight matrix, $\upsilon$ is eigenvalues of $W$, $Q$ is the matrix that trinagularizes $W$.
1.i can't figure out how changes taking place of the $Q^{-1}$ matrix in front of $(I_n-\lambda W)$ in the first equation to behind of $(I_n-\lambda W)$ in the second equation? is there any proporties for that?
2.why do need $W$ is triangularized? can it be proof without triangularized?
I would really appreciate some help.

A: So we know (given) that there is a $Q$ such that $QWQ^{-1}$ is triangular. The first step is to introduce $Q$
$$\det(I - \lambda W) = \det( Q^{-1}Q(I-\lambda W))$$
Second let's use the property $\det(AB) = \det(BA)$ where $A = Q^{-1}$ and $B = Q(I-\lambda W)$ hence
$$\det(I - \lambda W) = \det(Q(I-\lambda W) Q^{-1})$$
Third, expand the above
$$\det(I - \lambda W) = \det(QQ^{-1}-\lambda Q W Q^{-1} )$$
Notice that $QQ^{-1} = I$ again so
$$\det(I - \lambda W) = \det(I-\lambda Q W Q^{-1} )$$
Fifth denote our triangular matrix $QWQ^{-1} = T$ hence
$$\det(I - \lambda W) = \det(I-\lambda T )$$
Notice that $I - \lambda T$ is also triangular with diagonal elements $1 - \lambda v_1$, where $v_k$ appear on the diagonal entries of $T$. Using the fact that the determinant of a triangular matrix is nothing other than the product of it's diagonal entries, then
$$\det(I - \lambda W) =(1 - \lambda v_1)\ldots(1-\lambda v_n)$$

A: *

*Just think of a theorem saying that $$\det(AB)=\det(A)\det(B)$$so we have $$\det(AB)=\det(BA)$$2. sure it can be proved in such way. Probably in your problem the matrix is particularly triangular but it doesn't require to remain so. To show that the key idea is that $$\text{the determinant of a matrix is multiplication of all its eigenvalues}$$can you finish this one?


text:
Q: error CS0103: The name "ressourcesText" does not exist in the current context I set up a string named ressourcesText, which will be set as the text LblRessources
This is the code for this problem :
public void ressources()
{
    string ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressourcesText;
}

How can the text for LblRessources use the string ressourcesText? It usually worked this way.

A: The issue with your code is that ressourcesText is declared locally in the ressources() function.
Variables that are declared within { } brackets are destroyed at the end of the bracket, and are called local variables.
To solve this you could make your variable global:
string ressourcesText;
public void ressources()
{
    ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressourcesText;
}

Now this isn't necessarily good practice, because at the time of declaring your variable, it will be null, and thus can not be used until you call ressources().
Another alternative would be to return the variable through the ressources() function and calling it directly to retrieve the value, like follows:
public string ressources()
{
    string ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
    return ressourcesText;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressources();
}

That's somewhat safer.
You should check out these links for more info:
Local variables
C# Methods
Scopes


text:
Q: When Bootstrap button is clicked it changes to primary state This question might seem to be a duplicate, but the other solutions are not working for me.
My problem is whenever I click my customized Bootstrap button it changes to the btn-primary style.
Customized button:

Button clicked:

When I search for a solution, I only find them with btn:active:focus.
I've tried this but it didn't do the trick for me.
My CSS:
.btn-custom01 {
    background-color:#3b3b3b;
    border-color:#ff0066;
}
.btn-custom01:active:focus{background-color:#333333; border-color:#ff0066; color:#ff0066; }
.btn-custom01:hover{background-color:#3b3b3b; border-color:#f2f2f2;}

How do I fix this? I hope someone here can help me out.

A: Looks like you're chaining your element state, remove active from the chain and focus starts working. If you want both, separate them differently.

.btn-custom01 {
  background-color: #3b3b3b;
  border-color: #ff0066;
}

.btn-custom01:focus {
  background-color: #333333;
  border-color: #ff0066;
  color: #ff0066;
}

.btn-custom01:hover {
  background-color: #3b3b3b;
  border-color: #f2f2f2;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" />
<button class='btn btn-custom01'>Hello World</button>

A: Use .btn-custom01:focus
.btn-custom01 {
  background-color: #3b3b3b;
  border-color: #ff0066;
}

.btn-custom01:active:focus {
  background-color: #333333;
  border-color: #ff0066;
  color: #ff0066;
}

.btn-custom01:hover,
.btn-custom01:focus {
  background-color: #3b3b3b;
  border-color: #f2f2f2;
}

A: Use the visited selector https://www.w3schools.com/cssref/sel_visited.asp
btn:visited {}


text:
Q: Draw Electrical Characteristics using tikz How can i draw any one of the following transfer characteristics using tikz?
Especially arrows between the nodes?

A: \documentclass[tikz,margin=3.14mm]{standalone}
\usetikzlibrary{arrows.meta,decorations.pathmorphing}
\begin{document}
\begin{tikzpicture}
\draw (0,-3) -- (0,3) node[left]{$v_{B1}$};
\draw (0,0) node[left]{0} -- (10,0) node[below left]{$t$};
\draw[very thick] (0,0.1) -- ++(1,0) -- ++(0,-1) coordinate (x1) -- ++(6,0)
coordinate (x2) -- ++(0,1) -- ++(2.5,0);
\draw[{Straight Barb[length=0pt,width=4mm] Latex[]}-{Latex[] Straight Barb[length=0pt,width=4mm]}]
(1,0.5) -- (7,0.5) node[midway,fill=white]{$T_g$};
\node (VBE) at (0.5,1) {$V_{BE}$};
\draw[-{Latex[]}] (VBE)  -- (0.5,0.1);
\draw[-{Latex[]}] (0.5,-0.7) -- (0.5,-0.1);
%
\begin{scope}[yshift=-8.5cm]
\draw (0,-1) -- (0,5) node[left]{$\ell_{C1}$};
\draw (0,0) node[left]{0} -- (10,0) node[below left]{$t$};
\draw[very thick] (0,1) node[left]{$\displaystyle\approx\frac{V_{CC}}{R}$} -- ++(1,0)
 -- ++(0,-1) coordinate (y1) -- ++(6,0) -- ++(0,3) coordinate (y2) -- ++(1,0) --
 ++(0,-2) coordinate (y3) -- ++(1.5,0);
\node (ICBO) at (2,1) {$I_{CBO}\approx0$};
\draw[-{Latex[]}] (ICBO)  -- (2,0);
\draw[-{Latex[]}] (2,-0.7) -- (2,0);
\draw (5,3) -- (7,3);
\draw[{Latex[]}-{Latex[]}] (6,3) -- (6,0) node[midway,fill=white]{$\displaystyle
\frac{h_{FC}V_{CC}}{R_C}$};
\draw[thick] (11,3) -- (12,3) (11,1) -- (12,1);
\draw[thick,decorate,decoration={zigzag,pre length=5mm,post length=5mm,segment
length=5mm,amplitude=2.5mm}] (12,3) -- (12,1) node[midway,left=3pt] {$R_i$};
\end{scope}
%
\begin{scope}[yshift=-13cm]
\draw (0,-3) -- (0,3) node[left]{$v_0$};
\draw (0,0) node[left]{0} -- (10,0) node[below left]{$t$};
\draw[very thick] (0,0) -- ++(1,0)
coordinate (z1) -- ++(4,3) coordinate (z4) -- ++(2,0) coordinate (z2) -- ++(1,-3)
coordinate (z3) -- ++(1.5,0);
\draw[{Latex[]}-{Latex[]}] (6,3) -- (6,0) node[midway,fill=white]{$V_{CC}$};
\draw (z1 |-0,0) -- ++ (0,-3) coordinate[pos=1/6] (l1) coordinate[pos=1/2] (l2)
coordinate[pos=5/6] (l3);
\draw (z3 |- 0,0) -- ++(0,-3) coordinate[pos=5/6] (r3);
\draw (z4 |- 0,0) -- ++(0,-1) coordinate[pos=1/2] (m1);
\draw (z2 |- 0,0) -- ++(0,-2) coordinate[pos=3/4] (m2);
\draw[{Latex[]}-{Latex[]}] (l1) -- (m1) node[midway,fill=white]{$T_*$};
\draw[{Latex[]}-{Latex[]}] (l2) -- (m2) node[midway,fill=white]{$T_g$};
\draw[{Latex[]}-{Latex[]}] (l3) -- (r3) node[midway,fill=white]{$T$};
\draw[dashed] (z4) -- (z4 |- 0,0);
\draw[dashed] (x2) -- (z2 |- 0,0);
\end{scope}
\draw[dashed] (x1) -- (z1) node[pos=0.1,fill=white] {$t=0$};
\draw[dashed] (y3) -- (z3);
\end{tikzpicture}
\end{document}


text:
Q: Does this problem contradict the uniqueness theorem? If we have a first order second degree ODE , and we solved it for y' . Then we will get two solutions : one solution using the positive square root and another one using the negative square root .
So do first order second degree ODE contradict always the uniqueness theorem at all points (x,y) ?
For example the following ODE:
$$x^2y^2y'^2-(x^2+y^2)y'+1=0$$
I got from positive square root , this solution :
$$x=\frac{y^3}{3}+c_1$$
From negative square root , we obtain this solution:
$$y=\frac{x^3}{3}+c_2$$
OR we have to look to the solution as one equation :
$$(x-\frac{y^3}{3}-c_1)(y-\frac{x^3}{3}-c_2)=0$$
So this does not contradict the uniqueness theorem ? and if it contradicts how to know which points have more than one solution ?


text:
Q: Python: User Input and Invalid returns I'm trying to create a program in python where the user will enter a temperature and units having the program convert the temperature to Kelvins. For the code, I need help on detecting the case where either input is invalid, and having a None return value if the input is invalid.
cas_number = "7732-18-5"
rho = 1000
mu = 1
Tm = 273.15
Tb = 373.13
k = 0.58

units = input("Input desired units, 'K' for Kelvin, 'C' for Celsius, and 'F' for Fahrenheit \n")

temperature = input("Input temperature value \n")

def check_units(units):
    if units == 'F' or units == 'C' or units == 'K':
        return True
    else:
        print("Invalid Input")
        return False

def check_temperature(temperature):
    try:
        float(temperature)
        return True
    except:
        return False

def convert_to_kelvin(temperature, units):
    if check_temperature == True and check_units == True:
        if units == 'K':
            temperature = temperature
            return temperature
        elif units == 'C':
            temperature += Tm
            return temperature
        elif units == 'F':
            temperature = (temperature - 32)/1.8 + Tm
            return temperature
    else:
        print("Invalid Input")
        return

def is_gas(temperature):
    if check_temperature and check_units:
        if temperature >= Tb:
            return True
        elif temperature < Tb:
            return False
    else:
        return None

def is_liquid(temperature):
    if check_temperature and check_units:
        if temperature > Tm and temperature < Tb:
            return True
        elif temperature <= Tm and temperature >= Tb:
            return False
    else:
        return None

def is_solid(temperature):
    if check_temperature and check_units:
        if temperature <= Tm:
            return True
        elif temperature > Tm:
            return False
    else:
        return None

A: def check_units(units):
    if units == 'F' or units == 'C' or units == 'K':
        return True
    else:
        return None

Test the check_units()
units = input("Input desired units, 'K' for Kelvin, 'C' for Celsius, and 'F' for Fahrenheit \n")

input_check = check_units(units) # calling the function

if input_check == True:
    print('Valid input')
if input_check == None:
    print('Invalid input')

Your check_temperature() is messed up.  After you get the input, you can convert it to float, like so:
temperature = input("Input temperature value \n")
temperature = float(temperature)

Or
temperature = float(input("Input temperature value \n"))


text:
Q: tSqlt - Unit Testing Procedures which output XML using Schema Collections We are currently developing SQL stored procedures for an integration project which requires XML payloads, which we have implemented using Schema Collections to ensure strict adherence to the defined schema.
We want to write unit tests for these stored procedures but given the output is XML, I am not sure how ( or if ) I can do this with the assert stored procedures in tsqlt (without having to convert everything into a table / table variable.)
Can someone please point me in the right direction - whether it can/can't be done, and if its not possible, how should I approach trying to create a new asset stored procedure for XML payloads ?
Or would we save a lot of time / heartache by simply converting the expected and actual results from XML into tables in each test ?
Thanks

A: If you are dealing with the situation that the order of nodes might change, then converting the XML to tables might be your best bet.
If the order of nodes and attributes is fixed in your output, you could convert the XML to an NVARCHAR(MAX) and then use tSQLt.AssertEqualsString.


text:
Q: Combination with no repeat in Excel including reducing rows My dataset looks like this
AAAA
BBBB
CCCC
DDDD
EEEE
FFFF

I want to delete the first and second row and then I want to delete the first and third line and then the first and fourth and so on.
Next, second and third line, second and fourth line and so on.
CCCC   BBBB   BBBB
DDDD   DDDD   CCCC
EEEE   EEEE   EEEE
FFFF   FFFF   FFFF

Does anyone have an idea how I can implement it in Excel?

A: Much more suited to VBA, though given that your dataset is limited to six items this can also be achieved with Office 365 formulas:
=LET(ζ,A1:A6,ξ,SEQUENCE(5556,,1111),λ,FILTER(ξ,MMULT(N(ISNUMBER(FIND(SEQUENCE(,6),ξ))),SEQUENCE(6,,,0))=4),TRANSPOSE(INDEX(ζ,UNIQUE(MAKEARRAY(ROWS(λ),4,LAMBDA(α,β,SMALL(0+MID(INDEX(λ,α),SEQUENCE(,4),1),β)))))))

A: Please, test the next code. It will process the range you show, located in "A1:A" & x and returns starting from "C2":
Sub RemoveIncrementedRows()
  Dim arr, arrRes, i As Long, k As Long, c As Long, lastR As Long

  'the range to be processed should be in "A1:A"
  lastR = Range("A" & rows.count).End(xlUp).row
  arr = Range("A2:A" & lastR).Value2 'place the range in an array for faster iteration
  ReDim arrRes(1 To UBound(arr) - 1, 1 To UBound(arr) - 1) 'ReDim the result array
  For k = 1 To UBound(arrRes)
    For i = 1 To UBound(arr)
           If i <> k Then
               c = c + 1
               arrRes(c, k) = arr(i, 1)
          End If
    Next i
    c = 0 'reinitialize the variable to keep the result array rows
  Next k
  'drop the result array content at once (in "C2")
  Range("C2").Resize(UBound(arrRes), UBound(arrRes, 2)).Value2 = arrRes
End Sub

It is able to process more values situated in "A:A", calculating the last row.
I suppose that "AAAA", "BBBB", etc. are there only like examples and you will use different strings. Otherwise, an array containing that strings could also be automatically built...

A: I've been playing around with this for a while and wondered if I could take OP's instructions literally and exclude the first and second, first and third rows etc. from the full set of 90 rows to leave 60 rows, then reshape the array into 15 sets of four:
=LET(n,6,r,4,C,COMBIN(n,r),range,A2:A7,
rows,SEQUENCE(n*C,1,0),
pairs,SEQUENCE(n*n,1,0),
filterPairs,FILTER(pairs,MOD(pairs,n)>QUOTIENT(pairs,n)),
filter,INDEX(filterPairs,QUOTIENT(rows,n)+1),
filterRows,FILTER(rows,(MOD(rows,n)<>QUOTIENT(filter,n))*(MOD(rows,n)<>MOD(filter,n))),
select,MOD(filterRows,n)+1,
WRAPCOLS(INDEX(range,select),r))


text:
Q: Hybrid batch & VBS autorun as Administrator I'm getting strange error "Unterminated entity reference" in a hybrid batch & VBS, which popups the UAC "Run as Admin" Dialog using an adaptation of this code, and then proceeds with unzipping a file to a folder on the system drive. The hybrid is structured similar to suggested here, and changing it is undesirable.
Tried adding CDATA VBS blocks without success. Restructuring the batch to replace :GetAdminRights function with the same section inside it doesn't help. Any ideas, what's wrong here?
<!-- : Begin batch script
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set vbs="%temp%\_.vbs" & set "dir=C:\Unzip"
set "file=%USERPROFILE%\Downloads\archive.zip\"
call :GetAdminRights
cscript //nologo "%~f0?.wsf" //job:UNZ "%dir%" "%file%"
exit /b

:GetAdminRights
REM  --> Check for permissions
IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system")
REM --> If error flag set, user don't have admin permissions
if '%errorlevel%' NEQ '0' (echo Requesting administrative privileges...
) else (set "adm=1")
if not defined adm (set params = %*:"=""
    cscript //nologo "%~f0?.wsf" //job:ADM %~s0 !params!
) else (pushd "%CD%" & CD /D "%~dp0")
exit /b

----- Begin wsf script --->
<package>
    <job id="ADM"><script language="VBScript">
        <![CDATA[
        Set UAC = CreateObject("Shell.Application")
        UAC.ShellExecute "cmd.exe", "/c ""wscript.Arguments(0)"" wscript.Arguments(1)", "", "runas", 1
        ]]>
    </script></job>
    <job id="UNZ"><script language="VBScript">
        <![CDATA[
        set fso = CreateObject("Scripting.FileSystemObject")
        If NOT fso.FolderExists(wscript.Arguments(0)) Then
        fso.CreateFolder(wscript.Arguments(0))
        End If
        set objShell = CreateObject("Shell.Application")
        set FilesInZip = objShell.NameSpace(wscript.Arguments(1)).items
        objShell.NameSpace(wscript.Arguments(0)).CopyHere(FilesInZip)
        set fso = Nothing
        set objShell = Nothing
        ]]>
    </script></job>
</package>

::Error
\test.bat?.wsf(44, 12) Windows Script Host: Unterminated entity reference - matching ';' not found

A: This fixed script works well. It represents a hybrid script example, which can elevate a user to Admin rights for the duration of the Cmd session, and allows to run other user tasks added as VBS jobs. Characters < > must be avoided in batch segments of the hybrid, since they identify ignored by WSF batch sections.
<!-- : Begin batch script
@echo off
setlocal EnableExtensions EnableDelayedExpansion
CD /D "%~dp0"
set "dir=%temp%\Unzip" & set "file=%USERPROFILE%\Downloads\archive.zip"
if not "%1"=="ADR" (call :GetAdminRights
    if defined adm cscript //nologo "%~f0?.wsf" //job:ADM "/c" "%~sf0" "ADR" )
echo/ & >nul 2>&1 net file && (echo "!errorlevel!" Got admin rights & echo/) ^
 || (echo "!errorlevel!" No admin rights & goto :end)

:: add your code here
echo Performing admin tasks & echo/
cscript //nologo "%~f0?.wsf" //job:UNZ "%dir%" "%file%"
if !errorlevel! equ 0 echo All tasks completed.

:end
timeout /t 5 >nul
exit /b

:GetAdminRights
REM Check for permissions
echo/ & >nul 2>&1 net session && (echo "!errorlevel!" Got admin rights) ^
 || (echo "!errorlevel!" No admin rights) & echo/
REM If error flag set, user don't have admin permissions
if '!errorlevel!' NEQ '0' (set "adm=0" & echo Requesting admin rights...)
exit /b

----- Begin wsf script --->
<package>
    <job id="ADM"><script language="VBScript">
        Set UAC = CreateObject("Shell.Application")
        args = ""
        For Each strArg in WScript.Arguments
        args = args & strArg & " "
        Next
        UAC.ShellExecute "cmd.exe", args, "", "runas", 1
    </script></job>
        <job id="UNZ"><script language="VBScript">
        set fso = CreateObject("Scripting.FileSystemObject")
        If NOT fso.FolderExists(wscript.Arguments(0)) Then
        fso.CreateFolder(wscript.Arguments(0))
        End If
        set objShell = CreateObject("Shell.Application")
        set FilesInZip = objShell.NameSpace(wscript.Arguments(1)).items
        objShell.NameSpace(wscript.Arguments(0)).CopyHere(FilesInZip)
        set fso = Nothing
        set objShell = Nothing
    </script></job>
</package>


text:
Q: If Two Filenames in Two Separate Directories Match, Then I have a set of files within two different directories that are similar in the fact that for every file in directory A there is a file in directory B that shares the same first four characters in the prefix (the subject ID). For instance,
Directory A contains files:
001FileNameX,
002FileNameX,
003FileNameX,
etc.
and Directory B contains files:
001FileNameY,
002FileNameY,
003FileNameY,
etc.
What I am trying to create is a macro loop that:

*

*Searches both directories until it finds a set of file names that share the same first four characters (e.g. match 001FileNameX in Directory A with 001FileNameY in Directory B)

*If it finds a matching set, I want it to execute a piece of code. In this case, I want it to copy and paste a range of cells from the file (workbook) in Directory A to the file (different workbook)in Directory B and then close the workbooks (saving the changes to the workbook in Directory B).

*Then return to the directories and find the next set of matching file names and so on until there are no matches remaining.

I am generally able to use wildcards to search similar files, but this case is different due to the increased specificity- I need the filenames from TWO different directories to MATCH using the first four characters in the prefixes and then loop while allowing the next prefix of four characters to be different from the last prefix. Does anyone have any ideas about how to go about solving this issue?
Below is an example of a code I generally use when the prefixes do not matter or do not change and the workbook I am copy/pasting from is also static. Thanks so much for any help!

Sub Insert_Template_With_Formulas()
Dim FNames As String
Dim DirectoryA As String

DirectoryA = Cells(2, 2).Value

ChDrive DirectoryA
ChDir DirectoryA

' Open any file containing "Resps.xlsx", regardless of prefix

 FNames = Dir("*Resps.xlsx")
    If Len(FNames) = 0 Then
        MsgBox "No files in the Directory"
        Exit Sub
    End If

Application.ScreenUpdating = False

Do While FNames <> ""

        Workbooks.Open ("Resps_Template.xlsx")
            Range("AL1:BX32").Select
            Selection.Copy

        Workbooks.Open (FNames)
            Range("AL1").Select
            ActiveSheet.Paste

    ActiveWorkbook.Save
    ActiveWorkbook.Close

    Workbooks("Resps_Template.xlsx").Close SaveChanges:=False

    ChDrive DirectoryA
    ChDir DirectoryA

    ' Call Dir again without arguments to return the next file in the same
      directory

     FNames = Dir()

Loop

Application.ScreenUpdating = True

End Sub

A: Get in array list of all filenames only (w/o path) in Directory A by loop:
Dir("FullPAth\Directory A\", vbNormal) with the following Dir w/o parameters.
Then iterate this array and check for non-zero results of similar command as:
Dir("FullPAth\Directory B\" & sArr(i), vbNormal).
.


text:
Q: Finding Prime Number with input N in assembly This is a code from this link from stackexchange:
MIPS Assembly code to find all the prime numbers below an inputted number
I am studying this for my exam, but how would I fix this code to make it so that it prints out prime numbers from 2-N
As the post in the link, I was able to complete step two from the answer but am currently having difficultly implementing step 1 in the code
Here are the two problem that occur in the code:
There are two problems:

*

*When you increment i you forget to set j back to 2. L3 should be moved 1 line
up. (difficulty implementing this)

*ble in MIPS is less than or equal to, so your code is actually checking j <=
i, not j < i. This causes your code to check i % j when i = j, which always
has a remainder 0 and will register as not prime. Changing 'ble' to 'blt'
should fix this. Same goes for the i < n check.
Here is the code:
# The number is read through the keyboard
.text
.globl main

 main:
 # Display message to user for a number
 li $v0, 4
 la $a0, prompt1
 syscall

 # read keyboard into $v0 (number x is upper bound number to find primes)
 li $v0, 5
 syscall

 # move the number from $v0 to $t0
 move $t0, $v0 # $t0 = n

 # store 2 in $t1 and $t2
 li $t1, 2 # i
 li $t2, 2 # j

 L3: # for (int i=2; i<n; i++)
 # store 0 in $t3
 li $t3, 0 # p = 0;

 L2: # for (int j=2; j<i; j++)
 # do div of two numbers
 div $t2, $t1

 # store the remainder in $t4
 mfhi $t4

 # branch if remainder is not 0 to L1
 bne $t4, 0, L1 # if (i % j == 0)

 # set $t3 as 1
 li $t3, 1 # p = 1

 # if p=1 break to next i
 beq $t3, 1, L4

 L1: # if (i % j == 0)
 # add 1 to t2
 addi $t2, $t2, 1 # j++

 # repeat code while j < i
 ble $t2, $t1, L2

 # print integer function call 1
 # put the answer into $a0
 li $v0, 1
 move $a0, $t1
 syscall # System.out.println(i)
 #print comma
 li $v0, 4
 la $a0, comma
 syscall

 L4:
 # add 1 to t1
 addi $t1, $t1, 1 # i++

 # repeat code while i < n
 ble $t1, $t0, L3 # for (int i=2; i<n; i++)

 .data
 prompt1:
 .asciiz "Enter a number "
 comma:
 .asciiz ","

Thanks in advance :]


text:
Q: SQL - Guarantee at least n unique users with 2 appearances each in query I'm working with AWS Personalize and one of the service Quotas is to have "At least 1000 records containing a min of 25 unique users with at least 2 records each", I know my raw data has those numbers but I'm trying to find a way to guarantee that those numbers will always be met, even if the query is run by someone else in the future.
The easy way out would be to just use the full dataset, but right now we are working towards a POC, so that is not really my first option. I have covered the "two records each" section by just counting the appearances, but I don't know how to guarantee the min of 25 users.
It is important to say that my data is not shuffled in any way at the time of saving.
My query
SELECT C.productid AS ITEM_ID,
    A.userid AS USER_ID,
    A.createdon AS "TIMESTAMP",
    B.fromaddress_countryname AS "LOCATION"
FROM A AS orders
    JOIN B AS sub_orders ON orders.order_id = sub_orders.order_id
    JOIN C AS order_items ON orders.order_id = order_items.order_id
WHERE orders.userid IN (
        SELECT orders.userid
        FROM A AS ORDERS
        GROUP BY orders.userid
        HAVING count(*) > 2
    )
LIMIT 10

I use the LIMIT to just query a subset since I'm in AWS Athena.

A: The IN query is not very efficient since it needs to compare each row with all (worst case) the elements of the subquery to find a match.
It would be easier to start by storing all users with at least 2 records in a common table expression (CTE) and do a join to select them.
To ensure at least 25 distinct users you will need a window function to count the unique users since the first row and add a condition on that count. Since you can't use a window function in the where clause, you will need a second CTE and a final query that queries it.
For example:
with users as (
    select userid as good_users
    from orders
    group by 1
    having count(*) > 1 -- this condition ensures at least 2 records
),
cte as (
    SELECT C.productid AS ITEM_ID,
    A.userid AS USER_ID,
    A.createdon AS "TIMESTAMP",
    B.fromaddress_countryname AS "LOCATION",
    count(distinct A.userid) over (rows between unbounded preceding and current row) as n_distinct_users
FROM A AS orders
    JOIN B AS sub_orders ON orders.order_id = sub_orders.order_id
    JOIN C AS order_items ON orders.order_id = order_items.order_id
    JOIN users on A.userid = users.userid --> ensure only users with 2 records
order by A.userid -- needed for the window function
)
select * from cte where n_distinct_users < 26

sorting over userid in cte will ensure that at least 2 records per userid will appear in the results.