text:
Q: How to use React-i18next with Table antd I have following Table component created with antd:
import { Table } from "antd";

const dataSource = [
  {
    key: "1",
    name: "Mike",
    age: 32,
    address: "Downing Street"
  },
  {
    key: "2",
    name: "John",
    age: 42,
    address: "Downing Street"
  }
];

const columns = [
  {
    title: "Name",
    dataIndex: "name",
    key: "name"
  },
  {
    title: "Age",
    dataIndex: "age",
    key: "age"
  },
  {
    title: "Address",
    dataIndex: "address",
    key: "address"
  }
];

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

    </>
  );
};

export default CustomTable;

Now I would like to add translations to each columns name. I would like this solution to be obtained with the help of React-i18next
A simple example of using this library is the following code:
const {t} = useTranslation();

t('textToTranslate');

Additionally, I have some translate.json where are my translations key & value like:
{
  "name": "name",
  "age": "age"
}

How I can add translation to each columns -> name?

A: You can change the way of generating columns and use translation as a typical react prop:
const dataSource = [
  {
    key: "1",
    name: "Mike",
    age: 32,
    address: "Downing Street"
  },
  {
    key: "2",
    name: "John",
    age: 42,
    address: "Downing Street"
  }
];

const columns = [
  {
    title: "tableHeadings.name",
    dataIndex: "name",
    key: "name"
  },
  {
    title: "tableHeadings.age",
    dataIndex: "age",
    key: "age"
  },
  {
    title: "tableHeadings.address",
    dataIndex: "address",
    key: "address"
  }
];

const CustomTable = () => {
  const { t } = useTranslation();

  return (
    <>

        {columns.map((column) => (

        ))}

    </>
  );
};

export default CustomTable;


text:
Q: Facebook SDK 2.8 doesnot give email address I am trying to implement FacbookSDK 2.8 for my website and below is the simplified version of the code.
 <button onclick="logout()">Logout</button>
    <button onclick="login()">LogIn</button>
    <script>
        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s);
            js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));
        setTimeout(() => {
            window.fbAsyncInit = () => {
                FB.init({
                    appId: 'xxxxxxx', //My app id here
                    cookie: true, // enable cookies to allow the server to access
                    // the session
                    xfbml: true, // parse social plugins on this page
                    version: 'v2.8' // use graph api version 2.8
                });
                checkFBLoginStatus();
            }
        })

        function checkFBLoginStatus() {
            FB.getLoginStatus((response) => {
                console.log(response)
            });
        }

        function logout() {
            FB.logout(function(response) {
                console.log(response)
            })
        }

        function login() {
            FB.login(function(response) {
                console.log(response)
                FB.api('/me?fields=id,email,name', function(response) {

                    console.log(JSON.stringify(response));
                });
            }, {
                scope: 'email'
            })
        }

        function onLoginSuccess() {
            FB.getLoginStatus(function(response) {
                console.log(response)
            })
        }
    </script>

I am getting the response on logout and login
Here are my questions

*

*On FB.api call i am getting only ID and Name whereas i need user email to set as an unique user identifier.

*When is the condition i can achieve not_authorized. I am getting status 'connected' if i login and 'unknown' if i logout. I am not able to reproduce the condition un_authorized, so that i could code for it.

A: You should use the ID of the user to identify him, not the email. Users do not have to have an email, they can also use their phone number to login. Make sure you get asked for the email permission in the login process/popup. Also, use this form instead:
FB.api('/me', {fields: 'id,email,name'}, function(response) {
    console.log(JSON.stringify(response));
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: can safearrays be passed across process boundaries through com objects? can safearrays be passed across process boundaries through com objects ?

A: As long as you registered the marshaller for the interface, yeah, no problem.  The std marshaller can do it.


text:
Q: Can't deserialize json Can someone help me figure out how to deserialize this using json.net in C#? I have already successfully parsed a different json but its format was different. I've tried to use object and it says it needs to be an array and then I change it to array it says it needs to be an array..
Oh and there can be additional arrays with different "TYPE"..
"[
  {
    "ID": 1,
    "TYPE": 1,
    "APP_TAG": 1,
    "alert": "[13:13] This is a Test Message - 0.",
    "sound": "Default",
    "badge": 0
  }
]"

A: Since it is an array/list
public class Item
{
    public int ID { get; set; }
    public int TYPE { get; set; }
    public int APP_TAG { get; set; }
    public string alert { get; set; }
    public string sound { get; set; }
    public int badge { get; set; }
}

var items = JsonConvert.DeserializeObject<List<Item>>(json);

A: string json = @"[
  {
    'ID': 1,
    'TYPE': 1,
    'APP_TAG': 1,
    'alert': '[13:13] This is a Test Message - 0.',
    'sound': 'Default',
    'badge': 0
  }
]";

var items = Newtonsoft.Json.JsonConvert.DeserializeObject(json);


text:
Q: What is locality of reference? I am having problem in understanding locality of reference. Can anyone please help me out in understanding what it means and what is,

*

*Spatial Locality of reference

*Temporal Locality of reference

A: This would not matter if your computer was filled with super-fast memory.
But unfortunately that's not the case and computer-memory looks something like this1:
+----------+
| CPU      |  <<-- Our beloved CPU, superfast and always hungry for more data.
+----------+
|L1 - Cache|  <<-- ~4 CPU-cycles access latency (very fast), 2 loads/clock throughput
+----------+
|L2 - Cache|  <<-- ~12 CPU-cycles access latency (fast)
+----+-----+
     |
+----------+
|L3 - Cache|  <<-- ~35 CPU-cycles access latency (medium)
+----+-----+       (usually shared between CPU-cores)
     |
     |   <<-- This thin wire is the memory bus, it has limited bandwidth.
+----+-----+
| main-mem |  <<-- ~100 CPU-cycles access latency (slow)
+----+-----+  <<-- The main memory is big but slow (because we are cheap-skates)
     |
     |   <<-- Even slower wire to the harddisk
+----+-----+
| harddisk | <<-- Works at 0,001% of CPU speed
+----------+

Spatial Locality
In this diagram, the closer data is to the CPU the faster the CPU can get at it.
This is related to Spacial Locality. Data has spacial locality if it is located close together in memory.
Because of the cheap-skates that we are RAM is not really Random Access, it is really Slow if random, less slow if accessed sequentially Access Memory SIRLSIAS-AM.  DDR SDRAM transfers a whole burst of 32 or 64 bytes for one read or write command.
That is why it is smart to keep related data close together, so you can do a sequential read of a bunch of data and save time.
Temporal locality
Data stays in main-memory, but it cannot stay in the cache, or the cache would stop being useful. Only the most recently used data can be found in the cache; old data gets pushed out.
This is related to temporal locality. Data has strong temporal locality if it is accessed at the same time.
This is important because if item A is in the cache (good) than Item B (with strong temporal locality to A) is very likely to also be in the cache.

Footnote 1:
This is a simplification with latency cycle counts estimated from various cpus for example purposes, but give you the right order-of-magnitude idea for typical CPUs.
In reality latency and bandwidth are separate factors, with latency harder to improve for memory farther from the CPU.  But HW prefetching and/or out-of-order exec can hide latency in some cases, like looping over an array. With unpredictable access patterns, effective memory throughput can be much lower than 10% of L1d cache.
For example, L2 cache bandwidth is not necessarily 3x worse than L1d bandwidth.  (But it is lower if you're using AVX SIMD to do 2x 32-byte loads per clock cycle from L1d on a Haswell or Zen2 CPU.)
This simplified version also leaves out TLB effects (page-granularity locality) and DRAM-page locality.  (Not the same thing as virtual memory pages).  For a much deeper dive into memory hardware and tuning software for it, see What Every Programmer Should Know About Memory?

Related: Why is the size of L1 cache smaller than that of the L2 cache in most of the processors? explains why a multi-level cache hierarchy is necessary to get the combination of latency/bandwidth and capacity (and hit-rate) we want.
One huge fast L1-data cache would be prohibitively power-expensive, and still not even possible with as low latency as the small fast L1d cache in modern high-performance CPUs.
In multi-core CPUs, L1i/L1d and L2 cache are typically per-core private caches, with a shared L3 cache.  Different cores have to compete with each other for L3 and memory bandwidth, but each have their own L1 and L2 bandwidth.  See How can cache be that fast? for a benchmark result from a dual-core 3GHz IvyBridge CPU: aggregate L1d cache read bandwidth on both cores of 186 GB/s vs. 9.6 GB/s DRAM read bandwidth with both cores active.  (So memory = 10% L1d for single-core is a good bandwidth estimate for desktop CPUs of that generation, with only 128-bit SIMD load/store data paths).  And L1d latency of 1.4 ns vs. DRAM latency of 72 ns

A: First of all, note that these concepts are not universal laws, they are observations about common forms of code behavior that allow CPU designers to optimize their system to perform better over most of the programs. At the same time, these are properties that programmers seek to adopt in their programs as they know that's how memory systems are built and that's what CPU designers optimize for.
Spatial locality refers to the property of some (most, actually) applications to access memory in a sequential or strided manner. This usually stems from the fact that the most basic data structure building blocks are arrays and structs, both of which store multiple elements adjacently in memory. In fact, many implementations of data structures that are semantically linked (graphs, trees, skip lists) are using arrays internally to improve performance.
Spatial locality allows a CPU to improve the memory access performance thanks to:

*

*Memory caching mechanisms such as caches, page tables, memory controller page are already larger by design than what is needed for a single access. This means that once you pay the memory penalty for bringing data from far memory or a lower level cache, the more additional data you can consume from it the better is your utilization.

*Hardware prefetching which exists on almost all CPUs today often covers spatial accesses. Everytime you fetch addr X, the prefetcher will likely fetch the next cache line, and possibly others further ahead. If the program exhibits a constant stride, most CPUs would be able to detect that as well and extrapolate to prefetch even further steps of the same stride. Modern spatial prefetchers may even predict variable recurring strides (e.g. VLDP, SPP)
Temporal locality refers to the property of memory accesses or access patterns to repeat themselves. In the most basic form this could mean that if address X was once accessed it may also be accessed in the future, but since caches already store recent data for a certain duration this form is less interesting (although there are mechanisms on some CPUs aimed to predict which lines are likely to be accessed again soon and which are not).
A more interesting form of temporal locality is that two (or more) temporally adjacent accesses observed once, may repeat together again. That is - if you once accessed address A and soon after that address B, and at some later point the CPU detects another access to address A - it may predict that you will likely access B again soon, and proceed to prefetch it in advance.
Prefetchers aimed to extract and predict this type of relations (temporal prefetchers) are often using relatively large storage to record many such relations. (See Markov prefetching, and more recently ISB, STMS, Domino, etc..)
By the way, these concepts are in no way exclusive, and a program can exhibit both types of localities (as well as other, more irregular forms). Sometimes both are even grouped together under the term spatio-temporal locality to represent the "common" forms of locality, or a combined form where the temporal correlation connects spatial constructs (like address delta always following another address delta).

A: *

*It is a principle which states that if some variables are referenced
by a program, it is highly likely that the same might be referenced
again (later in time - also known as temporal locality) .

*It is also highly likely that any consecutive storage in memory might
be referenced sooner (spatial locality)

A: Temporal locality of reference - A memory location that has been used recently is more likely to be accessed again. For e.g., Variables in a loop. Same set of variables (symbolic name for a memory locations) being used for some i number of iterations of a loop.
Spatial locality of reference - A memory location that is close to the currently accessed memory location is more likely to be accessed. For e.g., if you declare int a,b; float c,d; the compiler is likely to assign them consecutive memory locations. So if a is being used then it is very likely that b, c or d will be used in near future. This is one way how cachelines of 32 or 64 bytes, help. They are not of size 4 or 8 bytes (typical size of int,float, long and double variables).


text:
Q: What is the expected number of steps in the following process? We have $n$ boxes. And initially there are $x_1, x_2, x_3, \ldots, x_n$ marbles in each box. We randomly (with equal probabilities) select one of the boxes. We take one marble from it and we put it into another (different from the origin) box chosen randomly (with equal probabilities). We continue this process until one of the boxes become empty. How many operations we do on average?
It is not a homework. I don't know whether a closed form solution exists. My current results are:
\begin{align}{}
x_1 x_2 & \text{ for } n=2\\\
\frac{3x_1 x_2 x_3}{x_1 + x_2 + x_3} & \text{ for } n=3
\end{align}
I have crossposted in artofproblemsolving. This problem is related and maybe (or not) useful.
Update2:
As i learned: this problem has been studied before. As usual :)
It seems very hard even for $n=4$. No explicit solution is known, only asymptotics for the case $f(x,x,x,x)$. Nevertheless the solution is much much more easier if we change slightly the problem. For example.
Big thanks to Viktor for pointing the reference!

A: Here are some results for very small numbers, when there are $n$ variables:
$$
\begin{align*}
f(1,1,1,\ldots,1) &= 1, \\
f(2,1,1,\ldots,1) &= \frac{n}{n-1}, \\
f(3,1,1,\ldots,1) &= \frac{n^3-2n^2+3n}{n^3-3n^2+4n-2} = \frac{n}{n-1} \cdot \frac{n^2-2n+3}{n^2-2n+2}, \\
f(2,2,1,\ldots,1) &= \frac{n^3-n^2+2n}{n^3-3n^2+4n-2} = \frac{n}{n-1} \cdot \frac{n^2-n+2}{n^2-2n+2}.
\end{align*}
$$


text:
Q: A card is lost from the deck of 52 cards. Two cards are drawn and found to be of spades. What is the probability that the lost card was of spades?
My work :
Prob of spades = 13/52
Prob of lost card being spade = 1/13
How do I proceed after this? Is it like P(A/B) = P(A) / P(A $\cap$ B)? I am not able to follow after this.

A: Hint:
Let $A$ be the event that lost card was spade
Let $B$ be the event that two cards are drawn and found to be spade
You want to compute $P(A|B)$, use Bayes Theorem,
$$P(A|B)=P(B|A)\frac{P(A)}{P(B)}$$
Note that you can compute $P(B)$ by
$$P(B)=P(B|A)P(A)+P(B|A^c)P(A^c).$$

A: You have got a good answer in a "standard" way, but probability problems can often be very easily solved using a bit of imagination.
You know that the two cards drawn are spades,
so (including the lost card), there are $11$ spades in $50$ cards
Thus, very simply, P(lost card is a spade) $= \dfrac{11}{50}$


text:
Q: How to handle id element when mapping mongoDB document to C# class I want to deserialize document which looks like this:
{
    "_id" : ObjectId("58e67bd8df79507aa3f8a6b6"),
    "value" : 10,
    "stack" : [
        {
            "id" : "49ccbadf-5964-11e6-b1e9-549f3520935c",
            "value" : 0
        },
        {
            "id" : "49ccb5cc-5964-11e6-b1e9-549f3520935c",
            "value" : 0
        }
    ]
}

to a C# class. The class name is Entry and its definition looks like this:
public class Entry
{
    public BsonObjectId _id { get; set; }
    public int value { get; set; }
    public List<Stack> stack { get; set; }
}

and the Stack class looks like this
public class Stack
{
    public string id { get; set; }
    public int value { get; set; }
}

When querying I get the following exception
'An error occurred while deserializing the stack property of class ConsoleApp4.Entry: Element 'id' does not match any field or property of class ConsoleApp4.Stack.'

I can decorate the stack class with [BsonIgnoreExtraElements] attribute and then the exception is gone but I don't want to do this since I have to use the id property in querying. Anyone has any idea what I should do? I would appreciate any help.

A: Got it by doing through some trial and error - enough to decorate the stack class with [BsonNoId] attribute.

A: I do not think you need that either. Just change the type like this:
public ObjectId Id { get; set; }

A: To use the ObjectId class you need to pull in the nuget package MongoDB.Bson this will allow you to map the _id property


text:
Q: Self-Hosted MongoDb Single Quotes Issue As Parse is getting closed we have migrated our apps data to self-hosted mongodb.
But we have encountered an issue with Single quotes .
For example:
It's a new Day.
When the database was hosted by parse itself we never had this issue and never needed extra code to escape the single quotes but now after migrating the parse and using self hosted mongodb we are facing this problem.
MongoDb data
{ "_id" : "vryoEYQqDt", "rowid" : 9, "image" : "982621c6338150d34c345ee62baa3420_outlet-335936476.jpg", "_created_at" : ISODate("2015-03-03T09:08:43.217Z"), "_updated_at" : ISODate("2016-11-09T08:20:21.074Z"), "name" : "Hello World" }

Parse code to insert in mongodb
$query = new ParseQuery("prodcuts");
        $query->equalTo("rowid", $rowid);

$object = $query->first();
$object->set("name", $pro_data->name);
try {
    $object->save();

    } catch (ParseException $ex) {
      // Execute any logic that should take place if the save fails.
      // error is a ParseException object with an error code and message.
      echo 'Failed to create new object, with error message: ' +    $ex->getMessage();
}

"$pro_data->name" - gets the name from MySql database. currently "It's a new day".
When we execute this code . Mongo db updates the "_updated_at" : ISODate("2016-11-09T08:20:21.074Z") field but "name" : "Hello World" is not updated because it has a single quote which is not escaped.
Even Parse doesn't catch any exceptions.
Is there a way or config that escapes single quotes in MongoDb without using extra code in php?
Thanx in advance.
Update:
It might actually not be the single quotes which was not updating the mongo db but the UTF-8 characters.
Value of "$object" before save:
Parse\ParseObject Object
(
    [serverData:protected] => Array
        (
            [rowid] => 9
            [image] => Parse\ParseFile Object
                (
                    [name:Parse\ParseFile:private] => 982621c6338150d34c345ee62baa3420_outlet-335936476.jpg
                    [url:Parse\ParseFile:private] =>
                    [data:Parse\ParseFile:private] =>
                    [mimeType:Parse\ParseFile:private] =>
                )

            [name] => Matzig 33'cl
        )

    [operationSet:protected] => Array
        (
            [name] => Parse\Internal\SetOperation Object
                (
                    [value:Parse\Internal\SetOperation:private] => M?tzig 33'cl
                    [isAssociativeArray:Parse\Internal\SetOperation:private] =>
                )

        )

    [estimatedData:Parse\ParseObject:private] => Array
        (
            [rowid] => 9
            [image] => Parse\ParseFile Object
                (
                    [name:Parse\ParseFile:private] => 982621c6338150d34c345ee62baa3420_outlet-335936476.jpg
                    [url:Parse\ParseFile:private] =>
                    [data:Parse\ParseFile:private] =>
                    [mimeType:Parse\ParseFile:private] =>
                )

            [name] => M?tzig 33'cl
        )

    [dataAvailability:Parse\ParseObject:private] => Array
        (
            [rowid] => 1
            [image] => 1
            [name] => 1
        )

    [className:Parse\ParseObject:private] => products
    [objectId:Parse\ParseObject:private] => vryoEYQqDe
    [createdAt:Parse\ParseObject:private] => DateTime Object
        (
            [date] => 2015-03-03 09:08:43.217000
            [timezone_type] => 2
            [timezone] => Z
        )

    [updatedAt:Parse\ParseObject:private] => DateTime Object
        (
            [date] => 2016-11-10 10:20:35.823000
            [timezone_type] => 2
            [timezone] => Z
        )

    [hasBeenFetched:Parse\ParseObject:private] => 1
)

$object value after save!!
Parse\ParseObject Object
(
    [serverData:protected] => Array
        (
            [rowid] => 9
            [image] => Parse\ParseFile Object
                (
                    [name:Parse\ParseFile:private] => 982621c6338150d34c345ee62baa3420_outlet-335936476.jpg
                    [url:Parse\ParseFile:private] =>
                    [data:Parse\ParseFile:private] =>
                    [mimeType:Parse\ParseFile:private] =>
                )

            [name] => M?tzig 33'cl
        )

    [operationSet:protected] => Array
        (
        )

    [estimatedData:Parse\ParseObject:private] => Array
        (
            [rowid] => 9
            [image] => Parse\ParseFile Object
                (
                    [name:Parse\ParseFile:private] => 982621c6338150d34c345ee62baa3420_outlet-335936476.jpg
                    [url:Parse\ParseFile:private] =>
                    [data:Parse\ParseFile:private] =>
                    [mimeType:Parse\ParseFile:private] =>
                )

            [name] => M?tzig 33'cl
        )

    [dataAvailability:Parse\ParseObject:private] => Array
        (
            [rowid] => 1
            [image] => 1
            [name] => 1
        )

    [className:Parse\ParseObject:private] => products
    [objectId:Parse\ParseObject:private] => vryoEYQqDe
    [createdAt:Parse\ParseObject:private] => DateTime Object
        (
            [date] => 2015-03-03 09:08:43.217000
            [timezone_type] => 2
            [timezone] => Z
        )

    [updatedAt:Parse\ParseObject:private] => DateTime Object
        (
            [date] => 2016-11-10 10:22:16.878000
            [timezone_type] => 2
            [timezone] => Z
        )

    [hasBeenFetched:Parse\ParseObject:private] => 1
)

Here M?tzig 33'cl -> ? == 'ä'


text:
Q: delete item in list SPWeb web = SPContext.Current.Web;
    SPList list = web.Lists["MyList"];
    if (list != null)
    {
        for (int i = list.ItemCount - 1; i >= 0; i--)
        {
            list.Items[i].Delete();
        }
        list.Update();
    }

I have more Items in an SharePoint list then when i in an listbox select only one item and delete if with the following code , then it deletes al the items in my list , not just the only I have selected , can somebody help me ?

A: This is an alternative to Jussi Palo's answer, but without iterating through ALL the list items, which is a huge performance loss.
string filtervalue = TextBox1.Text; // Value you selected, criteria for deletion.
SPWeb currentWeb = SPContext.Current.Web;
SPList list = currentWeb.Lists.TryGetList("MyList");
if(list==null)
    throw new InvalidOperationException("MyList does not exist on current site.");
SPQuery query = new SPQuery()
{
    Query = string.Format("<Where><Eq><FieldRef Name='MyField' /><Value Type='Text'>{0}</Value></Eq></Where>", filtervalue),
    ViewFields = "<FieldRef Name='ID' />",
    ViewFieldsOnly = true
};
SPListItemCollection filteredItems = list.GetItems(query);

foreach (SPListItem item in filteredItems)
{
    item.Delete();
    break; // If you want to delete ONLY the first occurence.
}
list.Update();

Also, if by any chance you know the ID of the item you selected, you can pass that as a parameter to the following method:
list.Items.DeleteItemById(SelectedId);

A: In your code you are deleting all items. You need to have some check within the for loop to only delete the item you want.
Example:
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists.TryGetList("listname").Items;
int itemCount = listItems.Count;

for (int k=0; k<itemCount; k++)
{
    SPListItem item = listItems[k];

    if (TextBox2.Text==item["Employee"].ToString())
    {
        listItems.Delete(k);
        break; // Only break away if you want to delete one item ONLY!
    }
}

Source


text:
Q: Identificar si una etiqueta es valida o no usando un cierto criterio y las librerias  y  Estoy intentando resolver un problema en lenguage c, pero no puedo llegar a entender como completarlo. Resolvi parte de ello pero me falta la parte más dificil y quisiera comprender como podria.
Si necesitan que aclare algo me dejan saber, porfavor.

La ciudad de Yakarta ha sido rodeada por los atacantes. Un trailer entra en la ciudad. El conductor afirma que la carga es comida y medicinas de los indonesios. Ali Asmath es uno de los soldados en Bekasi. Duda sobre el trailer, tal vez sea del equipo rival.

Ali sabe que una etiqueta es válida si la suma de cada dos dígitos consecutivos de la misma es par y su letra no es una vocal.

Determina si la etiqueta del camión es válida o no.

Para este problema consideramos que las letras "A", "E", "I", "O", "U", "Y" son vocales.

Crear un programa que le ayude a soldados como Ali, a controlar el acceso correctamente.

Con esto podemos saber cual es el criterio y que se tiene que poder hacer.
Criterio:

*

*La etiqueta debe contener una letra

*La letra no puede ser una de las vocales consideradas: "A", "E", "I", "O", "U", "Y"

*La letra puede estar en cualquier posicion de la etiqueta

*La suma de cada dos numeros consecutivos deben ser par: 1 + 1 = 2, 3 + 3 = 6

*No especifica la longitud de la etiqueta pero no influeye tanto en el criterio de todas formas

Que hara el programa:

*

*El usuario puede ingregsar la etiqueta en forma de cadena ya que va a contener una letra. Ejemplos: C789638 o 71C9108 o 20C91

*Identificar si la etiqueta contiene alguna letra que sea de las vocales, si contiene una no es valida la etiqueta. Tomando en cuenta que la letra puede estar en cualquier posicion de la etiqueta.

*Verificar que la suma de cada dos numeros consecutivos sea par, si no es asi, la etiqueta es invalida.

Por ejemplo: C789628 - No es Valida, ya que entre los numeros, no todas las sumas de cada dos numeros pares.

*

*7 + 8 = 15 (impar)

*9 + 6 = 15 (impar)

*2 + 8 = 10 (par)

Un ejemplo que si seria valido seria: 20C91

*

*2 + 0 = 2 (par)

*9 + 1 = 10 (par)

Con esto tambien podemos saber que la longitud de la cadena debe ser impar para que pueda haber una suma apropiada entre dos numeros consecutivos. Ya que no se cuenta la letra y de tal forma sera una longitud par al no contar la letra.
Por ejemplo si tenemos una etiqueta como, 9C91, solo podra haber una suma entre los dos numeros al final, "9 y 1 pero el "9" al inicio no tendra una suma.

*

*C789628 (Longitud = 7 y se quita la C, (7 - 1) = longitud = 6)

*20C91 (Longitud = 5 y se quita la C, (5 - 1) = longitud = 4)

Con esto creamos otro paso que se debe tomar en cuenta antes de verificar la suma de dos numeros consecutivos

*

*Verificar si la longitud de la cadena es impar o par, si es par se le deja saber al usuario que las placas solo pueden ser de una longitud impar (7, 9, 11, etc.)

Ahora con todo esto tomado en cuenta quiero dejarles saber que no solo consideren este criterio, tambien si identifican otras cosas al leer el problema me dejan saber.
Otra cosa que quiero dejar clara es que solo puedo usar las siguientes funciones:
Funciones en la libreria <string.h> y <stdio.h>
Puedo usar: if, else if, else, scanf(), gets(), getchar(), puts(), char, int, float, double
y en la libreria <string.h>:

*

*strlen()

*strcat

*strncat()

*strcpy()

*strncpy()

*strcmp()

*strncmp()

*strchr()

*strrchr()

*strstr()

*strcspn()

*strspn()

*strpbrk()

*strtok()

Si por alguna razón debo usar algo más que esté en alguna de esas liberias, me dejan saber porfavor y si me podrian presentar un codigo que resuelva este problema sería de gran ayuda, ya que debo averiguar como hacerlo hoy mismo. He intentado varias cosas y no sé que más pensar. Solo he podido completar la parte de identificar si hay alguna de las vocales consideradas.
Actualización:
Pude resolver el problema de una diferente forma pero aun me gustaria saber como lo resolverian ustedes solo usando mayormente cadenas.
Aqui esta la forma en que lo resolvi:
/*
Título: Revisión de Etiqueta
Nombre: Naresh Pillay
Fecha: 15/05/2022
*/

//Inclusión de Liberias
#include <stdio.h>
#include <string.h>

int main ()
{
  //Variables Locales
  const char vocales[] = "AEIOUY";
  char letra[2];
  int n1,n2,n3,n4,n5,n6;
  char* res_letras;
  int suma1;
  int suma2;
  int suma3;

  //Instrucciones a Soldado para ingresar la etiqueta del vehiculo
  printf("\nEscriba la etiqueta del vehiculo. Escribala usando un espacio entre cada caracter.\n\n");

  printf("Asegurese que al terminar de escribir la etiqueta presione ENTER en el teclado.\n\n");

  printf("Deben haber 7 caracteres en su etiqueta. Debe iniciar con la letra que le corresponda y que sea mayuscula.\n\n");

  printf("Siga el ejemplo: [ D 1 2 3 4 5 6 ]\n\n");

  //Ingreso de etiqueta
  printf("ETIQUETA DEL VEHICULO: ");
  scanf("%s%d%d%d%d%d%d", letra,&n1,&n2,&n3,&n4,&n5,&n6);

  //Impresión de etiqueta ingresada
  printf("\n\nLa etiqueta es: [ %s %d %d %d %d %d %d ]\n\n", letra, n1, n2, n3, n4, n5, n6);

    //Comparación de letra en etiqueta con vocales las cuales no estan permitidas
    res_letras = strpbrk(vocales, letra);

    //Calculos de sumas entre dos numeros consecutivos
    suma1 = n1 + n2;
    suma2 = n3 + n4;
    suma3 = n5 + n6;

  //Revision de criterio para validar la etiqueta (Condiciones) e impresiones de resultados
  if(res_letras) {
    printf("********************************************************\n");
    printf("*LA ETIQUETA NO ES VÁLIDA!! NO DEJE AL VEHICULO PASAR!!*\n");
    printf("********************************************************\n\n\n");

    printf("********************************************************\n");
    printf("************** ESTÁ PRESENTE LA VOCAL: %c ***************\n", *res_letras);
    printf("********************************************************\n\n\n");

  } else if (suma1 %2 != 0) {
    printf("********************************************************\n");
    printf("*LA ETIQUETA NO ES VÁLIDA!! NO DEJE AL VEHICULO PASAR!!*\n");
    printf("********************************************************\n\n\n");

    printf("**********************************************************\n");
    printf("*LA PRIMERA SUMA ENTRE DOS NUMEROS CONSECUTIVOS NO ES PAR*\n");
    printf("**********************************************************\n\n\n");
    printf("La letra en la etiqueta es: [%s] (NO VOCAL)\n\n", letra);
    printf("Primera Suma = [%d] (IMPAR)\n\n", suma1);

      } else if (suma2 %2 != 0) {
        printf("********************************************************\n");
        printf("*LA ETIQUETA NO ES VÁLIDA!! NO DEJE AL VEHICULO PASAR!!*\n");
        printf("********************************************************\n\n\n");

        printf("**********************************************************\n");
        printf("*LA SEGUNDA SUMA ENTRE DOS NUMEROS CONSECUTIVOS NO ES PAR*\n");
        printf("**********************************************************\n\n\n");
          printf("La letra en la etiqueta es: [%s] (NO VOCAL)\n\n", letra);
          printf("Primera Suma = [%d] (PAR)\n\n", suma1);
          printf("Segunda Suma = [%d] (IMPAR)\n\n", suma2);

        } else if (suma3 %2 != 0) {
            printf("********************************************************\n");
            printf("*LA ETIQUETA NO ES VÁLIDA!! NO DEJE AL VEHICULO PASAR!!*\n");
            printf("********************************************************\n\n\n");

            printf("**********************************************************\n");
            printf("*LA TERCERA SUMA ENTRE DOS NUMEROS CONSECUTIVOS NO ES PAR*\n");
            printf("**********************************************************\n\n\n");
            printf("La letra en la etiqueta es: [%s] (NO VOCAL)\n\n", letra);
            printf("Primera Suma = [%d] (PAR)\n\n", suma1);
            printf("Segunda Suma = [%d] (PAR)\n\n", suma2);
            printf("Tercera Suma = [%d] (IMPAR)\n\n", suma3);

            } else {
                printf("**************************************************\n");
                printf("*LA ETIQUETA ES VÁLIDA!! DEJE AL VEHICULO PASAR!!*\n");
                printf("**************************************************\n\n\n");

                printf("******************************************\n");
                printf("*La etiqueta válida es: [ %s %d %d %d %d %d %d ]*\n", letra, n1, n2, n3, n4, n5, n6);
                printf("******************************************\n\n\n");

                printf("La letra en la etiqueta es: [%s] (NO VOCAL)\n\n", letra);
                printf("Primera Suma = [%d] (PAR)\n\n", suma1);
                printf("Segunda Suma = [%d] (PAR)\n\n", suma2);
                printf("Tercera Suma = [%d] (PAR)\n\n", suma3);
        }
  return 0;
}


text:
Q: import filters - TypeError: type() doesn't support MRO entry resolution Python 3.7.1, filters 1.3.2
>>> import filters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "E:\anaconda3\lib\site-packages\filters\__init__.py", line 27, in <modu
    from filters.extensions import FilterExtensionRegistry
  File "E:\anaconda3\lib\site-packages\filters\extensions.py", line 11, in <mo
    from class_registry import EntryPointClassRegistry
  File "E:\anaconda3\lib\site-packages\class_registry\__init__.py", line 5, in
    from .registry import *
  File "E:\anaconda3\lib\site-packages\class_registry\registry.py", line 33, i
    class BaseRegistry(with_metaclass(ABCMeta, Mapping)):
  File "E:\anaconda3\lib\site-packages\six.py", line 827, in __new__
    return meta(name, bases, d)
  File "E:\anaconda3\lib\abc.py", line 126, in __new__
    cls = super().__new__(mcls, name, bases, namespace, **kwargs)
TypeError: type() doesn't support MRO entry resolution; use types.new_class()

Looks like it is related to this and got fixed. However, I have the latest Python 3.7 and filters package. Any ideas?

A: Maintainer of filters and class-registry here.  I apologise that it took me so long to find this!
The issue is caused by a couple of lines in the class-registry package:
class BaseRegistry(with_metaclass(ABCMeta, Mapping)):
    ...

class MutableRegistry(with_metaclass(ABCMeta, BaseRegistry)):
    ...

The error occurs because with_metaclass() creates a dynamic type internally, which conflicts when using it with a generic type like Mapping and MutableMapping.
This issue was discussed on https://bugs.python.org/issue33188 and it appears that the outcome was, "works as intended":

This is not a bug but an explicit design decision. Generic classes are static typing concept and therefore are not supposed to work freely with dynamic class creation. During discussion of PEP 560 it was decided that there should be at least one way to dynamically create generic classes, types.new_class was chosen for this, see https://www.python.org/dev/peps/pep-0560/#dynamic-class-creation-and-types-resolve-bases
Also the exception message is quite clear about this. Unfortunately, PEPs 560 and 557 were discussed in parallel so not every possible interactions where thought out. But is it critical for dataclasses to call type? I believe there should be no other differences with types.new_class. I would say the latter is even better than type because it correctly treats __prepare__ on the metaclass IIRC. So I would propose to switch from type() to types.new_class() for dynamic creation of dataclasses.

There are two possible ways to resolve this issue:

*

*Use add_metaclass() instead of with_metaclass().

*Drop support for Python 2 and replace with_metaclass() with Python-3-style base/metaclass declarations.

Both solutions are represented in pull requests submitted by stj.
I no longer work at EFL Global [now LenddoEFL], so I don't have direct access to that repo any more.  It may be some time before a new version is released; in the meantime, I have forked the project and released a new version that explicitly supports Python 3.7 (and drops support for Python 2):
https://pypi.org/project/phx-filters/


text:
Q: Java: Select class member by string Is there a way in Java to get a member of a class using the name of said member.
Say we have a class as such:
public class intClass {
    public int x;
    public intClass(x) {
        this.x = x;
    }
}

Is there anyway to do something similar to:
intClass newIntClass = new intClass(4);
String memberName = "x";
int y = newIntClass.[memberName];


text:
Q: How do I change the color of the ActionBar hamburger icon? I'm using NavigationView from android design support library and toolbar and everything works fine, but I want to know how to make the hamburger icon dark (right now it appears white). Also I wanna adjust distance from screen edge to ActionBar Title. So how do I do this? Thanks for help.
I set theme as Theme.AppCompat.Light.NoActionBar. So I use toolbar. Here is my code:
public class MainActivity extends AppCompatActivity {

//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Песни","Исполнители"};
int Numboftabs =2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initializing Toolbar and setting it as the actionbar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

And xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false"
tools:context=".MainActivity">

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    >
    <include
        android:id="@+id/toolbar"
        layout="@layout/tool_bar"
        />

    <ru.amdm.amdm.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp"
        android:background="@color/ColorPrimary"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foreground="?android:windowContentOverlay">

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"

            android:layout_height="match_parent"
            android:layout_width="match_parent"/>
    </FrameLayout>

</LinearLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
    android:layout_gravity="start"
    app:headerLayout="@layout/header"
    app:menu="@menu/drawer"
    />

A: To change the hamburger icon, just create a new icon (e.g. ic_my_dark_menu) then assign that to your action bar:
actionBar.setHomeAsUpIndicator(R.drawable.ic_my_dark_menu);

Or, you can tint your existing icon, if you'd rather do it this way:
Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_menu, null);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, Color.BLACK);
actionBar.setHomeAsUpIndicator(drawable);

To change amount of space between your action bar title and the edge, just edit your toolbar layout (res/layout/tool_bar.xml). For example, you can add padding like this:
res/layout/tool_bar.xlml
<android.support.v7.widget.Toolbar
    ...
    android:paddingTop="16dp" />

A: May be you have to try this ..Apply this theme to toolbar ...
<style name="MyThemeOverlay">
   <item name="android:colorControlNormal">@color/myControlColor</item>
</style>


text:
Q: How to Disable verification code emails when the user is not registered in Azure AD B2C Azure B2C Password-less sign-in with email verification sends the verification code to every email address (Even if no user is not registered in directory) .after entering OTP(Non-Registered user) B2C validated the code and says "E-mail address verified. You can now continue".
Now when the users click "Continue" they get the error "An account could not be found for the provided user ID." .This is where we got sure about non-registered user.
I found this solution but not getting results after updating my current policy.
I am including my updated extension file here .
Or if it has another approach on How to Disable verification code emails when the user is not registered in Azure AD B2C.

A: Change
<ClaimsExchange Id="SignIn-WithEmail" TechnicalProfileReferenceId="LocalAccountDiscoveryUsingEmailAddress-SignIn" />

To
<ClaimsExchange Id="SignIn-WithEmail" TechnicalProfileReferenceId="LocalAccountDiscoveryUsingEmailAddress-AcctExists" />

Now your user journey will call your technical profile which uses the emailVerificationControl display control which contains the logic to only send the email OTP if the account exists.

A: I have tried this policy (Link attached), and it works perfectly fine.
https://github.com/azure-ad-b2c/samples/tree/master/policies/pwd-reset-email-exists
The right approach is not to spam users by sending verifications emails to those who are not registered, and also not telling users that email is incorrect or the account doesn't exist because, that way attackers will find out if that is an incorrect email, and to prevent Brute-force attack on your login page.
So, therefore, you use can that policy to disable verification code emails, and also turn off the Raise Error flag (RaiseErrorIfClaimsPrincipalDoesNotExist=false):


text:
Q: Match values in list of dataframes and extract in other dataframe in R I'm new programming in R and I'm creating a script for a lab.
I have a list of dataframes called: "cell_type_1", "cell_type_2", ... And the inside of dataframes are like these:
cell_type_1:

ID
Name
X
Y

01
DAP+
15
98

01
DAP+
43
68

01
DAP+
34
05

cell_type_2:

ID
Name
X
Y

02
Cer+
25
94

02
Cer+
43
68

02
Cer+
77
22

And so on. But each dataframe has a variable number of rows.
I want to compare columns X and Y of all the dataframes inside the list and those that match will export their information to another new dataframe in this way:
cell_type_n:

ID
Name
X
Y

n
DAP+Cer+
43
68

n
DAP+Cer+
36
75

cell_type_m:

ID
Name
X
Y

m
DAP+Cer+Other+
22
11

m
DAP+Cer+Other+
58
89

More info about the question:
I have those dataframes with the information of segmented biological cells, then dataframes has the spatial position (X,Y) of each cell and the name of its species (Name), therefore, each dataframe will have a variable amount of cells and there will also be a variable amount of dataframes depending on how many species there are. So if the position (X,Y) of a cell with name "A+" coincides with the position (X,Y) of another one "B+" it means that this cell is "A+B+" and I want to know its position (X,Y) and the joint name ("A+B+", in this case).
To do this, the positions (X,Y) between all the dataframes must be compared and those that match are extracted to a new dataframe which, in addition to having the positions, has the names (Names column) of the species that have matched.
The number of new dataframes would be equal to all possible combinations of the dataframes (cell species) from the beginning, for example:
If we have 3 dataframes named "A+", "B+", "C+", the new dataframes would be:
"A+B+"
"A+C+"
"B+C+"
"A+B+C+"

With the respective spatial information (X,Y) and the Name column within each dataframe.
Thanks.

A: Using base R. Since you're working on a list of data frames and want to compare combinations (comb) of them an outer apply is needed. Using a toy example of 4 data frames named "A" - "D" in df_list.
List of data frames
df_list
$A
  ID Name  X  Y
1  1 DAP+ 15 98
2  1 DAP+ 43 68
3  1 DAP+ 34  5

$B
  ID Name  X  Y
1  2 Cer+ 25 94
2  2 Cer+ 43 68
3  2 Cer+ 77 22

$C
  ID Name  X  Y
1  2 Cer+ 25 94
2  2 Cer+ 43 68
3  2 Cer+ 77 22

$D
  ID Name  X  Y
1  1 DAP+ 15 98
2  1 DAP+ 43 68
3  1 DAP+ 34  5

comb <- data.frame(combn(1:length(df_list), 2))
names(comb) <- apply(combn(names(df_list), 2), 2, paste, collapse="")

apply(comb, 2, function(x){
  res <- merge(df_list[[x[1]]], df_list[[x[2]]], c("X", "Y"))
  cbind(ID = res[,c("ID.x")],
        Name = paste0(res$Name.x, res$Name.y),
        res[, c("X", "Y")])})
$AB
  ID     Name  X  Y
1  1 DAP+Cer+ 43 68

$AC
  ID     Name  X  Y
1  1 DAP+Cer+ 43 68

$AD
  ID     Name  X  Y
1  1 DAP+DAP+ 15 98
2  1 DAP+DAP+ 34  5
3  1 DAP+DAP+ 43 68

$BC
  ID     Name  X  Y
1  2 Cer+Cer+ 25 94
2  2 Cer+Cer+ 43 68
3  2 Cer+Cer+ 77 22

$BD
  ID     Name  X  Y
1  2 Cer+DAP+ 43 68

$CD
  ID     Name  X  Y
1  2 Cer+DAP+ 43 68

Data
df_list <- list(A = structure(list(ID = c(1L, 1L, 1L), Name = c("DAP+",
"DAP+", "DAP+"), X = c(15L, 43L, 34L), Y = c(98L, 68L, 5L)),
class = "data.frame", row.names = c(NA,
-3L)), B = structure(list(ID = c(2L, 2L, 2L), Name = c("Cer+",
"Cer+", "Cer+"), X = c(25L, 43L, 77L), Y = c(94L, 68L, 22L)),
class = "data.frame", row.names = c(NA,
-3L)), C = structure(list(ID = c(2L, 2L, 2L), Name = c("Cer+",
"Cer+", "Cer+"), X = c(25L, 43L, 77L), Y = c(94L, 68L, 22L)),
class = "data.frame", row.names = c(NA,
-3L)), D = structure(list(ID = c(1L, 1L, 1L), Name = c("DAP+",
"DAP+", "DAP+"), X = c(15L, 43L, 34L), Y = c(98L, 68L, 5L)),
class = "data.frame", row.names = c(NA,
-3L)))


text:
Q: Does inequality for subset imply inequality for set? Suppose I have two finite sets of numbers ($\mathbb{R}_{\geq 0}$) $A$ and $B$, each split into some $n$ disjoint subsets $A = A_1 \cup A_2 \cup ... \cup A_n$ and $B = B_1 \cup B_2 \cup ... \cup B_n$, and let $\mathcal{A} = \{A_1, A_2, ...,A_n \}$ and $\mathcal{B} = \{B_1, B_2, ...,B_n \}$.
If there exists a one-to-one matching of each $B_i \in \mathcal{B}$ to a $A_j \in \mathcal{A}$ such that
$$\frac{\sum_{k\in B_i}k}{|B_i|} \geq \frac{\sum_{k\in A_j}k}{|A_j|}$$
(e.g. if $A_1$ is used for $B_1$ in the relation above, then $B_2$ cannot use $A_1$ anymore)
Does it imply $$\frac{\sum_{k \in B} k}{|B|} \geq \frac{\sum_{k \in A} k}{|A|}?$$
Intuitively, if each of the subset average in $B$ is $\geq$ a unique subset average in $A$ (one-to-one matching), does that imply $B$'s average is $\geq$ $A$'s average?

A: Let $A=A_1\cup A_2$ and $B=B_1\cup B_2$, where $A_1=\{1.0,1.1,1.2\}$, $A_2=\{2.1\}$, $B_1=\{1\}$, and $B_2=\{2\}$; then
$$\frac{\sum A_1}{|A_1|}=1.1>1=\frac{\sum B_1}{|B_1|}$$
and
$$\frac{\sum A_2}{|A_2|}=2.1>2=\frac{\sum B_2}{|B_2|}\;,$$
but
$$\frac{\sum A}{|A|}=1.35<1.5=\frac{\sum B}{|B|}\;.$$


text:
Q: Php Deployment Stage Issue, i have site that is hosted on my Cpanel  with registered domain(ex:domain1.com project hosted here)
and have clients also and each client having different domains
but they are not do any hosting to respective domains and it have only one htacees file that simply forward to my hosted site without changing the domain name
means
my hosted site is : hk-test1.com/Showcase/ (i.e site hosted here)
client site is:    engineering.hk-test1.com.  (contains nothing having htacces file only that is forwarded to my hk-test1.com/Showcase/ without changing the domain or URL)
if any one enters in address bar engineering.hk-test1.com it shows content of hk-test1.com/Showcase/ means  "engineering.hk-test1.com" forwarded to "hk-test1.com/Showcase/"
In address bar still engineering.hk-test1.com
but my requirement is
i have inner links in my hosted site(i.e hk-test1.com/Showcase/)means anchor tag
when i click on that it goes to hk-test1.com/Showcase/home/theme_desc/11 this url my client url(i.e engineering.hk-test1.com/home/theme_desc/11) gone because the
base url of my project.It is hosted at (hk-test1.com/Showcase/)
is there any posibilty like url comes with like  engineering.hk-test1.com/Showcase/home/theme_desc/11
please help me

A: If I am understanding you correctly, you can accomplish this in cPanel by setting the base location for each sub-domain to your website root. I cannot see a useful purpose to do this, but I am sure you have your reasons. You will no longer need the .htaccess files as the sub-domain will not point to those directories any more.
When you create or edit a sub-domain (for example engineering or blobby), simply point the folder location for that sub-domain to your website root folder. That way all of the below URL'S will work.
hk-test1.com/Showcase/home/theme_desc/11
engineering.hk-test1.com/Showcase/home/theme_desc/11
blobby.hk-test1.com/Showcase/home/theme_desc/11
etc....


text:
Q: 24V DC to +5V and -5V I need to convert 24V DC to +5V and -5V to power two op-amps (opa2134) and one ATtiny85 with minimal heat generated from the circuit.
What voltage regulator would you recommend ?
//Digis

A: The most simple solution is to buy a small DC/DC converter with bipolar outputs in an oversized 24-pin DIP package.  Note - these usually require additional capacitors on the input and outputs.
If you want to grow it from scratch, I would go with a linear regulator for the +5 V (because the total load current is so low) and a non-isolated buck-boost converter to turn the +24 V into -5 V.  There are dozens of parts to choose from for this, including ones with the power transistors on-board.  Linear Technology (now a part of Analog Devices) is a good company for this.

A: For less than 10mA total current per supply, consider an LM7805 + ICL7660. At the higher end the 7805 will get warm but it won't require a heat sink in most situations. It will draw approximately 20mA +5mA Iq from the supply at 10mA + 10mA output current, so the power dissipation will be (24-5)V * 20mA + 24V * 5mA = 500mW.
For higher asymmetric currents, like 50mA on the +5 and 10-20mA on the -5, you can consider a switching buck regulator and the same 7660 to turn the +5 into -5. Suitable switching regulators are the well established LM2596 or MC34063.
If you really need the ultra-low distortion amplifier you mentioned, you may wish to think about how to mitigate noise from a switching regulator if this could be a concern.

A:
What voltage regulator would you recommend for 24V to +/-5 regulated ….with minimal heat generated from the circuit.

I'd suggest that the cheapest but not quite the lowest power would be to use two of the LM2596 based switching regulators readily available online:

These cost about $0.60 each and are a great replacement for older linear regulators. You'd need one for the +5 and one for the -5.
You can use one of these to generate a -5V supply simply by using a series diode to the unit, and grounding the OUT+ pin. The regulated -5V is available on the OUT- pin
The only downside of these regulators is that they ALWAYS draw a peak pulse current of 3A, so your 24V supply needs a reasonably high output capacitor to supply this.

A: If you don't care about cost, but want low noise, LDO regulated charge pump 100µA Quiescent Current use LTC3260.
But if you don't give any other requirements, how can you search or design or decide? ( collorary to the best question has better specs)


text:
Q: Do you know Atom one light color scheme for vim I'm looking for One light syntax highlight for vim.
I found atom-dark syntax highlighting file, but I cannot find One light.
Do you know One light for vim or similar color scheme?

A: Here's a color scheme called one-light. Is that it?


text:
Q: Running a Giraph job showing the following error INFO zookeeper.ClientCnxn: Opening socket connection to server debashis-Pseudo-Hadoop/127.0.1.1:22181. Will not attempt to authenticate using SASL (unknown error)
14/06/17 13:07:28 WARN zookeeper.ClientCnxn: Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect
java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:735)
at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:350)
at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1068)

A: This is not necessarily a problem, sometimes it does this and tries again and succeeds.  Have you looked at the logs?  Try something like the following from the command line to see them, you may need to pipe to a file as they're quite big.  Replace the application ID with the relevant numbers, you should be able to find this either in the console output or somewhere on Hue (or whatever you're using):
yarn logs --applicationId application_1399469361545_0003


text:
Q: pandas merge does miss values; matching rows I am trying to compare a small pandas.df with a larger one and want to find matching rows. Infact, I know that all rows of the samller Df are part of the larger. They both consist of x, y and z coordinates, so initially I did something like:
overlap = pd.merge(largeDF,smallDF,'inner')

That seems to work, but gives me only ~50 of the values of the smallerDF. Then I fiddled around for some hours, tried to do is manually and came across this:
So I took some rows from the smaller DF that were missing from the merge and tried to find the values manually.
largeDF.loc[largeDF['y']==0.102808]

with the output:
           x         y         z  ID
14 -0.045073  0.102808  0.593552  14

Nice and fine! Thats what I expect.
But then:
locationsDF.loc[locationsDF['z']==0.593552]

Gives me:
Empty DataFrame
Columns: [x, y, z, ID]
Index: []

But... why? Is that some sort of rounding error that I do not see, because the rows match in the source .txt file. I import them with pd.read_table.
Thank you for your help


text:
Q: How to print hash of anonymous hashes in perl? How would I get value of stones if hash structure is as follows?
%HoA =
(
[stones    => "ruby"],
[metal     => "gold"],
);

I am trying to get using "print $HoA->{stones};", but no value is returned.

A: The problem is that the members of %HoA are arrays, not hashes. In fact, what you have is a hash with one element.  The key of that element is a reference to an array holding two elements: "stones" and "ruby".  The value of that element is a reference to an array holding two elements: "metal" and "gold".
I'm guessing you want a hash that will contain a list of stones, a list of metals etc.  The way to do that is:
%HoA =
(
    stones    => ["ruby"],
    metal     => ["gold"],
);

Now $HoA{stones} is a reference to an array containing the single element "ruby".
print @($HoA{stones});

should give you:
ruby


text:
Q: Passing Props in Context [React] I have 5 generation structure of components:
A-B-C-D-E
Firsly i create a context:
const ThemeContext = React.createContext();

in A is created provider
     <ThemeContext.Provider value={this.props.name} >
                    <Col><Menu navbarState={this.state.name} /></Col>
    </ThemeContext.Provider>

And in E i need to create context with {this.props.name}
export class Panel extends RoleAwareComponentUser{

    constructor(props) {
        super(props);
        // component will be visible for the roles below:
        this.authorize = ['user'];
      }

    render(){
    const jsx =(
    <div>
        <ThemeContext.Consumer>
            {value => <Col><Link className={{value: value}} to= "/HomePage">Panel</Link></Col>}
        </ThemeContext.Consumer>
    </div>
      );

      return this.shouldBeVisible() ? jsx : null;

    }
}

The output of Link className is "[Object, object]"
How can i pass the props correctly?

A: Stringified object like "[Object, object]" means that object value were provided in a place where a string is expected.
It should be:
<ThemeContext.Consumer>
    {value => <Col><Link className={value} to= "/HomePage">Panel</Link></Col>}
</ThemeContext.Consumer>

className accepts strings, but class attribute won't be added if a value is falsy.
As explained in this answer, it is a hierarchy of Provider and Consumer components that allows to pass the context, so <ThemeContext.Consumer> should have <ThemeContext.Provider> as a parent.
If there is proper hierarchy but context value is falsy, this means that this.props.name was falsy when it was passed as provider value prop:
<ThemeContext.Provider value={this.props.name}>...


text:
Q: using updated state in function I have a function called confirmOrder that takes in orderData and makes an API call with that data:
const confirmOrder = () => {
    // updateTime();
    updateDate();
    // delete this
    console.log(`order data: ${JSON.stringify(orderData)}`);
    axiosWithAuth()
        .post(`/diner/${props.account.id}/confirm-order`, orderData)
        .then(res => {
            console.log(res);
        })
        .catch(err => console.log(err));
}

The orderData object has properties for both date and time:
const [orderData, setOrderData] = useState({
    date:'',
    time: '',
    truck_id: props.selectedTruck.id,
    breakdown: props.order,
    subtotal: orderSubtotal,
    tip: tipVal.tip,
    total: orderSubtotal + Number(tipVal.tip)
})

As you can see, when I run confirmOrder (through an onClick), a call is made inside that function (i.e. updateDate) that should update the values of orderData.date and orderData.time. Here is the code for that:
    const updateDate = () => {
        let date = new Date();
        let month = date.getMonth() + 1;
        if (month < 10) {
            month = '0' + month;
        };
        let calenDay = date.getDate();
        if (calenDay < 10) {
            calenDay = '0' + calenDay;
          };
        setOrderData({
            ...orderData,
            date: `${date.getFullYear()}-${month}-${calenDay}`,
            time: `${date.getHours()}:${date.getMinutes()}`
        });
    }

The problem I'm having is when I make the API call inside of confirmOrder, orderData.date and orderData.time are being sent to the backend as empty strings instead of with the updated code. How can I resolve this problem?

A: In React, setting state is asynchronous. When you call the state updater, all you do is schedule an update and rerender. The rest of your function will finish running and then the state will be updated and your component rerendered.
If your UI does not depend on the date and time strings, they should not be included in the state at all. You should generate those strings and then combine them with the state to send the request.
const updateDate = () => {
    let date = new Date();
    let month = date.getMonth() + 1;
    if (month < 10) {
        month = '0' + month;
    };
    let calenDay = date.getDate();
    if (calenDay < 10) {
        calenDay = '0' + calenDay;
    }
    return ({
        date: `${date.getFullYear()}-${month}-${calenDay}`,
        time: `${date.getHours()}:${date.getMinutes()}`
    });
}

const confirmOrder = () => {
    const date = updateDate();
    axiosWithAuth()
        .post(`/diner/${props.account.id}/confirm-order`, { ...date, ...orderData })
        .then(res => {
            console.log(res);
        })
        .catch(err => console.log(err));
}


text:
Q: How to keep the original css on an input linked to an instantsearch widgets.searchBox I was looking at the documentation of InstantSearch and I don't understand some things about the searchBox.
I would like to use a searchBox. I already have my own styled inputBox for the user to write. So I would like to be able to keep my css. Then, i wrote :
jobSearchIndex.addWidget(
widgets.searchBox({
    container: '#mySuperCuteBox',
    placeholder: 'I'm a cute box!',
    cssClasses: {
        input: 'myCuteCssClass',
    }
})
);

The problem is, that a weird instantsearch css selector overide some of my css and add style I don't need/want. I don't know how to get just my css...
I also tried something like :
jobSearchIndex.addWidget(
    widgets.searchBox({
        container: '#mySuperCuteBox',
        placeholder: 'I'm a cute box!',
    })
);

but it is not better.
I have also seen that in my render, i can see something like :
<input id="mySuperCuteBox" name="cuteName" class="myCuteCssClass ais-search-box--input" autocapitalize="off" autocomplete="off" autocorrect="off" placeholder="I'm a cute box!" role="textbox" spellcheck="false" value="bo" type="text">

Is there a simple way to activate the autocomplete="on" ? I tried to have a look on : https://github.com/algolia/instantsearch.js/blob/develop/dev/app/jquery/stories/autocomplete.stories.js
But it is not really userfriendly for a novice such as me :(... I just felt flooded by so much information and I cannot figure out how to connect all this to my searchbox...
If someone can enlighten me about this, that would be great! :)
Thank you


text:
Q: Inline enumerate: Two lines are not aligned I tried to make a horizontal list using \usepackage[inline]{enumitem}. However, when it breaks into new line, the second line is not aligned the same as the first one.
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath, amsfonts, amssymb}
\usepackage[left=1.5cm,right=1.5cm,top=1.5cm,bottom=1.5cm]{geometry}

\usepackage[inline]{enumitem}
\setlist[enumerate]{
    label = \textbf{\arabic*.},
    align = left,
    labelwidth = \parindent,
    leftmargin = \parindent,
    style = standard
}

\begin{document}
\begin{enumerate*}[mode = unboxed, itemjoin = \hspace{2cm}]
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
\end{enumerate*}
\end{document}

I've known that there is tasks environment, but somehow it's not suitable for my work.

A: The environment enumerate* starts a paragraph, with its normal indentation.
You should also add some flexibility in itemjoin.
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath, amsfonts, amssymb}
\usepackage[left=1.5cm,right=1.5cm,top=1.5cm,bottom=1.5cm,showframe]{geometry}

\usepackage[inline]{enumitem}
\setlist[enumerate]{
    label = \textbf{\arabic*.},
    align = left,
    labelwidth = \parindent,
    leftmargin = \parindent,
    style = standard,
    labelsep=4pt,
}

\begin{document}

\noindent\begin{enumerate*}[mode=unboxed,itemjoin = \hspace{2cm plus 2cm}]
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
    \item text
\end{enumerate*}

\end{document}


text:
Q: How to add class to an hyperlink using jquery? I would like to add an additional class to a hyperlink within a span element. I can able to add a div to a combination of span elements using jquery $( ".q-button" ).wrapAll( "
");

But I need to set a class to the hyperlink with in the span elements using jquery and also wrap with a new class(like the example at the end of the post).
Here is the php code:
function custom_content_filter_the_content( $content ) {
    if ( function_exists('get_field') ) {
      $content .= '' . get_field("website") . '';
      $content .= '' . get_field("website2") . '';

    }
    return $content;
}
add_filter( 'the_content', 'custom_content_filter_the_content' );

The HTML of the content looks exactly like this:

        Google

        My post

The hyper link is inside the  I don't know a proper way to add class to the hyperlink similar to this:
$( ".q-button" ).wrapAll( "
");

Could anyone suggest me a solution for this?
Update:
Also, I want to achieve two things here. 1) I want to add class to the hyper link  2) I need another div wrapping around the hyperlink.
So that should looks like this:

            Google

            My post

Update:
Here is what I tried:
First-time:

Second-time(as per-jquery docs):

I had no luck with any of those two attempts. Failed to achieve the both- add class to the hyperlink and wrap a new class around the hyperlink.

A: $( ".q-button" ).wrapAll( "
");
$( ".q-button a" ).addClass('your-class-here');

A: It works fine in JSFiddle. May be you are not importing the necessary jquery file in your html template. Or there might be some error in your js functions. Check the firebug console for any errors and try to solve it. Hope this helps.
$('.q-button a').addClass('myClass');


text:
Q: Trying to loop through a list of options for an item but not print the very last option <#list orderItem.options as option>

            ${option.name} :

            ${option.value}

</#list>

The above code(inside of html) is what I am using in order to loop through a list of options inside of an item. At the current moment it loops through all options and prints them all. However I would like to make it so it does not print the final option inside of this list.
I am a bit limited because I have to do this through html alone. I am assuming I need some type of if statement to either tell it to stop when it reaches the last option or tell it specifically which option content to stop at but I can't seem to figure out how to write it.

A: option_index gives you the index of the current option and ?size gives you the length, you just need to compare them with an if statement
The option_index is 0 based so you need to minus 1 from the size to not include the last item
Note - you can also use option?index to get the index, depending on which version of freemarker you are using, but option_index will work in newer freemarker versions as well as older
For completeness I will also add the ?is_last, credit goes to ddekany's answer, usage <#if option?is_last>
Altogether if you have an updated freemarker version, the if statement can be written like so
Updated - assuming Freemarker 2.3.23 or later
<#if option?is_last>
    ....
</#if>

Original answer
<#list orderItem.options as option>

    <#if option_index < orderItem.options?size - 1>

            ${option.name} :

            ${option.value}

    </#if>

</#list>

Documentation for size
https://freemarker.apache.org/docs/ref_builtins_sequence.html#ref_builtin_size

The number of sub variables in sequence (as a numerical value). The
  highest possible index in sequence s is s?size - 1 (since the index of
  the first subvariable is 0) assuming that the sequence has at least
  one subvariable.

Documentation for index
https://freemarker.apache.org/docs/ref_builtins_loop_var.html#ref_builtin_index

Returns the 0-based index where the iteration (which is identified by
  the loop variable name) currently stands.

A: You could cut off the last item of the list (beware, this gives error for an already empty list):
<#list orderItem.options[0 ..< orderItem.options?size - 1] as x>
  ...
</#list>

Alternatively, you can use ?is_last to check if you are at the last item, then add a nested #if that uses that:
<#list orderItem.options as option>
  <#if !option?is_last>
     ...
  </#if>
</#list>


text:
Q: Prevent conversion to lowercase in bibtex I am using the style ascelike.bst for my reference list, and it gives me almost what I want. Except it converts everything to lowercase

Vigdor, Jacob (2008). "The economic aftermath of hurricane katrina."
  The Journal of Economic Perspectives, 22(4): 135-54.

I want titles within quotation marks and capitalised words

Vigdor, Jacob (2008). "The Economic Aftermath of Hurricane Katrina."
  The Journal of Economic Perspectives, 22(4): 135-54.

Instead of protecting the titles with {} in the bib-file I try to modify the bst-file, the format.title looks like this:
FUNCTION {format.title}
{ title empty$
{ "" }
{ "``" title "t" change.case$ *
}
if$
}

Suggestions?

A: If your bib file already has the correct capitalization: As indicated in this other question, you can change format.title in the bst to:
FUNCTION {format.title}
{ title empty$
{ "" }
{ title }
if$
}

If the capitalization is not correct to begin with, there is not much you can do. As explained here, change.case$ does not support capitalizing the first letter of each word, since this would be problematic (some words like "and" or "the" should not be capitalized). The capitalization styles supported by change.case$ are [source] :

"u" to change to uppercase, "t" to change to lowercase apart the first character and character in {}, and "l" to change to lowercases.


text:
Q: Identifying the ssh username and password on my windows machine I am able to ssh into my windows machine but as soon as the session starts; putty asks for a username and password. how do I find/change the username and password for my windows 10 openssh feature?

A: The username and password is your login credentials to the machine. the default OpenSSH on windows will not work if your login does not have a password. Either change the default OpenSSH config to work without passwords or have a login that has a password.


text:
Q: NixOS: Mediatek 7961 wifi not working properly (Vivobook Pro 16x) I have a Vivobook Pro 16x which has a mediatek 7961 wifi chip and I just installed Nixos on it. Everything works except the Wifi. The wifi works occasionally, but not always.
I updated the kernel to the latest version by setting boot.kernelPackages = pkgs.linuxPackages_latest;, as I read that was needed for the mediatek 7961 chip to work.
I've also tried setting networking.networkmanager.wifi.backend = "iwd", which seems to work slightly better, but only for a few seconds.
So my wifi works for a bit, few seconds, and then nothing loads.
Are there any other settings I can try out?

A: Sadly I was unable to fix it through software. Luckily it was easy to replace the wifi chip. So I did that, now using an AX200 chip, which works flawlessly with the default settings in NixOS.


text:
Q: PrestaShop vs. Shopify I have seen several Questions comparing different ECommerce CMS's:

*

*Prestashop compared to Zen-Cart and osCommerce

*Magento or Prestashop, which is better?

*Best php/ruby/python e-commerce
solution
I was hoping to get some people to weigh in with which they prefer for a relatively small E-shop.  I am now primarily looking at PrestaShop and Shopify.  I really like that Shopify does the hosting, has quality service, and is simple to understand and theme.  However PrestaShop is free and seems to be able to do just as much if not more than Shopify.
I have decided that Magento is too clunky for the project, and have read that many other solutions (osCommerce, ZenCart, OpenCart) are outdated, buggy, or just inferior.

A: "Free" in the e-commerce industry usually works out to a few thousand dollars a month of real cost. E-commerce stores are powering the livelihood of businesses, so there is no way to go with a value hosting company. Additionally security is a huge concern so updates are incredibly important. So this leaves you with a server configuration of at least 2 servers setup in HA environment and a part time operations person performing the maintenance. So once you ensure that you can keep your site up you then have to invest into things that most people don't think off:

*

*Email service that guarantees delivery

*CDN, your store needs to be fast or you won't sell.

*Fraud protection services ($$$)

Anyways, you get all of the above for 30 bucks a month from a hosted service.
Full disclosure: I'm founder of Shopify. I used to host my own e-commerce store before I started Shopify. 95% of our customers recover the monthly Shopify bill in the first few hours of the first day of each month.

A: The prices is not the main difference between Shopify and PrestaShop.  Talking about the scope- I think both will suit you.

*

*Technical Level

The choice of hosted Shopify or open-source PrestaShop may depends on the level of technical skills. Without doubt it is easier to maintain your store with hosted shopping cart which supplies you with regular updates and takes care of bug fixes.
PrestaShop administration is quite intuitive as well. It has the  interface with numerous themes, modern designs and easily guided catalogues is attractive for the customers. It goes without saying, that such details help you raise your traffic rates.

*

*Performance

Non-hosted installed platforms provide you with control over the speed. As the store is located on your server, you can maintain the necessary speed of connection. Unfortunately, this is not the case with hosted solutions. So, using Shopify you can face issues with low connection speed.


text:
Q: How to configure pod disruption budget to drain kubernetes node? I'd like to configure cluster autoscaler on AKS. When scaling down it fails due to PDB:
I1207 14:24:09.523313       1 cluster.go:95] Fast evaluation: node aks-nodepool1-32797235-0 cannot be removed: no enough pod disruption budget to move kube-system/metrics-server-5cbc77f79f-44f9w
I1207 14:24:09.523413       1 cluster.go:95] Fast evaluation: node aks-nodepool1-32797235-3 cannot be removed: non-daemonset, non-mirrored, non-pdb-assignedkube-system pod present: cluster-autoscaler-84984799fd-22j42
I1207 14:24:09.523438       1 scale_down.go:490] 2 nodes found to be unremovable in simulation, will re-check them at 2018-12-07 14:29:09.231201368 +0000 UTC m=+8976.856144807

All system pods have minAvailable: 1 PDB assigned manually. I can imagine that this is not working for PODs with only a single replica like the metrics-server:
❯ k get nodes -o wide
NAME                       STATUS   ROLES   AGE   VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION      CONTAINER-RUNTIME
aks-nodepool1-32797235-0   Ready    agent   4h    v1.11.4   10.240.0.4    <none>        Ubuntu 16.04.5 LTS   4.15.0-1030-azure   docker://3.0.1
aks-nodepool1-32797235-3   Ready    agent   4h    v1.11.4   10.240.0.6    <none>        Ubuntu 16.04.5 LTS   4.15.0-1030-azure   docker://3.0.1

❯ ks get pods -o wide
NAME                                    READY   STATUS    RESTARTS   AGE   IP            NODE                       NOMINATED NODE
cluster-autoscaler-84984799fd-22j42     1/1     Running   0          2h    10.244.1.5    aks-nodepool1-32797235-3   <none>
heapster-5d6f9b846c-g7qb8               2/2     Running   0          1h    10.244.0.16   aks-nodepool1-32797235-0   <none>
kube-dns-v20-598f8b78ff-8pshc           4/4     Running   0          3h    10.244.1.4    aks-nodepool1-32797235-3   <none>
kube-dns-v20-598f8b78ff-plfv8           4/4     Running   0          1h    10.244.0.15   aks-nodepool1-32797235-0   <none>
kube-proxy-fjvjv                        1/1     Running   0          1h    10.240.0.6    aks-nodepool1-32797235-3   <none>
kube-proxy-szr8z                        1/1     Running   0          1h    10.240.0.4    aks-nodepool1-32797235-0   <none>
kube-svc-redirect-2rhvg                 2/2     Running   0          4h    10.240.0.4    aks-nodepool1-32797235-0   <none>
kube-svc-redirect-r2m4r                 2/2     Running   0          4h    10.240.0.6    aks-nodepool1-32797235-3   <none>
kubernetes-dashboard-68f468887f-c8p78   1/1     Running   0          4h    10.244.0.7    aks-nodepool1-32797235-0   <none>
metrics-server-5cbc77f79f-44f9w         1/1     Running   0          4h    10.244.0.3    aks-nodepool1-32797235-0   <none>
tiller-deploy-57f988f854-z9qln          1/1     Running   0          4h    10.244.0.8    aks-nodepool1-32797235-0   <none>
tunnelfront-7cf9d447f9-56g7k            1/1     Running   0          4h    10.244.0.2    aks-nodepool1-32797235-0   <none>

What needs be changed (number of replicas? PDB configuration?) for down-scaling to work?

A: Basically, this is an administration issues when draining nodes that are configured by PDB ( Pod Disruption Budget )
This is because the evictions are forced to respect the PDB you specify
you have two options:
Either force the hand:
kubectl drain foo --force --grace-period=0

you can check other options from the doc -> https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#drain
or use the eviction api:
{
  "apiVersion": "policy/v1beta1",
  "kind": "Eviction",
  "metadata": {
    "name": "quux",
    "namespace": "default"
  }
}

Anyhow, the drain or the eviction api attempts delete on pod to let them be scheduled elswhere before completely draining the node
As mentioned in the docs:
the API can respond in one of three ways:

*

*If the eviction is granted, then the pod is deleted just as if you had sent a DELETE request to the pod's URL and you get back 200 OK.

*If the current state of affairs wouldn't allow an eviction by the rules set forth in the budget, you get back 429 Too Many Requests. This is typically used for generic rate limiting of any requests

*If there is some kind of misconfiguration, like multiple budgets pointing at the same pod, you will get 500 Internal Server Error.

For a given eviction request, there are two cases:

*

*There is no budget that matches this pod. In this case, the server always returns 200 OK.

*There is at least one budget. In this case, any of the three above responses may apply.
If it gets stuck then you might need to do it manually
you can read me here or here


text:
Q: insert data from excel into database using spring boot I suppose to insert the excel sheet data into database using spring boot but i don't know how mainly i'm not gonna insert all the columns from the excel file ,only the columns i need to use.
I don't know how to start .So can anyone help me please?

A: Use POI library to read Data and dump it to DB through a connection. Refer to this link.


text:
Q: Angular-Material : md-select in md-dialog not closing I've created a simple directive that consists in a form with few md-input and one md-select.
I've used my directives in a few pages now and everything works fine, but now i would like to use it inside an md-dialog and it's not working as expected, i can't close the md-select-menu if i click outside of it, even if i focus an md-input.
So the only two ways for the user to close the menu is to either select an option or dismiss the dialog.
It's not that bad but i found this rather annoying.
Here is the content of the dialog :
<md-dialog aria-label="Modal" ng-cloak flex="75">
    <md-toolbar ng-class="md-primary">

personModal.update

            <md-button class="md-icon-button" ng-click="cancel()">
                <md-icon md-svg-src="img/ic_close_white.svg" aria-label="Close dialog"></md-icon>
            </md-button>

    </md-toolbar>
    <person-form person="person"></person-form>
</md-dialog>

And the directive content :
<form name="createPersonForm" layout="row" layout-align="space-between center" class="bg-sec query-fields">
    <md-input-container flex class="full-width-input">
        createPerson.form.firstname
        <input name="firstname" ng-model="person.firstname" required md-asterisk/>

                createPersonForm.errors.firstnameMissing

    </md-input-container>

    <md-input-container flex class="consumption-filter full-width-input">
        createPerson.form.contact
        <md-select name="contact" ng-model="person.contactId" required>
            <md-option ng-repeat="contact in contacts" ng-value="{{contact.id}}">
                {{contact.name}}
            </md-option>
        </md-select>

                createPersonForm.errors.contactMissing

    </md-input-container>

    <md-button class="md-raised bg-white" ng-click="createPerson()" ng-disabled="createPersonForm.$invalid" ng-hide="loading" >createPersonForm.errors.createButton</md-button>
    <md-progress-circular md-mode="indeterminate" class="md-accent" ng-show="loading"></md-progress-circular>
</form>

I'm using Angular 1.5 and Angular Material 1.0 .
I tried toying around with z-index, and upgrading angular/angular material, but it doesn't solve the problem.
I'm considering closing the menu programatically when the md-select looses focus, but i found that kinda ugly. And i don't know how do to do that yet.
Thanks in advance !

A: Using the method proposed by Freego above throws an error for me on angular-material 1.1.5
TypeError: Cannot read property '$viewValue' of undefined

I got this fixed in angular-material 1.1.5 by setting the z-index for <md-backdrop /> alongside .md-select-menu-container.
.md-select-menu-container {
    z-index: 900;
}

md-backdrop.md-select-backdrop {
    z-index: 899;
}

A: For those interested here is what i've done to fix my problem. I know it's not the most elegant solution, but it worked for me. If anyone has a better idea feel free to share with us !
HTML :
            <md-input-container flex>
                Category
                <md-select ng-model="selectedCategory" md-on-open="dirtyFix()">
                    <md-option ng-repeat="cat in categories" ng-value="{{cat}}" ng-selected="$first">{{cat.name}}
                    </md-option>
                </md-select>
            </md-input-container>

JS :
$scope.dirtyFix= function () {
    $timeout(function () {
        $(".md-scroll-mask").css("z-index", 899);
        $(".md-scroll-mask").click(function () {
            $(".md-select-menu-container").remove();
            $(".md-scroll-mask").css("z-index", -1);
        });
    }, 500);
}

CSS :
.md-select-menu-container {
    z-index: 900;
}

Had to set a timeout to let the modal render and then toy with z-index and clicklistener.
It's far from perfect but maybe it'll inspire you !


text:
Q: Run external tool before GIT commit in PHPStorm Our project uses gettext to allow for multiple languages. Further, there is a *.bat and *.sh file, which generates the current POT file both from the PHP files and Smarty templates.
Is there a way to configure PHPStorm to execute an external tool (for example the bat file), before doing a GIT commit? In the commit window, there is only the possibility to execute a tool after commit. However, after doing changes in the code, I would like to update the POT first, then commit the code.

A: That looks like the clean step of a content filter driver:

(image shown in "Customizing Git - Git Attributes", from "Pro Git book")
The commit would trigger the clean script in order to modify the files, before the commit.
The clean script is:

*

*declared with git config filter.<filtername>.clean ./<filterscript>

*used in a .gitattributes file.


text:
Q: What's the better way to add multiple cookies - response.addCookie(cookie) or response.addHeader("Cookie", "value") I want to add two cookies to the response, and would like to know what's the best practice to do that and why? This is a general question, but in my case i am sending the response to a non web browser REST client. Here are few options i could think of:
Option 1:

// create cookie and set maxage, domain etc. if applicable
Cookie cookie1 = new Cookie("cookie1", "value1");
response.addCookie(cookie1);

// create cookie and set maxage, domain etc. if applicable
Cookie cookie2 = new Cookie("cookie2", "value2");
response.addCookie(cookie2);

Option 2:

response.addHeader("Cookie", "cookie1=value1");
response.addHeader("Cookie", "cookie2=value2");

Option 3:

response.addHeader("Cookie", "cookie1=value1;cookie2=value2");

Can someone plz suggest/reason the best way from above options.

Thanks

A: First, a server needs to set the Set-Cookie header not the Cookie header in the response. Second, the addCookie(Cookie) method exist specifically to make your life easier, use it. A cookie can have much more than just a name and a value like in cookie1=value1. It can have an age, a path, a security level, etc. Writing these out in a String is a hassle.


text:
Q: Switch statement in C++ Consider:
#include <iostream>

using namespace std;

int main()
{
    int score;
    char grade;
    cout << "Enter your score: " << endl;
    cin >> score;
    if (score >= 90)
        grade = 'a';
    if (score >= 80)
        grade = 'b';
    if (score >= 70)
        grade = 'c';
    if (score >= 60)
        grade = 'd';
    else
        grade = 'f';

    cout << grade << endl;

    switch (grade) {
        case 'a':
            cout << "Good job" << endl;
            break;
        case 'c':
            cout << "Fair job" << endl;
            break;
        case 'f':
            cout << "Failure" << endl;
            break;
        default:
            cout << "invalid" << endl;
    }

    cin.get();
    return 0;
}

Why is it giving my default switch case when I enter 95 when I should be getting case 'a'?

A: You're missing a bunch of elses, or doing the comparisons in the wrong order.
95 is greater than 90, but it's also greater than 80, 70 and 60. So you'll get a 'd'.
(And you're not handling 'd' in your switch.)

A: I believe you want
if (score >= 90)
    grade = 'a';
else if (score >= 80)
    grade = 'b';
else if (score >= 70)
    grade = 'c';
else if (score >= 60)
    grade = 'd';
else
    grade = 'f';

What you have does not mutually exclude any but the last two cases, 60 and above and lower. Your code doesn't short circuit; it checks all of 1 through 5.
if (score >= 90) // 1.
    grade = 'a';

if (score >= 80) // 2.
    grade = 'b';

if (score >= 70) // 4.
    grade = 'c';

if (score >= 60) // 5.
    grade = 'd';
else
    grade = 'f';

A: I think you want to use 'else if'. It is falling down to the last if "score >= 60" which is true, and grade then equals "d", which produces the default case in your switch statement.

A: You have specified it such that your 95 satisfies all the cases: 95 is bigger than 90, but also bigger than 80, than 70, etc.
In this case, the last one wins.
You can solve it by either using elses, or by wrapping it in a function and returning as soon as you know the grade you need:
char grade(int score) {
   if (score >= 90) return 'a';
   if (score >= 80) return 'b';
   ...
}

A: The if branches are ordered wrong (or you need to provide else branches like so:)).
See it live here: http://ideone.com/2uSZT
#include <iostream>

using namespace std;

int main()
{
    int score;
    char grade;
    cout << "Enter your score:" << endl;
    cin >> score;
    if (score >= 90)
        grade = 'a';
    else if (score >= 80)
        grade = 'b';
    else if (score >= 70)
        grade = 'c';
    else if (score >= 60)
        grade = 'd';
    else
        grade = 'f';

    cout << grade << endl;
    switch (grade)
    {
    case 'a':
        cout << "Good job" << endl;
        break;
    case 'c':
        cout << "Fair job" << endl;
        break;
    case 'f':
        cout << "Failure" << endl;
        break;
    default:
        cout << "invalid" << endl;
    }
    cin.get();
    return 0;
}

A: It's because of your if statements up top. You should be using else ifs instead of individual ifs. Your if for 90 is following through, and then so are all the others. Your letter "a" is essentially being overwritten because 95 is >= to all of the other conditions. Using an else if will break the rest of the checks when a true one is found.
if (score >= 90)
    grade = 'a';
else if (score >= 80)
    grade = 'b';
else if (score >= 70)
    grade = 'c';
else if (score >= 60)
    grade = 'd';
else
    grade = 'f';

A: Because all score comparisons are not combined with if/else if conditions. They are independent if statements. Thus grade gets overwritten for 95.

A: You need to improve your if conditions.
You are checking score >= no. The input 95 executes all the if statements and the last executed statement was the d. Now in your switch statement, case d is not present so it executes the default one.

A: You've gotten some answers already, but I think I'll suggest a slightly different possibility that gets rid of most of the control flow and substitutes a bit of math:
char grades[] = "00000012344";

char *messages[] = {
    "Excellent Job",
    "Good job",
    "Average job",
    "Mediocre Job",
    "Failure"
};

if (score < 0 || score > 100)
    std::cout << "Invalid score";
else {
    int grade = grades[score/10];
    std::cout << messages[grade];
}

So, we use score/10 to turn scores of 0-100 to 0-10. We then look up the appropriate grade for a score, with f=0, d=1, c=2, b=3 and a=4. We use that to select and print out the appropriate message. I've added messages (that may or may not be quite what you want) for the letters you skipped.


text:
Q: How to retain Conductor's router object during activity re-create? Let say I have a Conductor's Router lives inside an Activity. The Router is holding 4 Conductor's Controller inside it.
When I re-create my activity by changing the locale for example.
Is this possible I can somehow retain the Router for my activity after it's re-created?
I know about the saveInstanceState and restoreInstanceState of activity but since Router is neither implementation of Parcelable nor Serializable. So, those method are not the option here. :(


text:
Q: Curl Requests Params inside url I have an API, where all important Parameter like ID, category is in the Request's URL and not as payload. What would be the smartest and recommended way to solve this?
curl --request GET \
  --url 'https://api.otto.market/v2/products?sku=SOME_STRING_VALUE&productReference=SOME_STRING_VALUE&category=SOME_STRING_VALUE&brand=SOME_STRING_VALUE&page=SOME_INTEGER_VALUE&limit=SOME_INTEGER_VALUE' \
  --header 'Authorization: Bearer REPLACE_BEARER_TOKEN'

What I did till now
def example(content_type: str, cache_control: str, grand_type:str, client_id:str):

    endpoint = website.BASE_URL
    header_content = {
        'Content-Type': (f'{content_type}'),
        'Cache-Control': (f'{cache_control}')
    }
    data_content = {
        'grant_type': (f'{grand_type}'),
        'client_id': (f'{client_id}')
    }
    response = requests.get(url= endpoint, headers=header_content, data=data_content, verify=False)
    return response

A: requests.get has optional parameter params where you might deliver dict, consider following simple example
import requests
parameters = {"client":"123","product":"abc","category":"a"}
r = requests.get("https://www.example.com",params=parameters)
print(r.url)  # https://www.example.com/?client=123&product=abc&category=a

For further discussion read Passing Parameters In URLs

A: The curl request that you posted in python would be:
import requests

headers = {
    'Authorization': 'Bearer REPLACE_BEARER_TOKEN',
}

params = {
    'sku': 'SOME_STRING_VALUE',
    'productReference': 'SOME_STRING_VALUE',
    'category': 'SOME_STRING_VALUE',
    'brand': 'SOME_STRING_VALUE',
    'page': 'SOME_INTEGER_VALUE',
    'limit': 'SOME_INTEGER_VALUE',
}

response = requests.get('https://api.otto.market/v2/products', params=params, headers=headers)

Insert your variables as required.


text:
Q: Can I run an LED light fitting which states 265 V input with 240 V power? Can I run an LED light fitting which states 265 V input with 240 V power - Australian power?

A: For LED drivers, an input voltage rating of AC 85-265V 50/60Hz isn't uncommon. So I'm assuming the 265V refer to the max rated voltage.
In Australia the nominal supply voltage is 230V. But in practice 240V ±6% is still widely spread. In order to deal with this discrepancy the rated supply voltage is 230V +10%/−6%.
230V + 10% = 253V
240V + 6% = 254.4V
Both voltages are within the accepted range of max 265V, so you should be fine.
Source: Australian Rectifiers


text:
Q: Confusion over cartesian product, how do elements in $\mathbb{N}^k$ look? I was always under the impression for the cartesian product of $\mathbb{N}^k$, an element in the set was of the form $(a_1,a_2,a_3,...a_k)$. Is this correct?

A: There is an alternative definition of the product using functions. It is as follows:
$$
\prod_{i \in I}X_i = \left\{ f: I \to \bigcup_{i \in I} X_i \ \ | \ \ f(i) \in X_i \ \ \forall i \in I \right\}.
$$
In your particular example $X_i = \Bbb{N}$ for every $I \in I =\{0 \leq i \leq k\}$. This definition becomes particularly useful if you are interested in infinite products.
However, you are right, it is merely a $k$-tuple of elements from $\Bbb{N}$.


text:
Q: How to convert sql query using between to codeigniter I have sql query that i need to convert to codeigniter. can anyone help me with this?
the sql query is
SELECT * FROM m_slow_log WHERE start_time BETWEEN CAST('2020-01-15%' AS DATE) AND CAST('2020-01-22%' AS DATE);

A: Try use this one
public $table = 'm_slow_log';

function getbetween() {
$where = "start_time BETWEEN CAST('2020-01-15%' AS DATE) AND CAST('2020-01-22%' AS DATE)";
$this->db->where($where);
$this->db->from($this->table);
    return $this->db->count_all_results();
}

or you can set the date at controller/view
public $table = 'm_slow_log';

function getbetween($f, $t) {
$this->db->where("start_time BETWEEN '$f' AND '$t'");
$this->db->where($where);
$this->db->from($this->table);
    return $this->db->count_all_results();
}

A: Use Simple query like
 $this->db->query(SELECT * FROM m_slow_log WHERE start_time BETWEEN CAST('2020-01-15%' AS DATE) AND CAST('2020-01-22%' AS DATE))->row();


text:
Q: Will Windows XP work on a Hybrid Hard Drive? I'm looking into getting the Seagate Momentus XT hybrid hard drive, and I'm planning on dual booting between Windows 7 and Windows XP. I know 7 and Vista have native support for taking advantage of the SSD portion of a hybrid drive, and I assume XP does not have any such support, but will XP still work on the drive? I would think it will, but I wanted to be sure, and the Googles are coming up empty for me on this one.
Thanks!

A: I know someone that has that drive and does have XP running on it.

A: It will work I also have one, the TRIM function wont work in XP however.


text:
Q: If $\wp(u) = \wp(v)$, then $u-v$ or $u+v$ is a period of $\wp$ The Weierstrass $\wp$ function with an associated lattice $L$ is given by the following equation for $z \notin L:$
$$
\wp(z)=\frac{1}{z^{2}}+\sum_{\omega \in L \backslash\{0\}}\left[\frac{1}{(z-\omega)^{2}}+\frac{1}{\omega^{2}}\right].
$$
What we want to show that $\wp(u) = \wp(v)$ if and only if $u-v$ or $u+v$ is a period of $\wp$.
My attempt:
($\Leftarrow$): If $u-v$ is a period of $\wp$, then $\wp((u-v)+z)=\wp(z)$. In particular, we have that
$$\wp(u)=\wp((u-v)+v)=\wp(v).$$
Similarly, If $u+v$ is a period of $\wp$, then $\wp((u+v)+z)=\wp(z)$. In particular, we have that
$$\wp(u)=\wp((u+v)-v)=\wp(-v)=\wp(v),$$ since $\wp$ is an even funciton.
($\Rightarrow$): Is there any idea to show this direction?

A: COMMENT.- The attached figure shows a fundamental parallelogram and the values that the Wierstrass function takes in it. Can you deduce from this the properties that you enunciate?


text:
Q: Variable inside array in Wordpress I have some problem here with some code in Wordpress.
<?php
$output="";
foreach($type2 as $t) {$output.= "'".$t->slug."',"; }
echo $output;
?>

This code outputs this:
'cocinas','banos-y-spa','mobiliario-de-hogar',

The problem comes when I want to use $output to put it in an array:
<?php
if(is_tax( 'type', array ($output))) {
putRevSlider(get_queried_object()->slug);}
?>

The strange thing is that this one does work ok, although it's not useful, because I need it to be dynamic:
<?php
if(is_tax( 'type', array ('cocinas','banos-y-spa','mobiliario-de-hogar',))) {
putRevSlider(get_queried_object()->slug);}
?>

Why doesn't $output work inside the array if it has the same values?

A: Why are you converting array content into string.
Anyways, convert the $type2 into the format you are looking for:
<?php
$output=array();
foreach($type2 as $t) {
    $output[] =  $t->slug;
}
?>

This will provide you appropriate array which you can use directly in your is_tax() function.
<?php
if(is_tax( 'type', $output)) {
putRevSlider(get_queried_object()->slug);}
?>


text:
Q: How do i collapse navbar after I click the nav items using Javascript? I'm using Bootstrap4, but after clicking my navigation menu, it won't collapse, I'm trying to do this in Javascript. Any help?

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-
         target="#navbarResponsive">

      </button>

            Home

            About

            Portfolio

            Contact

CSS
.navbar {
    padding: .7rem 1rem;
    text-transform: uppercase;
    font-size: .9rem;
    font-weight: 700;
    letter-spacing: .1rem;
    transition: background-color .5s ease 0s;
  background-color: black;
}

.navbar-nav li{
  padding: .8rem;
}
.navbar-nav .nav-link{
  color: white;
  padding-top:.8rem;
}
.navbar-nav .nav-link.active,
.navbar-nav .nav-link:hover{
    color:#c83832;
    transition: ease-in-out .15s;
}

.navbar-toggler{
    color: white;
}

JS
$(document).ready(function() {
  $(document).click(function(event) {
    var clickover = $(event.target);
    var opened = $(".navbar-collapse").hasClass("show");
    if (opened === true && !clickover.hasClass("navbar-toggler")) {
      $(".navbar-toggler").click();
    }
  });
});