text:
Q: Placement of latitude labels in cartopy with polar stereographic projection I am trying to figure out how to change the placement of gridline labels (more specifically, latitude labels) in cartopy when using a polar stereographic projection (NorthPolarStereo). My axis currently looks like this:
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import numpy as np
import cartopy.crs as ccrs

# Helper function
# from https://nordicesmhub.github.io/NEGI-Abisko-2019/training/example_NorthPolarStereo_projection.html
def polarCentral_set_latlim(lat_lims, ax):
    ax.set_extent([-180, 180, lat_lims[0], lat_lims[1]], ccrs.PlateCarree())
    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)
    ax.set_boundary(circle, transform=ax.transAxes)

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(1,1,1,projection=ccrs.NorthPolarStereo(central_longitude=0))
ax.coastlines(linewidth=0.5,color='k')
ax.gridlines(color='C7',lw=1,ls=':',draw_labels=True,rotate_labels=False,ylocs=[60,70,80])
polarCentral_set_latlim((50,90),ax)

Oddly, the latitude labels are always plotted at about 150E even if the central_longitude is set to a different value. Preferably, I'd like to align them with the 180th meridian (similar to the labels in this plot) but I cannot find an option in the documentation of the gridlines function to set their position. Did I overlook something or would I have to place them manually with plt.text()

A: After the gridlines is created, some labels can be accessed and moved to new positions.
I use alternate method to define the circular boundary of the plot in order not to interfere with gridlines' labels.
import cartopy.crs as ccrs      #cartopy v0.19
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import numpy as np

# Value for r_extent is obtained by trial and error
# get it with `ax.get_ylim()` after running this code
r_extent = 4651194.319
r_extent *= 1.005       #increase a bit for better result

# Projection settings
lonlat_proj = ccrs.PlateCarree()
use_proj = ccrs.NorthPolarStereo(central_longitude=0)
fig = plt.figure(figsize=[7, 7])
ax = plt.subplot(1, 1, 1, projection=use_proj)
ax.set_extent([-180, 180, 50, 90], lonlat_proj)

#ax.stock_img() # add bluemarble image
ax.coastlines(lw=0.5, color="black", zorder=20) # add coastlines

# draw graticule (meridian and parallel lines)
gls = ax.gridlines(draw_labels=True, crs=lonlat_proj, lw=1, color="gray",
        y_inline=True, xlocs=range(-180,180,30), ylocs=range(0,90,10))

# set the plot limits
ax.set_xlim(-r_extent, r_extent)
ax.set_ylim(-r_extent, r_extent)

# Prep circular boundary
circle_path = mpath.Path.unit_circle()
circle_path = mpath.Path(circle_path.vertices.copy() * r_extent,
                           circle_path.codes.copy())

#set circular boundary
#this method will not interfere with the gridlines' labels
ax.set_boundary(circle_path)
ax.set_frame_on(False)  #hide the boundary frame

plt.draw()  # Enable the use of `gl._labels`

# Reposition the tick labels
# Labels at 150d meridian will be moved to 180d
for ea in gls._labels:
    # No _labels if not run `plt.draw()`
    pos = ea[2].get_position()
    #print("Position:", pos[0], pos[1])
    if (pos[0]==150):
        ea[2].set_position([180, pos[1]])

plt.show()

Edit (Mar 3, 2023)
The code above worked well for Cartopy v0.19. The gridlines in newer versions has changed, and parts of the code need update.
Here is the relevant code:-
# ...
for ea in gls.label_artists:
    pos = ea.get_position()
    if pos[0] == 150:
        print("Position:", pos, ea.get_text() )
        ea.set_position([180, pos[1]])

plt.show()

A: Might because of the cartopy version (0.21.1) I used but the the answer by @swatchai didn't work for me. Yet a slight change can be done and will work fine.
plt.draw()
for ea in gls.label_artists:
    # return ea of mpl.text type, e.g. Text(135, 30, '30°N')
    pos = ea.get_position()
    if pos[0] == 135:
        ea.set_position([180, pos[1]])


text:
Q: How do I generate an extrinsic proof that encodes the actual extrinsic for which the proof was generated I am trying to generate an extrinsic proof that can in turn be used to generate a partial trie and then extract the actual extrinsic for which the proof was generated from the trie, but I've not been able to figure it out yet.
Currently I'm using the trie_db::proof::generate_proof to generate the proof
This is what I've done so far https://github.com/Wizdave97/extrinsic-from-proof/blob/master/src/main.rs
The issue is the second line of this snippet returns an error 'InvalidStateRoot'
    let db = sp_trie::storage_proof::StorageProof::new(proof.to_vec()).into_memory_db::<BlakeTwo256>();
    let trie = sp_trie::TrieDB::<sp_trie::LayoutV0<BlakeTwo256>>::new(&db, root).unwrap();

redpajama_set_name: RedPajamaStackExchange


text:
Q: nginx status : requests? Acorrding to nginx stats module

server accepts handled requests -- nginx accepted 16630948 connections, handled 16630948 connections (no one was closed just it was accepted), and handles 31070465 requests (1.8 requests per connection)

I would like to know what the requests part means it say 1.8 per connection that does not make sense to me thanks in advance.

A: Nowadays keep-alive (or persistent) http connections are normal, especially in http 1.1. One keep-alive connection can handle more than 1 request.
Reference: http://en.wikipedia.org/wiki/HTTP_persistent_connection


text:
Q: Bootstrap Contact Form server not responding I am trying to get my contact form to work, but when I fill out the form, it throws out a server not responding error.
You can view the JSFiddle here: JS & HTML contact form code
The contact_me.php code:
<?php

error_reporting(E_ALL); ini_set('display_errors', 1);

// check if fields passed are empty
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   empty($_POST['phone'])       ||
   empty($_POST['message'])     ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// create email body and send it
$to = 'trisha@trishajohnson.net'; // put your email
$email_subject = "Contact form submitted by:  $name";
$email_body = "You have received a new message. \n\n".
                  " Here are the details:\n \nName: $name \n ".
                  "Email: $email_address\n Phone: $phone\n Message: \n $message";
$headers = "From: no-reply@trishajohnson.net\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

I don't see any errors in any of the code, so I'm not quite sure what the issue is.

A: When I visited your page, I noticed the following were missing from the form:

*

*The form's action. Forms default to GET when omitted.

*Missing name elements.

Solution:

*

*Add method="post" inside the form.

*Add the name attribute to the inputs, i.e.: <input type="text" name="name">
Your PHP contains POST variables and POST relies on the name attribute in order to process the form's data.
Sidenote: Your original question did not contain the error reporting, which should be used to check for errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.


text:
Q: PHP - Parse XML with simplexml_load_string - Getting empty values with CDATA? When parsing an XML array like:
<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product>
    ABC-1001
    <Brand>ZCOM</Brand>
  </Product>
</Products>

I get an output of:
Array
(
  [0] => Array
  (
    [Code] => AP1024-DDRII640
    [Brand] => ZCOM
  )
}

But when the XML is like:
<?xml version="1.0" encoding="utf-8"?>
<Products Code="ABC-1001">
  <Product>
    <![CDATA[ABC-1001]]>
    <Brand><![CDATA[ZCOM]]></Brand>
  </Product>
</Products>

It returns:
array
  0 =>
    array (size=12)
      '@attributes' =>
        array (size=1)
          'Code' => string 'ABC-1001' (length=8)
      'Code' =>
        array (size=0)
          empty
      'Brand' =>
        array (size=0)
          empty

This is how the XML is parsed from a URL:
$updateUrl = file_get_contents('http://www.someplace/xmlfeed/xml.cfm?asd=12345&uhg=9999');
$updateXml=<<<XML
$updateUrl
XML;
$updateXmlObject=json_decode(json_encode((array) simplexml_load_string($updateXml)), 1);
$updatePHPArray=$updateXmlObject['Product'];

And:
var_dump($updatePHPArray);exit;

Gives the output as above.
Now, why am I getting empty values in the second instance and how could I remedy this without access to the XML source?

A: The problem seems to be that the cast you're doing to array can return results different than the actual structure of the XML object.
Something like the following code should give you an array with the correct info:
$array = array_map('strval', (array) $xml->Product);

Take care you cast those parts to string of which you'll get the data from (in the example done via strval()). In the opposite, json_encode() is not working well with SimpleXMLElement.


text:
Q: Were Elves & Men clothed when they awoke? I am curious as to what condition they awoke in. Does it specify, or is it left to the reader's imagination?

A: We know practically nothing about the physical state of the Children of Ilúvatar at the time of their awakening. In the published Silmarillion, the awakening of the Elves is described very simply:

It is told that even as Varda ended her labours, and they were long, when first Menelmacar strode up the sky and the blue fire of Helluin flickered in the mists above the borders of the world, in that hour the Children of the Earth awoke, the Firstborn of Ilúvatar. By the starlit mere of Cuiviénen, Water of Awakening, they rose from the sleep of Ilúvatar; and while they dwelt yet silent by Cuiviénen their eyes beheld first of all things the stars of heaven.
The Silmarillion III Quenta Silmarillion Chapter 2: "Of the Coming of the Elves and the Captivity of Melkor"

The awakening of Men is similarly vague:

At the first rising of the Sun the Younger Children of Ilúvatar awoke in the land of Hildórien in the eastward regions of Middle-earth; but the first Sun arose in the West, and the opening eyes of Men were turned towards it, and their feet as they wandered over the Earth for the most part strayed that way.
The Silmarillion III Quenta Silmarillion Chapter 12: "Of Men"

As near as I can tell, none of the drafts in History of Middle-earth offer more detail than this; there's certainly no reference to clothing that I can find.
There is a very early draft (the earliest, from The Book of Lost Tales) that describes Men in slightly more detail, but offers no hints at answering this question:

Now did Nuin descend deeper into the vale, treading softly by reason of some unknown wonder that possessed him, and lo, beneath the trees he saw the warm dusk full of sleeping forms, and some were twined each in the other's arms, and some lay sleeping gently all alone, and Nuin stood and marvelled, scarce breathing.
History of Middle-earth I The Book of Lost Tales, Part One Chapter 10: "Gilfanon's Tale: The Travail of the Noldoli and the Coming of Mankind"


text: Q: Зачем всегда писать интерфейсы для репозиториев, сервисов и контроллеров в mvc? Интерфейсы, как я понял, служат для абстракции. Один интерфейс - множество реализаций. Зачем тогда всегда писать интерфейсы в частности для репозиториев, для сервисного слоя, для контроллеров? В 99% случаев реализация интерфейса будет только одна. Единственное что приходит на ум, это ограничение доступа к методам реализации с помощью интерфейса для использования в других классах. Что можно почитать по этой теме?


text:
Q: Why does using Displacement vector doesn't give the correct result for the surface charge density of an infinite dielectric slab below a point charge
Find the force on a point charge $q$ placed a distance $d$ above the XY plane with the region $z<0$ filled with dielectric with susceptibilty $\chi_{e}$.
(From Griffiths EM, Example 4.8)

The author employs two methods, one which calculates the z component of the net electric field at a point $\mathbf{r}$ from origin in the XY plane and then use it in the relation $\sigma_{b} = P_z = \chi_e \epsilon_0E_z$ to find $\sigma_b$. The other one uses the familiar Image Method, both of which makes perfect sense. The surface charge density comes out to be:
$$\sigma_b = -\frac{1}{2\pi}\frac{\chi_e}{\chi_e+2}\frac{qd}{(r^2+d^2)^{3/2}}$$
However, I tried to do it on my own with the use of Displacement Vector D. Here's how I proceed:
$$\oint_{\mathcal{S}}\mathbf{D\cdot}d\mathbf{a} = Q_{f\,encl}$$
where $\mathcal{S}$ is the gaussian surface, a sphere centered at $q$ with radius $\mathcal{R}$, therefore
$$D\cdot(4\pi\mathcal{R}^2) = q$$ $$\text{or}\;\;\mathbf{D} = \frac{q\mathbf{\hat{\mathcal{R}}}}{4\pi\mathcal{R}^2}\;,\;\;\text{everywhere}$$
$$\text{so,}\;\;\mathbf{E}=\frac{\mathbf{D}}{(1+\chi_e)\epsilon_0}=\frac{q\mathbf{\hat{\mathcal{R}}}}{4\pi(1+\chi_e)\epsilon_0\mathcal{R}^2}$$
$$\therefore\;\;\mathbf{P}=\chi_e\epsilon_0\mathbf{E}=\frac{\chi_eq\mathbf{\hat{\mathcal{R}}}}{4\pi(1+\chi_e)\mathcal{R}^2}\;\;\text{, just below the surface, inside the dielectric}$$
Now, $\sigma_b$ will be then just $\mathbf{P\cdot\hat{n}}$, where $\mathbf{\hat{n}=\hat{k}}$ and $\mathbf{\mathcal{R}=r-}d\mathbf{\hat{k}}$. So,
$$\sigma_b = \frac{\chi_eq\mathbf{\hat{\mathcal{R}}\cdot\hat{k}}}{4\pi(1+\chi_e)\mathcal{R}^2} = - \frac{\chi_eqd}{4\pi(1+\chi_e)\mathcal{R}^{3}}\;\;\text{as,}\;\mathbf{\hat{\mathcal{R}}\cdot\hat{k}} = - \frac{d}{\mathcal{R}}$$
$$\text{i.e.,}\;\;\;\sigma_b = -\frac{1}{4\pi}\frac{\chi_e}{1+\chi_e}\frac{qd}{\mathcal{R}^{3}}$$
which comes out to be different from the one found above, surely something has gone wrong, but I am not able to make out what am I missing here.
Although I have used the correct equations but it seems that they do not apply nicely in this case, for which I am unsure of why the displacement method does't work here, what difference does it causes from the above two methods. Is it ok @ACuriousMind?


text:
Q: Adding index at uitableview is not working in Swift 2.0 I am loading contacts in UITableView and I want to add index at the right end for user to navigate through contacts.
I am using the code:
var indexOfNames = [String]()
let indexNames = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
indexOfNames = indexNames.componentsSeparatedByString(" ")

func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    return indexOfNames
}

func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    let temp = indexOfNames as NSArray
    return temp.indexOfObject(title)
}

But it is not working. When I tap on the index, the table view comes to the top row. i.e. A. I have set the delegates for tableview. Maybe there is some issues with Swift 2.0?

A: Adding index to UITableView working for me may help you (for swift 2.0):
 var arrIndexSection : NSMutableArray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

 //MARK:- TableView Datasource/DataDelegate Method
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return arrIndexSection.count
    }
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return arrIndexSection.objectAtIndex(section) as? String
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
        return self.arrIndexSection as? [String]
    }


text:
Q: Devo evitar o acesso repetido ao mesmo método dentro de um loop? Eu me preocupo com o desempenho final de um executável, ao mesmo tempo, não quero penalizar o programador com cuidados excessivos ou desnecessários no código.
No código abaixo, por exemplo, ele retornará o mesmo valor do método getPosition por 10000 vezes:
for (int i=0; i<10000 ; i++)
    std::cout << i + window.getPosition().x << endl;

Neste caso específico, eu sei que window.getPosition().x sempre retornará o mesmo valor.
Para evitar uma perda de desempenho, deveria eu alterar o código para, por exemplo:
const int x = window.getPosition().x;
for (int i=0; i<10000 ; i++)
    std::cout << i + x << endl;

Isso sempre envolve uma preocupação adicional do programador.
Ou há algum cache inteligente, onde eu não deveria me preocupar com isso?

A: É possível que tenha alguma otimização em código que seja garantido que não muda. Não é o caso. Então deve ser melhor fazer fora. Você sabe que retorna o mesmo valor, o compilador não. Estou partindo do princípio que não retorna uma constante e não faça praticamente mais nada, porque aí pode ser que o método pode ser otimizado para manter a expressão no lugar da chamada e como a expressão é conhecida como constante já na compilação e aí nem precisa fazer a segregação. Na verdade é possível que até o laço desapareça. Claro depende do compilador e como o método foi escrito.
Otimizações sempre dependem de de diversos fatores, como o compilador que está usando, a plataforma que será gerado, a versão do compilador, as configurações usadas, o contexto.
Se o método tiver efeitos colaterais que potencialmente trarão resultados diferentes a cada chamada, então fazer o cache de um resultado antes do laço pode impedir de pegar as alterações. Por outro lado pode ser que não queira pegar modificações, aí se colocar dentro pode não produzir o resultado esperado. Então onde colocar tem a ver com a semântica desejada mais que a otimização.
Note que não é só questão do resultado retornado. Se sempre der o mesmo resultado, mas fizer algo colateral no método chamar uma vez ou 10000 vezes dará resultado total diferente, mesmo que o resultado retornado seja diferente.
Programador existe para ter essas preocupações. Pelo menos os mais profissionais. Para os mais amadores pode importar pouco. A tendência é a inteligência artificial resolver casos simples no longuíssimo prazo, e esses programadores devem ficar sem trabalho.

A: Em vez de tentar adivinhar, por que não dá uma olhada?
Compilando o seguinte código:
#include <utility>
#include <iostream>

struct Window
{
    std::pair<int, int> pos;

    std::pair<int, int> getPosition() const
    {
        return pos;
    }
};

int main()
{
    Window window{{42, 314}};

    for (int i = 0; i < 10000; ++i)
        std::cout << (i + window.getPosition().first) << std::endl;
}

Com Clang 6.0.0, com otimização nível 3:
main: # @main
  push r15
  push r14
  push rbx
  mov r15d, 42
.LBB0_1: # =>This Inner Loop Header: Depth=1
  mov edi, offset std::cout
  mov esi, r15d
  call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
  mov r14, rax
  ; Continua...

Perceba que o valor 42 foi passado para o registrador r15d e, sempre que o laço imprime o valor do primeiro membro do par, ele é passado como argumento pro std::cout.operator<<(int) através do registrador esi, copiando direto de r15d.
Algo parecido é feito por GCC 8.1, com as mesmas flags:
main:
  push r12
  push rbp
  mov ebp, 42
  push rbx
  jmp .L7
  ; Continua...
.L7:
  mov esi, ebp
  mov edi, OFFSET FLAT:std::cout
  call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
  mov r12, rax
  ; Continua...

O valor do primeiro membro do par é guardado no registrador ebp, que é passado como parâmetro para std::cout.operator<<(int) pelo esi também.
Veja os dois resultados no Godbolt.
Como Maniero disse, há vários fatores em jogo na hora do compilador otimizar seu código e, por isso, deve-se evitar adivinhar o que irá acontecer com o seu código. Isole o problema e compile localmente, para ver qual é o resultado. Depois, compile o projeto todo e veja qual é o resultado comparando com o código isolado. Por fim, e mais importante, rode um perfilamento (profiling), ou um benchmark, do código isolado e não isolado, depois faça sua otimização em código (se necessário!) e compare os resultados com novos perfilamentos (não estou nem considerando a arquitetura onde seu programa estará rodando, mas seria bom também). Só assim, você terá certeza de que suas otimizações manuais tiveram sucesso.
Na maior parte dos casos, otimização prematura (i.e. tentar adivinhar o comportamento da execução do seu programa e otimizar em cima disso) é nociva e pode piorar muito mais as otimizações que o compilador consegue fazer.
Sempre otimize pensando nos dados que seu programa processará e pouco na construção do código, comparando perfilamentos pra provar o sucesso das otimizações.


text:
Q: Built In Built-in authenticators issue I am facing an issue while logging to my heroku account. After Logging I am having built-in identification although the identification is verified it is not redirection to my dashboard.
The Following attachment describes.
Image Link

A: Try searching Heroku help center for the issue you are facing. In case if it is unique, then open a new ticket regarding this.


text:
Q: Any way around dispatch pattern with no control over referenced classes I need to operate on an object of uncertain type, I know which types it can assume but I have no control over these types. I cannot modify the Classes A, B, ..
Is there a better solution than:
if (obj instanceof A)
        return extractA((A) obj);
if (obj instanceof B)
        return extractB((B) obj);
....

thanks!

A: As I said in the comments, you cannot delegate to the right overloaded extractStuff because the overloaded method to be invoked has to be decided at compile time.
I'm suggesting an option here to reduce the clutter in the code with all the if.. else by replacing it with a predefined mapping.
Assuming obj has a base type, you can define the which overloaded extractStuff to be invoked for each subclass of the type of obj.
Map<Class<? extends Number>, Function<Number, String>> mappings = new HashMap<>();
mappings.put(Integer.class, i -> extractStuff((Integer) i));
mappings.put(Float.class, f -> extractStuff((Float) f));
mappings.put(Long.class, l -> extractStuff((Long) l));

Here, Number is the base type and we have extractStuff for some of the subtypes of Number.
private static String extractStuff(Integer obj) {
    System.out.println(obj);
    return "Integer called";
}
private static String extractStuff(Float obj) {
    System.out.println(obj);
    return "Float called";
}
private static String extractStuff(Long obj) {
    System.out.println(obj);
    return "Long called";
}

Now, we can delegate to the right extractStuff by looking up the mappings by passing the class of the runtime object we get
public static void test(Number n) {
    System.out.println(mappings.get(n.getClass()).apply(n));
}

Calling code
test(1);
test(1f);
test(1L);

This prints
1
Integer called
1.0
Float called
1
Long called

You need to handle the missing mappings.
Example: test(new BigDecimal(1));
EDIT:
Thanks to Bubletan@ for suggesting this
When you encounter a missing mapping, you can loop till you find one by traversing up the inheritance hierarchy
for (Class<?> c = n.getClass(); c != Object.class; c = c.getSuperclass()) {
   //process and break once you found an entry in the map
}

A: If you already overload methods extract(A a), extract(B b) then you don't have to detect the type by using instanceof and casting. Method dispatch in Java will do just that.
Just create a utility class (here TypeFacade) with overloaded methods for all supported types, e.g.
public class ClassCaster {

  public static class A {
    public String getName() {
        return "A";
    }
  }

  public static class B {
    public String getMyName() {
        return "b";
    }
  }

  public static class C {
    public String getClassName() {
        return "C";
    }
  }

  public static class TypeFacade {

    public static String extractName(A a) {
        return a.getName();
    }

    public static String extractName(B b) {
        return b.getMyName();
    }

    public static String extractName(C c) {
        return c.getClassName();
    }
  }

  public static void main(String[] args) {
    System.out.println(TypeFacade.extractName(new A()));
    System.out.println(TypeFacade.extractName(new B()));
    System.out.println(TypeFacade.extractName(new C()));
  }
}


text:
Q: Flask Print Not Working If I send run this program to do a HTTP Post to my Flask server, which I know returns a 200 response:
import requests
import json
dump= '{"on": false}'
r = requests.post('http://127.0.0.1:5000', data=dump,
                  headers={'Content-Type': 'application/json'})

And my Flask server's code:
from flask import Flask
from flask import request, jsonify
import requests

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def signal():
    if request.method == 'POST':
        content = request.get_json()
        return jsonify(content)
        print(jsonify(content))
        r = requests.put("http://192.168.1.102/api/F5La7UpN6XueJZUts1QdyBBbIU8dEvaT1EZs1Ut0/lights/5/state/", jsonify(content))
    else:
         return 'Hello, world!'

if __name__ == '__main__':
    app.run(debug=True)

I want to print the data to the console, then send it over to a bridge on the network using a HTTP PUT. Neither of these are working, and I'm not sure why.

A: You need to return at the very end of the function
@app.route('/', methods=['GET', 'POST'])
def signal():
    if request.method == 'POST':
        content = request.get_json()
        print(content)
        r = requests.put("http://192.168.1.102/api/F5La7UpN6XueJZUts1QdyBBbIU8dEvaT1EZs1Ut0/lights/5/state/", content)
        return jsonify(content)
    else:
         return 'Hello, world!'

Note: You probably are over-using the jsonify function because the jsonify() function in flask returns flask.Response() object, and not a JSON string that you would POST or PUT to another service.


text:
Q: while sending contact form 7 select option value why am getting null values to database in mysql? while sending contact form 7 select option value why am getting null values to database in mysql?
Site link:https://www.submitmyclips.com/test-form/ form:https://i.stack.imgur.com/Lhzco.pngDatabase:https://i.stack.imgur.com/6Mi4d.png`
Any solution please help

A: You have given the Website URL, which is showing an error.
enter image description here
You can use the contact form 7 DB plugin for this, as the contact form is not storing its value in the Database, we need to use the Addon plugin for the same.
This is the link for your reference, please let me know if you have any query.
https://wordpress.org/plugins/contact-form-cfdb7/


text:
Q: Eclipse Dex Loader Error (Multiple dex files define ) I am trying to run a game app but  I am getting this error .
[2014-07-19 09:18:23 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/badlogic/gdx/Application$ApplicationType;
[2014-07-19 09:18:23 - my-gdx-game-android] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/badlogic/gdx/Application$ApplicationType

I tried cleaning,refreshing and deleting bin folder.If I delete bin folder it generates again. I tried restarting eclipse. But nothing worked for me. I need you help experts.


text:
Q: Is there a way to identify what executable made a network connection? I can identify open connections by
netstat -a
But I wonder if there is a simple way to identify what running exe is making the connection.

A: Yes.  Windows Administrative Tools. Select Resource Monitor. Run it and be sure to expand the Network section. This will tell you what processes are using the Network.


text:
Q: jquery concatenate variable and string i need contenate with jquery a variable with string
this is my example code:
 $("#totriepilogoassegni").html(msg);

After msg i need insert "euro" or "€".
How can fix it ?
Best Regards
Andrea

A: You can use concatenation + operator to concat string to a variable.
$("#totriepilogoassegni").html(msg + ' euro');

$("#totriepilogoassegni").html(msg + ' €');

Using Append
$("#totriepilogoassegni").html(msg).append(' euro');

A: You can create a js method for reuse it:
function currencyAppender(msg, curr){
    return msg +' '+curr;
}

then you can use it this way:
$("#totriepilogoassegni").html(currencyAppender(msg, 'euro'));

This way you can use it for multiple currencies.


text:
Q: Variable in getRange on Google Sheets I want to capture the information of the variable "row" and use it in getRange to find the data that are in the rows that were selected in the variable, for example I already defined the column I want to use, for example "A" and I want getRange to get the data from cell "A2", where the number 2 was selected in the variable "row", but I am not able to get this row value to be processed in the script, could someone help me select this?
function InputBox() {

var ui = SpreadsheetApp.getUi(); var coluna = ui.prompt("Qual coluna você deseja copiar?", ui.ButtonSet.OK);

Logger.log(coluna.getResponseText()); Logger.log(coluna.getSelectedButton());

Tks!

A: You can get the cell value using getValue() on Apps Script. You can add this code for getting the value in a cell which is defined by your variables col and row.
var value = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(<Sheet Name>).getRange(col+row).getValue()

This gets the value of the cell referring to the concatenated col and row("A"+"2").


text:
Q: How to know in which version SQL Server started to support a certain function? I want to check if the SQL scripts I wrote will run successfully on SQL Server regardless of the SQL Server version (or starting from a certain SQL Server version).
For example: how can I check if the following SQL statement will work in old SQL Server versions?
UPDATE TABLE_A
SET TABLE_A.COL_1= TABLE_B.COL_1
FROM TABLE_A AS TABLE_A
LEFT JOIN
TABLE_B AS TABLE_B
ON (TABLE_A.COL_ID=TABLE_B.COL_ID);

A: Changing the compatibility level allows you to "simulate" an older/different version of SQL Server.
So you can change the compatibility level before running you query to determine if a given query will run correctly with a certain version of SQL Server.
Here is the syntax:
ALTER DATABASE [YourDBname] SET COMPATIBILITY_LEVEL = x

where x is the compatibility level:

*

*140: SQL Server vNext

*130: SQL Server 2016

*120: SQL Database

*120: SQL Server 2014

*110: SQL Server 2012

*105: SQL Server 2008 R2

*100: SQL Server 2008

*90: SQL Server 2005

*80: SQL Server 2000

See MSDN for more details
For example the string_split() function has been introduced in SQL Server 2016 (compatibility level 130), therefore running a query containing string_split() with a compatibility level lower than 130 would result in an error:
ALTER DATABASE [YourDBname] SET COMPATIBILITY_LEVEL = 130
go
select value from string_split('1_2_3_4','_')

ALTER DATABASE [YourDBname] SET COMPATIBILITY_LEVEL = 120
go
select value from string_split('1_2_3_4','_')

The first query will execute correctly, while the second will give the following error:

Msg 208, Level 16, State 1, Line 9 Invalid object name 'string_split'.

Edit:
As pointed out by Damien_The_Unbeliever in comments there are some limitations with these approach. Each version of SQL Server can support only a limited number of compatibility level values.
According to MSDN  here are supported compatibility level values for each version (more info here):
+--------------------+--------------------------------------+
|      Product       | Supported Compatibility Level Values |
+--------------------+--------------------------------------+
| SQL Server vNext   | 140, 130, 120, 110, 100              |
| SQL Server 2016    | 130, 120, 110, 100                   |
| SQL Database       | 130, 120, 110, 100                   |
| SQL Server 2014    | 120, 110, 100                        |
| SQL Server 2012    | 110, 100, 90                         |
| SQL Server 2008 R2 | 100, 90, 80                          |
| SQL Server 2008    | 100, 90, 80                          |
| SQL Server 2005    | 90, 80                               |
| SQL Server 2000    | 80                                   |
+--------------------+--------------------------------------+

According to this table with the latest versions of SQL Server (2016, 2014) you can go back till SQL Server 2008, but you can't go back to SQL Server 2005 or 2000


text:
Q: For array copy, does const& perform better? For example
class A
{
    std::array<int, 10> m_data;

    A(std::array<int, 10> data) : m_data(data) {} // version 1 without const&

    A(std::array<int, 10> const& data) : m_data(data) {} // version 2 with const&
};

For the 2 versions, which one performs better?

A: Without optimizations, the second version will perform one copy less. The first one copies the object first to pass it into the constructor by value, and then copies the parameter into the field. The second version only performs copying into the field because the parameter is passed by reference.
However, since you declare these constructors inside the class declaration, it is very likely that the compiler will just optimize away the first copy, and maybe sometimes even both of them if the context allows.
Still, the second way is pretty much industry standard. There is no reason to pass something potentially large by value if you can do it by const reference.


text:
Q: clear a form without refresh am working with a form that has recaptcha and its validated with jquery, everything works perfectly fine *the info is sent to my email and all required field are checked before been send)
the only one problem am facing is that once the info is sent and all fields are reset the error messages are visible
only way they are hidden is if page is i change in the js "reset" instated of "clear" but this refresh the pagge and the thank u message isnt visible anymore.
(i know maybe all sounds bit confiusing)
this is the code what am talking
function validateCaptcha(){
    challengeField = $("input#recaptcha_challenge_field").val();
    responseField = $("input#recaptcha_response_field").val();
    nameField = $("input#name").val();
    emailField = $("input#email").val();
    phoneField =$("input#phone").val();
    reasonField =$("input#reason").val();
    messageField =$("textarea#message").val();

    var html = $.ajax({
    type: "POST",
    url: "ajax.recaptcha.php",
    data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField +"&name="+ nameField +"&email=" + emailField +"&phone="+ phoneField + "&reason=" + reasonField +"&message=" + messageField,
    async: false
    }).responseText;

    if(html == "success")
    {
        $('#contactForm').each (function(){
          this.reset();
         Recaptcha.reload();
        })

        $("#thanks").html("Thank you");

         return false;
    }

    else
    {
        $("#captchaStatus").html("Your captcha is incorrect. Please try again");
        Recaptcha.reload();
        return false;
    }
}

A: Use a reset button to clear the form feilds.
<input type="reset" />

A: Why don't you simply add this:
$("#captchaStatus").html("");

right below:
$("#thanks").html("Thank you");

That should clear out your error message.


text:
Q: Workflow activity causing errors with type ViewStateNameValue I am using visual studio 2017 2017 with SharePoint online (a developer site) to create a SharePoint hosted app. I have just been using the workflow designer so haven't touched the XAML. When I click the start button, with workflow debugging on and a connection string to my azure service bus entered, it returns an error:

In the output panel it says microsoft.workflow.visualstudio.configurator.exe ended with an error.
If I then turn off workflow debugging and run it again this error does not happen (obviously) but if my workflow includes anything that gets the information of the Listitem or the workflow context it just gets rid of the step and replaces it with "Activity could not be loaded because of errors in the XAML":

It also returns errors for the "problem activity"

I even tried following a blog post to the letter to see if I was missing a step but the same thing happens.
The really funny thing is that I have put this project on my home setup and the debugger runs fine! so I reset visual studio and replicated my home set up to ensure I haven't missed an important package somewhere but this is still happening!
Any advice would be greatly appreciated.

A: It turns out that this was two errors:

*

*A reference was missing

*The microsoft.workflow.visualstudio.configurator.exe was trying to use the wrong credentials to authenticate me against the database


text:
Q: arduino json parser failing to parse a uri HI I am trying to use the Json Library by Benoit Blanchon 2014-2016 from this URL https://github.com/bblanchon/ArduinoJson
I struggled at first as I had the second generation ethernet shield.  Got it going once I realised I needed the second ethernet library.
However I get the error message unable to parse json and I am unsure why, and how debug.
// Sample Arduino Json Web Client
// Downloads and parse http://api.sunrise-sunset.org/json?lat=53.440&lng=0.200&date=today
//
// Copyright Benoit Blanchon 2014-2016
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
// If you like this project, please add a star!

#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>

EthernetClient client;
const char* server =    "api.sunrise-sunset.org";                  // server's address
const char* resource =  "/json?lat=53.440&lng=0.200&date=today";   // http resource
const unsigned long BAUD_RATE = 9600;                              //     serial connection speed
const unsigned long HTTP_TIMEOUT = 10000;                          //       max respone time from server
const size_t MAX_CONTENT_SIZE = 512;                               // max size of the HTTP response

// The type of data that we want to extract from the page
struct UserData {
char sunrise[32];
char sunset[32];
};
// ARDUINO entry point #1: runs once when you press reset or power the board
void setup() {
// initSerial();
//  initEthernet();
 Serial.begin(9600);
 Serial.println("Serial ready");
 byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
 byte ip[] = { 192,168,0,202 };
 Ethernet.begin(mac, ip);
 Serial.println("Ethernet ready");
 delay(1000);
 }

 // ARDUINO entry point #2: runs over and over again forever
 void loop() {
  if (connect(server)) {
   if (sendRequest(server, resource) && skipResponseHeaders()) {
   char response[MAX_CONTENT_SIZE];
    readReponseContent(response, sizeof(response));
    UserData userData;
  if (parseUserData(response, &userData)) {
    printUserData(&userData);
  }
}
disconnect();
}
wait();
}

// Initialize Serial port
void initSerial() {
Serial.begin(BAUD_RATE);
while (!Serial) {
 ;  // wait for serial port to initialize
}
Serial.println("Serial ready");
}

// Initialize Ethernet library
void initEthernet() {
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
if (!Ethernet.begin(mac)) {
 Serial.println("Failed to configure Ethernet");
 return;
 }
Serial.println("Ethernet ready");
delay(1000);
}
// Open connection to the HTTP server
bool connect(const char* hostName) {
Serial.print("Connect to ");
Serial.println(hostName);
bool ok = client.connect(hostName, 80);
Serial.println(ok ? "Connected" : "Connection Failed!");
return ok;
}

// Send the HTTP GET request to the server
bool sendRequest(const char* host, const char* resource) {
Serial.print("GET ");
Serial.println(resource);
client.print("GET ");
client.print(resource);
client.println(" HTTP/1.1");
client.print("Host: ");
client.println(server);
client.println("Connection: close");
client.println();
return true;
}

// Skip HTTP headers so that we are at the beginning of the response's body
bool skipResponseHeaders() {
// HTTP headers end with an empty line
char endOfHeaders[] = "\r\n\r\n";
client.setTimeout(HTTP_TIMEOUT);
bool ok = client.find(endOfHeaders);

if (!ok) {
 Serial.println("No response or invalid response!");
}
return ok;
}
// Read the body of the response from the HTTP server
void readReponseContent(char* content, size_t maxSize) {
size_t length = client.readBytes(content, maxSize);
content[length] = 0;
Serial.println(content);
}
// Parse the JSON from the input string and extract the interesting values
// Here is the JSON we need to parse
//{
//  "results":{
//    "sunrise":"5:45:00 AM",
//    "sunset":"5:58:51 PM",
//    "solar_noon":"11:51:55 AM",
//    "day_length":"12:13:51",
//    "civil_twilight_begin":"5:10:15 AM",
//    "civil_twilight_end":"6:33:36 PM",
//    "nautical_twilight_begin":"4:28:54 AM",
//    "nautical_twilight_end":"7:14:57 PM",
//    "astronomical_twilight_begin":"3:45:29 AM",
//    "astronomical_twilight_end":"7:58:22 PM"
//  },
//  "status":"OK"
//}

bool parseUserData(char* content, struct UserData* userData) {
// Compute optimal size of the JSON buffer according to what we need to parse.
// This is only required if you use StaticJsonBuffer.
const size_t BUFFER_SIZE =
  JSON_OBJECT_SIZE(2)     // the root object has 2 elements
  + JSON_OBJECT_SIZE(10);   // the "result" object has 10 elements
// Allocate a temporary memory pool on the stack
StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
// If the memory pool is too big for the stack, use this instead:
// DynamicJsonBuffer jsonBuffer;

JsonObject& root = jsonBuffer.parseObject(content);
 if (!root.success()) {
  Serial.println("JSON parsing failed!");
  return false;
 }
 // Here were copy the strings we're interested in
 strcpy(userData->sunrise, root["results"]["sunrise"]);
 strcpy(userData->sunset, root["results"]["sunset"]);
 // It's not mandatory to make a copy, you could just use the pointers
 // Since, they are pointing inside the "content" buffer, so you need to make
 // sure it's still in memory when you read the string
return true;
}
// Print the data extracted from the JSON
void printUserData(const struct UserData* userData) {
Serial.print("Name = ");
Serial.println(userData->sunrise);
Serial.print("Company = ");
Serial.println(userData->sunset);
}
// Close the connection with the HTTP server
void disconnect() {
Serial.println("Disconnect");
client.stop();
}
// Pause for a 1 minute
void wait() {
 Serial.println("Wait 60 seconds");
 delay(60000);
 }

A: There is a 161 before the JSON string because the server is using Chunked transfer encoding.
It is a feature of the HTTP 1.1 specification and the only way to disable it is to use HTTP 1.0 in the request.
See:

*

*New JsonHttpClient.ino, which uses HTTP 1.0 and doesn't require the response buffer.

*FAQ: Why parsing fails?


text:
Q: Error injector when register on module in angular I have register model as below :
var angularTest = angularTest || {};
angularTest.app = angular.module('angularTest', ['xPlat.service', 'xPlat.controller', 'xPlat.directives', 'xPlat.repository']).run(function (DB) {
    DB.init();
});
angular.module('xPlat.config', []);
angular.module('xPlat.directives', []);
angular.module('xPlat.controller', []);
angular.module('xPlat.service', []);

and I have a controller with the correct use (it's not error) as below :
angularTest.app.controller('logInController', ['$scope', '$http', function ($scope, $http) {
    $scope.login = function () {
        var request = $http({
            method: "post",
            url: "http://localhost:4309/Account/Login",
            data: ""
        })
    }
}]);

but this controller below has error:
(function () {
    'use strict';
    angular.module("xPlat.controller", ['xPlat.service'])
        .controller('itemController', function ($scope, itemService) {
            // todo something

        });
})();

I want to change it like logInController as above. How do I change it?

A: Your code works for me when put into a single JS file. I'm assuming that you are not including the file that contains xPlat.controller in a  on your index.html page (or not including it if you are minifiying).
If you need more assistance, could you try to replicate it in a jsfiddle.


text:
Q: Creating a Macro to transfer only certain data from one worksheet to another that meets a criteria So I need to create a macro that transfers data in specific cells in a column on worksheet 1 to worksheet 2 based on data in a different column in worksheet 1 that meets a specific criteria. Say Worksheet 1 had a column(A) with colors Blue or Green and another column(B) with Apples or Pears (Apples to Blue and Pears to Green). I need to create a macro that will only transfer the Apples that correspond to the color Blue to another column in Worksheet 2.
Sub Update()
  Dim c As Range
  Dim j As Integer
  Dim Source As Worksheet
  Dim Target As Worksheet

    ' Change worksheet designations as needed
    Set Source = ActiveWorkbook.Worksheets("Sheet 2")
    Set Target = ActiveWorkbook.Worksheets("Sheet1")

    j = 1     ' Start copying to row 1 in target sheet
    For Each c In Source.Range("D35:D100")
        If c = "Blue" Then
           Target.Range("C5").Value = Source.Range("B35")
           j = j + 1

        End If
    Next c

End Sub

No matter what I try I cannot get it to only transfer the data that meets the criteria of "Blue". Any help would be greatly appreciated please and thanks!

A: I'm going to assume you wanted to copy this into Column C of your target worksheet...
Sub Update()
  Dim c As Range
  Dim j As Long
  Dim Source As Worksheet
  Dim Target As Worksheet

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("Sheet 2")
Set Target = ActiveWorkbook.Worksheets("Sheet1")

j = 1     ' Start copying to row 1 in target sheet
For Each c In Source.Range("D35:D100")
    If (c.Value = "Blue" And c.Offset(0.1).Value) = "Apples" Or _
(c.Value = "Green" And c.Offset(0,1).Value = "Pears") Then
       Target.Range("C" & j).Value = c.Value
       j = j + 1

    End If
Next c

End Sub


text:
Q: Trailing `1` in GolfScript factorial code I'm trying out the first GolfScript code from here:
4{:n;1:c;{n 1>}{n c*:c;n 1-:n;}while c}:f;f

This outputs 241, which has a redudant 1 at the end.
I can't even remove this using ; at the end of the code.
Is this a bug?

A: I don't know what is exactly wrong, but n makes a lot of bugs.
So just change the name of variable n to something like i.


text:
Q: Derivative of $\log(\log)$ I want the derivative of $\frac{d\left(\log(-\frac{1}{2}\log(p))\right)}{dp}$
Is this correct?
$$\left(\log(-\frac{1}{2}\log(p))\right)'=\frac{1}{-\frac{1}{2}\log(p)}\frac{1}{p}=\frac{-2}{p\log(p)}$$
If not Can someone expand on the correct way?

A: By the chain rule we get:
$$\left(\log\left(-\frac{1}{2}\log(p)\right)\right)'=\frac{1}{-\frac{1}{2}\log(p)} \left(-\frac{1}{2} \log(p) \right)'=\frac{1}{-\frac{1}{2}\log(p)} \left(-\frac{1}{2p}\right)=\frac{1}{p\log(p)}$$
You applied the chain rule incorrectly. There you should differentiate the whole "inner" function $-\frac{1}{2} \log(p)$ and not simply $\log(p)$.


text:
Q: "An assembly specified in the application dependencies manifest was not found" using docker I am trying to dockerize an an angular aspnet core 2.2 webapi using the following dockerfile:
FROM mcr.microsoft.com/dotnet/core/sdk:2.2.105 AS build
WORKDIR /src

# Copy csproj and restore as distinct layers
COPY ["Fightplan_v1/Fightplan_v1.csproj", "Fightplan_v1/"]
COPY ["Fightplan_v1.Autogenerate/Fightplan_v1.Autogenerate.csproj", "Fightplan_v1.Autogenerate/"]
COPY ["Fightplan_v1.Autogenerate.Test/Fightplan_v1.Autogenerate.Test.csproj", "Fightplan_v1.Autogenerate.Test/"]
COPY ["Fightplan_v1.Database/Fightplan_v1.Database.csproj", "Fightplan_v1.Database/"]
COPY ["Fightplan_v1.Helpers/Fightplan_v1.Helpers.csproj", "Fightplan_v1.Helpers/"]
COPY ["Fightplan_v1.Jobs/ConvertImagestoBlob/Fightplan_v1.ConvertImagestoBlob.csproj", "Fightplan_v1.Jobs/ConvertImagestoBlob/"]
COPY ["Fightplan_v1.Models/Fightplan_v1.Models.csproj", "Fightplan_v1.Models/"]
COPY ["Fightplan_v1.Shared/Fightplan_v1.Shared.csproj", "Fightplan_v1.Shared/"]
RUN dotnet restore "Fightplan_v1/Fightplan_v1.csproj"

# Copy everything else and build
COPY . .
WORKDIR "/src/Fightplan_v1"
RUN dotnet build "Fightplan_v1.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "Fightplan_v1.csproj" -c Release -o /app

# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS runtime
WORKDIR /app
COPY --from=build /app .

EXPOSE 80
ENTRYPOINT ["dotnet", "Fightplan_v1.dll"]

The build command used is:
docker build -f .\fp.dockerfile -t test .

The build goes through fine but when I try to run it using:
docker run -p 5100:80 -it test

I get the following error:

I have tried:

*

*Adding  -r linux-x64 to the end of publish to define the runtime: RUN dotnet publish "Fightplan_v1.csproj" -c Release -o /app -r linux-x64

*Adding <PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest> to my .csproj file

None of the above fixes work unfortunately.
Since this is combined poject of an angular application and a webapi I might be missing some installations/dependencies?

A: You are copying the runtime files from wrong layer
COPY --from=build /app .

Try to change it to
COPY --from=publish /app .

Also, you probably need to separate out path in build and publish steps:
RUN dotnet build "Fightplan_v1.csproj" -c Release -o /app/build
RUN dotnet publish "Fightplan_v1.csproj" -c Release -o /app/publish

and then copy runtime files from the publish folder
COPY --from=publish /app/publish .

Edit. Basically, you need to copy publish artifacts into runtime, not build. Build will produce deps.json, which will lists all external dependencies, and during runtime this libraries are resolving using NuGet cache, if it is empty you will see an error. To copy dependencies along with project files you need to run publish.
So I assume, that theoretically dotnet build can be omitted, and is using only to discover compilation errors on early stage of docker build.


text:
Q: Triple Angle Condition Let $ABC$ be a triangle with integral side lengths such that $\angle A=3\angle B$. Find the minimum value of its perimeter.
Essentially we want sinb, sin3b, sin4b to have rational ratios (manipulate the sine law). But then we don't actually need sinb to be rational, so that's pretty mysterious. Afterwards just make them integers by multiplying by LCM of denominator.

A: Let $x = \sin\angle B$. Using the identity $\sin 3\theta = -4\sin^3 \theta + 3\sin\theta$, $\sin\angle A = -4x^3+3x$.
Then $\sin\angle C = \sin (\pi - \angle B - \angle A) = \sin 4\angle B = 4\sin\angle B\cos\angle B(1-2\sin^2 \angle B) =4x\sqrt{1-x^2}(1-2x^2) $.
By the law of sines, $\frac{a}{b} = \frac{\sin\angle A}{\sin\angle B} = -4x^2+3$, etc.
The perimeter is therefore
$$ a+b+c = 4b\left[ 1-x^2+\sqrt{1-x^2}(1-2x^2) \right]$$
We want to minimize this subject to the quantity in brackets being rational.
Note also that $0 < \angle B < \pi/4$, so $0<x<1/\sqrt{2}$.
We need $x^2$ to be rational, so let $x^2 = p/q$. Since we also need $\sqrt{1-x^2}$ to be rational, both $q$ and $q-p$ must be squares. Let $q=a^2$, and $a^2-p = b^2$, with $2p<a^2$. Substituting this all back in, we get the following optimization problem:
$$ \min\; a^3-pa+ba^2-2bp $$
subject to $a$, $b$, $p$ being positive integers, $2p<a^2$, and $a^2-p=b^2$.
The objective is cubic in $a$, so we should try to find the smallest $a$. From the constraints, we see that $a\ge 3$, and the second constraint prevents $a=3$ from being a possibility. The next possibility is $a=4$, leading to $p=7$, and $b=3$. Plugging this in gives side lengths $b$, $a=\frac{5}{4}b$, and $c=\frac{3}{8}b$. Multiplying through by 8 gives 3, 8, 10 as side lengths, for a perimeter of 21.


text:
Q: 150 TPS for 30 users with 50,000 requests in 6 hrs Suppose we have to achieve 150 TPS for 30 users with 50,000 requests in jmeter where user runs for 6hrs.
I want to hit 3 HTTP request in this scenario.
Can you please suggest how can i configure in such a way?
I have tired to create thread group where users are 25 and duration is 28,800 but i am unable to achieve above part.
I need 150 tps for 50,000 requests in 6hrs

A: *

*If you want to execute 100 000 requests in 8 hours with 25 users - you need to perform approximately 3.5 TPS. In this case use Constant Throughput Timer to limit the requests execution rate to 208.3 requests per minute

*If you want to achieve 150 TPS rate - I doubt you will be able to do this with 25 users (unless response time of your application is 0.16 ms). You might want to allocate more virtual users in order to reach 150 TPS using Concurrency Thread Group and Throughput Shaping Timer combination. However given 150 TPS and 8 hours test duration you will get 4 320 000 requests.

So double check your SLA/NFR as the requirements you listed above are mutually exclusive and cannot be put together.


text:
Q: How to efficiently construct a matrix in matlab that depends on indices In my program in matlab I have several instances where I need to create a matrix, which entries depends on its indices and perform matrix-vector operations with it. I wonder how I can implement this most efficiently.
For example, I need to speed up:
N = 1e4;
x = rand(N,1);

% Option 1
tic
I = 1:N;
J = 1:N;
S = zeros(N,N);
for i = 1:N
    for j = 1:N
        S(i,j) = (i+j)/(abs(i-j)+1);
    end
end
a = x'*S*x
fprintf('Option 1 takes %.4f sec\n',toc)
clearvars -except x N

I try to speed this up, so I have tried the following options:
% Option 2
tic
I = 1:N;
J = 1:N;
Sx = zeros(N,1);
for i = 1:N
    Srow_i = (i+J)./(abs(i-J)+1);
    Sx(i)= Srow_i*x;
end
a = x'*Sx
fprintf('Option 2 takes %.4f sec\n',toc)
clearvars -except x N

and
% Option 3
tic
I = 1:N;
J = 1:N;
S = bsxfun(@plus,I',J)./(abs(bsxfun(@minus,I',J))+1);
a = x'*S*x
fprintf('Option 3 takes %.4f sec\n',toc)
clearvars -except x N

and (thanks to one of the answers)
% options 4
tic
[I , J] = meshgrid(1:N,1:N);
S = (I+J) ./ (abs(I-J) + 1);
a = x' * S * x;
fprintf('Option 4 takes %.4f sec\n',toc)
clearvars -except x N

Otion 2 is the most efficient. Is there a faster option of doing this operation?
Update:
I have also tried the option by Abhinav:
% Option 5 using Tony's Trick
tic
i = 1:N;
j = (1:N)';
I = i(ones(N,1),:);
J = j(:,ones(N,1));
S = (I+J)./(abs(I-J)+1);
a = x'*S*x;
fprintf('Option 5 takes %.4f sec\n',toc)
clearvars -except x N

It seems that the most efficient procedure depends on the size of N. For different N I get the following output:
N = 100:
Option 1 takes 0.00233 sec
Option 2 takes 0.00276 sec
Option 3 takes 0.00183 sec
Option 4 takes 0.00145 sec
Option 5 takes 0.00185 sec

N = 10000:
Option 1 takes 3.29824 sec
Option 2 takes 0.41597 sec
Option 3 takes 0.72224 sec
Option 4 takes 1.23450 sec
Option 5 takes 1.27717 sec

So, for small N, option 2 is the slowest but it becomes the most efficient for larger N. Maybe because of memory? Could somebody explain this?

A: You can create indices using meshgrid and no need to loop:
N = 1e4;
[I , J] = meshgrid(1:N,1:N);
x = rand(N,1);
S = (I+J) ./ (abs(I-J) + 1);
a = x' * S * x;

Update:
Since @Optimist shown that performance of this code is less than Option2 and Option3 I decided to slightly improve Option2:
N = 1e4;
x = rand(N,1);
Sx = zeros(N,1);
for i = 1:N
    Srow_i = (i+1:i+N)./[i:-1:2,1:N-i+1] ;
    Sx(i)= Srow_i*x;
end
a = x'*Sx;

A: You should try using the Tony's trick to do vector stacking/tiling in Matlab the fastest way. I have answered a similar question here. Here is the Tony's Trick option.
% Option using Tony's Trick
tic
i = 1:N;
j = (1:N)';
I = i(ones(N,1),:);
J = j(:,ones(N,1));
S = (I+J)./(abs(I-J)+1);

a = x'*S*x
fprintf('Option 1 takes %.4f sec\n',toc)

Edit 1: I ran a few tests and found the following. Up to N=1000, the Tony's trick option is slightly faster than the Option 2. Beyond that, Option 2 again catches up and becomes faster.
Possible Reason :
This should be so because, up until the size of the array could fit in the cache, the fully vectorized code (Tony's Trick option) is faster BUT as soon as the array sizes grow (N>1000), it spills into memory caches away from the CPU and then Matlab uses some internal optimization to breakdown the Tony's Trick code into piecemeal code so that it no-longer enjoys the benefit of complete vectorization.


text:
Q: The use the special ? variable Netlogo what is the Alternative? The use of the special ? variable which takes the values of each of the items in the list as we iterate over the list.
what is the alternative use in the new version of NetLogo software???

A: The new arrow syntax was introduced with NetLogo 6. Instead of just referring things as ?, this allows you to actually name your variables:
foreach [ 0 1 2 3 ] [ x ->
  print x
]

This also allows you to nest these types of blocks and still refer to all the values:
foreach [ 0 1 2 3 ] [ x ->
  foreach [ 4 5 6 7 ] [ y ->
    print x + y
  ]
]

Previously, you would have to do this with, for instance, let x ?. With primitives like map and filter, you couldn't do this at all, so it's a big improvement. Note that, if you have more than one variable, you have to wrap the arguments with []:
(foreach [0 1 2 3] [4 5 6 7] [ [x y] ->
  print x + y
])


text:
Q: Themes and Languages Resource Dictionary I was using the standard approach to themes in my WPF application and using a dynamicresource to change it during runtime.
This worked.
Now I have added language support (english, spanish) but when this is set, the dynamic resource no longer works for the theme. If I set the control to a static resource the theme works but then I lose the affect of changing it during runtime.
Heres the code that was added for language support but I'm confused as to why it stopped working the way I want it to.
App.xaml.cs calls this:
    SetLanguage(LocalePath(CultureInfo.CurrentCulture.Name));
/// <summary>
    /// Get the locale path for the resource dictionary.
    /// </summary>
    /// <param name="language"></param>
    /// <returns></returns>
    private string LocalePath(string language)
    {
        string file = language + ".xaml";

        return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Utilities\Resources\Locales\", file);
    }

    /// <summary>
    /// Set the language using the defined resource file.
    /// </summary>
    /// <param name="file"></param>
    private void SetLanguage(string file)
    {
        if (File.Exists(file))
        {
            var languageDictionary = new ResourceDictionary();
            languageDictionary.Source = new Uri(file);

            int dictionaryID = -1;

            for (int i = 0; i < Resources.MergedDictionaries.Count; i++)
            {
                var mergedDictionary = Resources.MergedDictionaries[i];

                if (mergedDictionary.Contains("ResourceDictionaryName"))
                {
                    if (mergedDictionary["ResourceDictionaryName"].ToString().StartsWith("Locale-"))
                    {
                        dictionaryID = i;
                        break;
                    }
                }
            }

            if (dictionaryID == -1)
            {
                Resources.MergedDictionaries.Add(languageDictionary);
            }
            else
            {
                Resources.MergedDictionaries[dictionaryID] = languageDictionary;
            }
        }
    }

A: I had 5 other keys in the language resource dictionaries with the same key as the theme being used. Changed the key name and it works again.


text:
Q: Using guid id in Entity Framework Web Api and DbContext Find not working I have a class that has Guid id.
public class Product {
    public Guid Id {get;set;}
}

and I am using this context in my web api application.
public class ProductController : ApiController
{
        readonly ProductContext database = new ProductContext();

        public IHttpActionResult Get(string id){
              database.find(id); // does not find.
        }
}

if I change action parameter as guid it finds.
        public IHttpActionResult Get(Guid id){
              database.find(id); // finds.
        }

But if a user sends invalid id parameter, applicaiton throws exception.

The parameters dictionary contains a null entry for parameter 'id' of
  non-nullable type 'System.Guid' for method
  'System.Web.Http.IHttpActionResult Get(System.Guid)

Should I make all of id properties as string? Which way is best?

A: You could try to use a Guid?
public IHttpActionResult Get(Guid? id)
{
    if (id.HasValue)
    {
        database.find(id.Value); // finds.
    }
    else
    {
        // invalid ID
    }
}

A: cast string to Guid.
 public class ProductController : ApiController
    {
            readonly ProductContext database = new ProductContext();

            public IHttpActionResult Get(string id){

                  database.find(new Guid(id));
            }
    }


text:
Q: Oracle Listener keeps crashing and getting unresponsive We have a restful web-service that uses hibernate and Glassfish to access an Oracle database. However, after a few simple transactions (a few simple queries and retrieving some data), the Oracle Listener becomes unresponsive with the following error:
ORA-12519, TNS:no appropriate service handler found
org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:91)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:79)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:363)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:122)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:125)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1308)
at data.CommonUnitOfWork.<init>(CommonUnitOfWork.java:29)
at data.UnitOfWorkFactory.createCommonUnitOfWork(UnitOfWorkFactory.java:14)
at controller.UserController.getUser(UserController.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)

Caused by: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:389)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:454)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:802)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:190)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:360)
... 51 more

And the only solution to get the service running again is by restarting the Listener.
Thank you for your help in advance.
EDIT:
The Oracle version is 11g, the restful web-service is in java. The listener becomes unresponsive after a few minutes of work which consists of running a small number of queries (like 4 or 5) to retrieve less than 5 rows of a table in the database (which consists of about 10 columns); the work is not that heavy at all.
The database consists of about 20 tables. In some of the queries, joins are being made using hibernate's criteria between 2 or 3 tables, which are not that complicated and shouldn't be considered as "heavy loads".
EDIT 2:
The model uses some kind of a UnitOfWorkFactory to implement the repository pattern. For each request (e.g. creating a new object, editing an existing object or searching) the model creates a unitOfWork, in which a hibernate session will be created, do the job and then close the session.

A: Be sure to use a connection pool. This prevents a lot of unneeded and very expensive re-connects to the database. For an example check here and page down to "First create a JDBC Connection Pool" Creating connections to the database is a very time consuming task that greatly reduces your overall systems performance. This is because it is a serialization process.
By using the connection pool, you make sure that there are always sessions available for your application to use, even when the listener itself is down for a short period.


text:
Q: Puppeteer opens about:blank page sometimes I have been experiencing this issue from a long time now. I have a web scraper on a Windows VM and I have it set to run every few hours. It works most of the time but a lot of times Puppeteer just opens this page  and not the site or page I want to open.
Why does that happen and what can be the fix for this?

A simple reproduction for this issue can be this code
import puppeteer from 'puppeteer'
import { scheduleJob } from 'node-schedule';

async function run() {
  const browser = await puppeteer.launch({
    headless: false,
    executablePath: chromePath,
    defaultViewport: null,
    timeout: 0,
    args: ['--no-sandbox', '--start-maximized'],
  });
  const page = await browser.newPage();

  await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, 'webdriver', {
      get: () => false,
    });
  });

  await page.goto('https://aliexpress.com', {
    waitUntil: 'networkidle0',
    timeout: 0,
  });
}

run();
scheduleJob('scrape aliexpress', `0 */${hours} * * *`, run);


text:
Q: detect html audio start download I would like to know when the audio tag starts downloading so that I can throw up an overlay. Then remove it when it stops, but this does not work in chrome
audio.oncanplay = () => {
  loading = false;
};
audio.onloadstart = () => {
  loading = true;
};

loading will be true as soon as the page loads.
Is there an event for started downloading, and finished downloading? I need both not just the finished.

A: I figured it out. You want to use the waiting event. As seen in my fiddle.
let audio = document.getElementById('ad')
let message = document.getElementById('mes')

audio.oncanplay = () => {
  message.append ( "done\n")
};
audio.onwaiting = () => {
  message.append ( "load\n")
};
message.append ("start\n")

<audio id='ad' controls src='https://html.com/wp-content/uploads/flamingos.mp3' preload="none"></audio>

The waiting will fire whenever the audio tag is loading, and canplay will fire whenever the audio tag is again capable of playing.
https://jsfiddle.net/2pdn1k5f/1/


text:
Q: Application.DoEvents, when it's necessary and when it's not? What is the necessity of using Application.DoEvents and when we should use it?

A: Windows maintains a queue to hold various events like click, resize, close, etc. While a control is responding to an event, all other events are held back in the queue. So if your application is taking unduly long to process a button-click, rest of the application would appear to freeze. Consequently it is possible that your application appears unresponsive while it is doing some heavy processing in response to an event. While you should ideally do heavy processing in an asynchronous manner to ensure that the UI doesn't freeze, a quick and easy solution is to just call Application.DoEvents() periodically to allow pending events to be sent to your application.
For good windows application, end user doesn't like when any form of application are freezing out while performing larger/heavyweight operation. User always wants application run smoothly and in responsive manner rather than freezing UI. But after googling i found that Application.DoEvents() is not a good practice to use in application more frequently so instead this events it's better to use BackGround Worker Thread for performing long running task without freezing windows.
You can get better idea if you practically look it. Just copy following code and check application with and without putting Application.DoEvents().
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For i As Integer = 0 To 1000
            System.Threading.Thread.Sleep(100)
            ListBox1.Items.Add(i.ToString())
            Application.DoEvents()
        Next
    End Sub

A: Application.DoEvents is usually used to make sure that events get handled periodicaly when you're performing some long-running operation on the UI thread.
A better solution is just not to do that. Perform long-running operations on separate threads, marshalling to the UI thread (either using Control.BeginInvoke/Invoke or with BackgroundWorker) when you need to update the UI.
Application.DoEvents introduces the possibility of re-entrancy, which can lead to very hard-to-understand bugs.

A: Imho you should more less never use it, as you might end up with very unexpected behavior.
Just generated code is ok. Things like you are executing again the event handler you are currently in,because the user pressed a key twice etc etc.
If you want to refresh a control to display the current process you should explicitly call .Update on that control in instead of calling Application.DoEvents.


text: Q: ffmpeg - Redownload missing fragments to fix downloaded stream I have dowloaded an H.264 video stream using ffmpeg -i <URL> -c copy <name>.mp4 but ffmpeg reports that it has skipped some fragments. Since the stream is still online (with, I suppose, all the fragments), is it possible to fix the downloaded file by fetching the missing fragments and adding them to it?


text:
Q: How do I activate button click with the Enter key in Tkinter? I'm progressing in the creation of a translation app. The "Translate" button works fine, but I want to be able to press the ENTER key to activate the translate button as well. Please, how do I do this? (Thanks for the help you provided on my previous question) Bellow is the code:
from tkinter import *
import tkinter. messagebox
root=Tk()
root.geometry('250x250')
root.title("Meta' Translator")
root.configure(background="#35424a")

#Entry widget object
textin = StringVar()

def clk():
    entered = ent.get()
    output.delete(0.0,END)
    try:
    textin = exlist[entered]
    except:
        textin = 'Word not found'
    output.insert(0.0,textin)

#heading
lab0=Label(root,text='Translate English Words to Meta\'',bg="#35424a",fg="silver",font=('none 11
bold'))
lab0.place(x=0,y=2)

#Entry field
ent=Entry(root,width=15,font=('Times 18'),textvar=textin,bg='white')
ent.place(x=30,y=30)

#focus on entry widget
ent.focus()

#Search button
but=Button(root,padx=1,pady=1,text='Translate',command=clk,bg='powder blue',font=('none 18
bold'))
but.place(x=60,y=90)

#output field
output=Text(root,width=15,height=1,font=('Times 18'),fg="black")
output.place(x=30,y=170)

#prevent sizing of window
root.resizable(False,False)

#Dictionary
exlist={
    "abdomen":"fɨbûm", "abdomens":"tɨbûm",
    "adam's apple":"ɨ̀fɨ̀g ədɔ'",
    "ankle":"ɨgúm ǝwù", "ankles":"tɨgúm rəwù",
    "arm":"ǝbɔ́", "arms":"ɨbɔ́",
    "armpit":"ǝtón rɨ̀ghá"
    }

root.mainloop()

A: Bind the return key to a function and from that function call the clk function.
from tkinter import *
import tkinter. messagebox

root=Tk()
root.geometry('250x250')
root.title("Meta' Translator")
root.configure(background="#35424a")

#Entry widget object
textin = StringVar()

def returnPressed(event):
  clk()

def clk():
    entered = ent.get()
    output.delete(0.0,END)
    try:
      textin = exlist[entered]
    except:
      textin = 'Word not found'
    output.insert(0.0,textin)

#heading
lab0=Label(root,text='Translate English Words to Meta\'',bg="#35424a",fg="silver",font=('none 11 bold'))
lab0.place(x=0,y=2)

#Entry field
ent=Entry(root,width=15,font=('Times 18'),textvar=textin,bg='white')
ent.place(x=30,y=30)

#focus on entry widget
ent.focus()

#Search button
but=Button(root,padx=1,pady=1,text='Translate',command=clk,bg='powder blue',font=('none 18 bold'))
but.place(x=60,y=90)

root.bind('<Return>', returnPressed)

#output field
output=Text(root,width=15,height=1,font=('Times 18'),fg="black")
output.place(x=30,y=170)

#prevent sizing of window
root.resizable(False,False)

#Dictionary
exlist={
    "abdomen":"fɨbûm", "abdomens":"tɨbûm",
    "adam's apple":"ɨ̀fɨ̀g ədɔ'",
    "ankle":"ɨgúm ǝwù", "ankles":"tɨgúm rəwù",
    "arm":"ǝbɔ́", "arms":"ɨbɔ́",
    "armpit":"ǝtón rɨ̀ghá"
    }

root.mainloop()


text:
Q: how to embed vlc media player into my c# windows form app? I know how to use windows media player in my app but it doesn't work for some files.I have search the web but found nothing that could be understood about using vlc in form.Could sb help me step by step to do this please?Thanks

A: http://sourceforge.net/projects/libvlcnet/
http://forum.videolan.org/viewtopic.php?f=32&t=58438
NET wrapper for VLC media player. This library allows you to use libvlc from .NET code without dll imports. Simple and easy to use for playing, streaming, transcoding of video streams. Visit the home page for more info.


text:
Q: CPack / CMake: Different installation prefixes per CPACK_GENERATOR How can I specify different installation prefixes for the different CPACK_GENERATORs?
For example:

*

*the DEB package should be installed to /opt/project

*the TGZ archive should consist only of the project directory

From the documentation I understood that I would have to use the CPACK_PROJECT_CONFIG_FILE variable. Using that, it should be possible to achieve the desired goal. However, it did not work for me.
This is my CPack configuration:
set(CPACK_GENERATOR "DEB;TGZ")
set(CPACK_PROJECT_CONFIG_FILE ${CMAKE_SOURCE_DIR}/cmake/package.linux.txt)

And this is my ${CMAKE_SOURCE_DIR}/cmake/package.linux.txt file:
IF (CPACK_GENERATOR MATCHES "DEB")
    set(CPACK_NATIVE_INSTALL_DIRECTORY "/opt")
    set(CMAKE_INSTALL_PREFIX "/opt")
    set(CPACK_PACKAGING_INSTALL_PREFIX "/opt")
    set(CPACK_INSTALL_DIRECTORY "/opt")
ELSEIF(CPACK_GENERATOR MATCHES "TGZ")
    set(CPACK_NATIVE_INSTALL_DIRECTORY "")
    set(CMAKE_INSTALL_PREFIX "")
    set(CPACK_PACKAGING_INSTALL_PREFIX "")
    set(CPACK_INSTALL_DIRECTORY "")
ENDIF()

I have made sure that all files get parsed using MESSAGE() directives, but the prefix of my packages is always /usr/local.

A: Finally, I found out what was wrong. I had the CPACK_SET_DESTDIR flag set. This makes CPACK append usr/local to the directory containing the binaries of the compilation. After removing the corresponding SET() directive, everything worked like a charm.
For the record I will provide you with my minimal working example.
CMakeLists.txt:
cmake_minimum_required(VERSION 3.2)
project(stripped-down C)

add_executable(main main.c)

install(TARGETS main
    RUNTIME DESTINATION bin
    )

set(CPACK_GENERATOR "DEB;TGZ")
set(CPACK_PROJECT_CONFIG_FILE ${CMAKE_SOURCE_DIR}/package.txt)

set(CPACK_PACKAGE_CONTACT "Some One <some.one@somewhere.com>")

include(CPack)

${CMAKE_SOURCE_DIR}/package.txt:
IF (CPACK_GENERATOR MATCHES "DEB")
    set(CPACK_PACKAGING_INSTALL_PREFIX "/opt")
ELSEIF(CPACK_GENERATOR MATCHES "TGZ")
    set(CPACK_PACKAGING_INSTALL_PREFIX "")
ENDIF()


text:
Q: 'require' in a subdirective depending on parent directive in AngularJS I am trying to construct a sub directive which will later be used in multiple directives.
These parent directives have the same controller that provides some methods with which I want to update things in the scope of these directives :
(may use different controllers later but with these same common methods)
myApp
.controller('SomeCommonController', function() {
    this.someMethod = function(data) {
        // do something for updating scope variables
    }
        ...
    return this;
})
.directive('myDir1', function() {
    return {
        controller: 'SomeCommonController',
        template : '<sub-dir ng-repeat="sth in aList" data="sth"></sub-dir>',
           ...
    }
})
.directive('myDir2', function() {
    return {
        controller: 'SomeCommonController',
        template : 'Something Different with calling <sub-dir data="otherData"></sub-dir>',
           ...
    }
})
.directive('subDir', function() {
    return {
        scope: { data : "=" }
        require: "^something",  // parent directive
        template: '<button ng-click="someMethod(data);"></button>'
        link: function(scope, elem, attrs, parentDirectiveCtrl) {
            scope.someMethod = function(data) {
                parentDirectiveCtrl.someMethod(data);
            };
        },
           ...
    }
})

Is there a way to require only the controller of the caller directive? Or is there a better way to achieve the same behavior?

A: I don't think so there is any way to find who is parent controller dynamically (I mean to say parent directive)
I'd suggest you to use require with array that means mention your require field in array, like here require would require: ['?^^myDir1', '?^^myDire2'] then inside link function 4th parameter is of controller, if you ctrl[0] you could get controller of myDir1 & if you do ctrl[1] then you will get controller of myDir2

You must use ?^^ because there could be one of them would not
  present in parent of directive

.directive('subDir', function() {
    return {
        scope: { data: "=" },
        require: ['?^^myDir1', '?^^myDir2'],  // parent directive
        template: '<button ng-click="someMethod(data);"></button>'
        link: function(scope, elem, attrs, parentDirectiveCtrl) {
            if(parentDirectiveCtrl[0])
              console.log('Parent controller is myDir1')
            if(parentDirectiveCtrl[1])
              console.log('Parent controller is myDir2')
            //whenever you want to call method of parent directive
            //then you should use either parentDirectiveCtrl[0] for myDir1
            //or parentDirectiveCtrl[1] for myDir2
            scope.someMethod = function(data) {
                parentDirectiveCtrl[0].someMethod(data);
            };
        },
           ...
    }
})

A: require is there to access another directive's controller (and thus "API"), and so you need to specify explicitly which directive you want. Otherwise, how would Angular know - there could be N number of "parent" directives. For example:
<parent ng-switch="abc" foo="123" bar>
  <child></child>
</parent>

Which of the directives parent, ngSwitch, foo, bar you would expect Angular to return?
It is a very rare case that you need to determine dynamically what the hosting directive is, even if you know that the controllers have the same "API". And, clearly, require was not designed for that.
If you have a well-defined set of potential parent directives, then I second @pankajparkar's approach with optionally require-ing them all:
require: ["?^^parent1", "?^^parent2", ],
link: function(scope, element, attrs, ctrls){
   var parentCtrl = ctrls[0] || ctrls[1]; // etc...
}

If not, you could get the parent, but you would have to do some manual work. Suppose you know that a parent will always be the immediate containing element and the element tag (rather than an attribute) is the directive. Then, you could get that directive's controller like so:
link: function(scope, element){
   var parentCtrlName = element.parent().prop("tagName").toLowerCase();
   var parentCtrl = element.parent().controller(parentCtrlName);

   if (parentCtrl){
     //
   }
}

A: how about having a container parent directive that can contain either dir1 or dir2; then dir1, dir2 and subDir will communicate through the container directive, granted when you use the set of directives you need to wrap them in the container directive but it buys you flexibility, it will let you add dir3 without modifying the structure
myApp
.controller('SomeCommonController', function() {
    this.someMethod = function(data) {
        // do something for updating scope variables
    }
    ...
    return this;
})
.directive('container', function() {
    return {
        controller: 'SomeCommonController',
        template : '<container></container>',
           ...
    }
})
.directive('myDir1', function() {
    return {
        require: '^container',
        link: function(scope, elem, attrs, parentDirectiveCtrl) {
            scope.someMethod = function(data) {
                parentDirectiveCtrl.someMethod(data);
            };
        },
        template : '<sub-dir ng-repeat="sth in aList" data="sth"></sub-dir>',
           ...
    }
})
.directive('myDir2', function() {
    return {
        ink: function(scope, elem, attrs, parentDirectiveCtrl) {
            scope.someMethod = function(data) {
                parentDirectiveCtrl.someMethod(data);
            };
        },
        template : 'Something Different with calling <sub-dir data="otherData"></sub-dir>',
           ...
    }
})
.directive('subDir', function() {
    return {
        scope: { data : "=" }
        require: '^^container',  // parent directive
        template: '<button ng-click="someMethod(data);"></button>'
        link: function(scope, elem, attrs, parentDirectiveCtrl) {
            scope.someMethod = function(data) {
                parentDirectiveCtrl.someMethod(data);
            };
        },
           ...
    }
})


text:
Q: Overriding Ace Editor defaults through CoffeeScript I have an Ace Text Editor enabled input field. I am attempting to execute an action through the keyboard shortcut combination of Shift+Enter, which is handled in my CoffeeScript file. Unfortunately, there seems to be a bug that Shift+Enter is automatically entering a newline character (presumably because defaults from Ace are not being overwritten). I would like the CoffeeScript keyboard shortcut to take precedence. Can someone point me in the right direction of how I could approach this?

A: You can call event.preventDefault() and event.stopPropagation() from coffeescript handler to not allow the event to reach ace or use handler in ace like: editor.commands.bindKey("Shift-Enter", function() {...})


text:
Q: c# filter a two dimensional double array with another two dimensional double array Is there any efficient way to filter a two dimensional double array with another two dimensional double array in c#?
For example, given two arrays as
    double[,] unfiltered = new double[ , ] {{1, 1, 2, 3}, {2, 4, 5, 6}, {3, 7, 8, 9}};
    double[,] filter = new double[ , ] {{1, 1, 2, 3}, {2, 4, 5, 6}};

At the end, I would like to have an array like,
filtered = {{3, 7, 8, 9}},
filtered by the first column of each row.
Thanks a lot in advance.

A: you're sure you want to use double for such numbers ?.
if possible use int, they calculate faster and require less memory.
Your filtering on whole rows of data it seams, looks like some graphic function.
Perhaps you could put them in a dictionary and then remove the indexed rows by row ID. Or use Array.Copy to copy from a certain index into a new array.


text:
Q: increase and creating empty image boxs , till the number is even Well actually i don't know how to ask this, I have an object which stores the image path from database and it was shown like a category on my page, each role having 4 images.
It looks great if the object length is an even number, like 4, but in case of odd numbers it looks weird, so I decided to add an empty image box to it when the object length is odd.
But how do I start? I have no idea, something like this:
box = 7 now (which is a odd);

var checkCategoryNumber = function (box){
  if (box.length % 2 == 0) {
    // do noting
    alert("even");
  }
  else {
    // increase and create an empty image box, till the number is even.
    alert("odd");
  }
}

Which will create one empty image box to 8 and it stop.
Hope you understand what I mean, please let me know if the question is confusing, thanks.

A: You can just check if box is odd number and if it is add empty box.

var checkCategoryNumber = function(box) {
  for (var i = 0; i < box; i++) {
    $('body').append(i + 1 + '. Box
')
  }
  if (box % 2 != 0) $('body').append(box + 1 + '. Empty box

')
}
checkCategoryNumber(7)
checkCategoryNumber(6)


text:
Q: Variable does not exist: MailingCountryCode When I try to deploy to a scratch org a class that references the field MailingCountryCode on the object Contact, I receive the following error message :
Variable does not exist: MailingCountryCode (79:110)

In the dev org, I have Standard Countries and Territories for Address Picklists enabled so I guess that's why I'm not seeing this issue there, but from the documentation found here, I understand that the field MailingCountryCode should be available even if that feature is not enabled :

The ISO country code for the address. For example, this field is known as MailingCountryCode on Contact. CountryCode is always available on compound address fields, whether or not state and country/territory picklists are enabled in your organization.

If that's not the case, how can I set this feature as a dependency and how do I enable it from SFDX cli ?
Thank you for your help.


text:
Q: spark mllib apply function to all the elements of a rowMatrix I have a rowMatrix xw
scala> xw
res109: org.apache.spark.mllib.linalg.distributed.RowMatrix = org.apache.spark.mllib.linalg.distributed.RowMatrix@8e74950

and I would like to apply a function to each of its elements:
f(x)=exp(-x*x)
The type of element of the matrix can be visualized as:
scala> xw.rows.first

res110: org.apache.spark.mllib.linalg.Vector = [0.008930720313311474,0.017169380001300985,-0.013414238595719104,0.02239106636801034,0.023009502628798143,0.02891937604244297,0.03378470969100948,0.03644030110678057,0.0031586143217048825,0.011230244437457062,0.00477455053405408,0.020251682490519785,-0.005429788421130285,0.011578489275815267,0.0019301805575977788,0.022513736483645713,0.009475039307158668,0.019457912132044935,0.019209006632742498,-0.029811133879879596]

My main problem is that I can not use map on vector
scala> xw.rows.map(row => row.map(e => breeze.numerics.exp(e)))
<console>:44: error: value map is not a member of org.apache.spark.mllib.linalg.Vector
              xw.rows.map(row => row.map(e => breeze.numerics.exp(e)))
                                     ^

scala>

How can I solve?

A: This is assuming you know you've actually got a DenseVector (which seems to be the case).  You can call toArray on the vector, which has a map, and then convert back to a DenseVector with Vectors.dense:
xw.rows.map{row => Vectors.dense(row.toArray.map{e => breeze.numerics.exp(e)})}

You could do this on a SparseVector as well; it will be mathematically correct, but converting to an array could be extremely inefficient.  Another option would be to call row.copy and then use foreachActive, which would make sense for both dense and sparse vectors.  But copy may not be implemented for the specific Vector class you are using, and also if you don't know the type of vector, you can't mutate the data.  If you really need to support sparse & dense vectors, I'd do something like:
xw.rows.map{
  case denseVec: DenseVector =>
    Vectors.dense(denseVec.toArray.map{e => breeze.numerics.exp(e)})}
  case sparseVec: SparseVector =>
    //we only need to update values of the sparse vector -- the indices remain the same
    val newValues: Array[Double] = sparseVec.values.map{e => breeze.numerics.exp(e)}
    Vectors.sparse(sparseVec.size, sparseVec.indices, newValues)
}


text:
Q: Compiling the icu sqlite extension statically linked to icu I want to compile the icu sqlite extension statically linked to icu.
This is what I've tried, maybe the mistake is obvious to you.

> cd icu/source
> ./runConfigureIcu Linux --enable-static --with-packaging-format=archive
...
> make

> cd ../../icu-sqlite
> gcc -o libSqliteIcu.so -shared icu.c -I../icu/source/common
      -I../icu/source/i18n -L ../icu/source/lib -lsicuuc -lsicui18n -lsicudata
...
> sqlite3
> .load "libSqliteIcu.so"
Undefined symbol utf8_countTrailBytes

Files
icu sqlite extension
Download icu.c from sqlite.org
ICU 4.2.1
Download ICU4C from icu-project.org
My Requirements

*

*Runs on Linux & Windows

*Only one file that I have to distribute: libSqliteIcu.so.

Any idea what else I can try?
Documentation

*

*Sqlite ICU extension's readme

*ICU's readme

A: This command line worked for me on Linux:
g++ -shared --language c  -o libSqliteIcu.so icu.c  -I../icu/source/common -I../icu/source/i18n -lpthread -lm   -L../icu/source/lib -lsicui18n -lsicuuc -lsicudata  -lpthread -lm

Notice the ordering of the library files, and the use of g++  to make sure the c++ runtime is referenced even though we're compiling a C file.
NB.
I used the output of icu-config --prefix=../icu/source --ldflags.

A: I ran into the same problem as you. You can edit icu\include\utf8.h and replace following lines

          #ifdef U_UTF8_IMPL
          U_EXPORT const uint8_t
          #elif defined(U_STATIC_IMPLEMENTATION) || defined(U_COMMON_IMPLEMENTATION)
          U_CFUNC const uint8_t
          #else
          U_CFUNC U_IMPORT const uint8_t /* U_IMPORT2? */ /*U_IMPORT*/
          #endif
          utf8_countTrailBytes[256];

with

              const uint8_t countTrailBytes[256];

This should do the trick.


text:
Q: Degree of the determinant of a matrix
Given a matrix $A\in C^{n\times n}$, the characteristic polynomial of
  $A$, $P_A$, is a polynomial of degree $n$.

By the definition of determinants, $P_A$ must be a polynomial. However, I don't completely understand how its degree cannot be larger than $n$.

A: To compute the determinant of a matrix, one formula consists of considering an alternate sum of products of entries, where you take the entries $n$ at a time, one in each row and one in each column.
See this question.
Because of the condition "no more than $n$ entries at a time", you can already see that the degree is no more than $n$, since each entry is a polynomial of degree at most $1$.
Moreover, there is exactly one choice that will achieve a degree equal to $n$, that is by taking all the diagonal elements. This choice gives you $(-X)^n$, and because all other terms will be of lower degree, this $X^n$ will never be cancelled.


text:
Q: Building year to date aggregations using SQL I need some help with building a monthly aggregation using only SQL.
Imagine the following table:
TranID  DateCode    Account Value
   1    20140101        1   5
   2    20140106        1   -3
   3    20140207        1   6
   4    20140409        1   3
   5    20140103        2   3
   6    20140215        2   7
   7    20140519        2   6

There are two accounts that have transactions on various dates. I would like to write code that gives me this result assuming we are in July:
MonthID     Account YTD
20140101        1   2
20140201        1   8
20140301        1   8
20140401        1   11
20140501        1   11
20140601        1   11
20140701        1   11
20140101        2   3
20140201        2   10
20140301        2   10
20140401        2   10
20140501        2   16
20140601        2   16
20140701        2   16

I'm thinking I should be able convert the dates to MonthCode using
DATEADD(day, -DAY(DateCode) + 1, DateCode) AS MonthCode

I'm thinking I should be able to solve this somehow by joining the table to itself but I don't really get the numbers right. Also I need to somehow get the months without transactions in as well..
Any and all help will be greatly appreciated!
Code to generate the mock data:
Create table #Tran(
TranID int identity(1,1),
DateCode Date,
AccountCode varchar(50),
Value int
);

insert into #Tran (DateCode, AccountCode, Value)
values ('20140101', '1', 5),
('20140106', '1', -3),
('20140201', '1', 6),
('20140401', '1', 3),
('20140101', '2', 3),
('20140201', '2', 7),
('20140501', '2', 6);

A: For SQL Server 2012, given this sample data:
CREATE TABLE #t(TranID INT, DateCode DATE, Account INT, Value INT);
CREATE CLUSTERED INDEX x ON #t(Account, DateCode);

INSERT #t VALUES(1,'20140101',1,5 ),(2,'20140106',1,-3),(3,'20140207',1,6 ),
(4,'20140409',1,3 ),(5,'20140103',2,3 ),(6,'20140215',2,7 ),(7,'20140519',2,6 );

I would use this query (imagine the first line as stored procedure parameters):
DECLARE @year INT = 2014, @cutoff DATE = NULL; -- just state the year

-- and optionally an explicit cutoff date (leave NULL for today)
SET @cutoff = '20140731';

DECLARE @startdate DATE = DATEADD(YEAR, @year-1900, 0);

;WITH accounts(a) AS
(
  SELECT DISTINCT Account FROM #t
    WHERE DateCode >= @startdate
    AND DateCode < DATEADD(YEAR, 1, @startdate)
),
months(m) AS
(
  SELECT TOP (12) DATEADD(MONTH, ROW_NUMBER() OVER
      (ORDER BY s.[object_id])-1, @startdate)
    FROM sys.all_objects AS s
),
s AS
(
  SELECT a.a, m.m, v = COALESCE(SUM(t.Value),0)
  FROM accounts AS a
  CROSS APPLY months AS m
  LEFT OUTER JOIN #t AS t
    ON t.DateCode >= m.m
    AND t.DateCode < DATEADD(MONTH, 1, m.m)
    AND t.Account = a.a
  WHERE m.m < COALESCE(@cutoff, SYSDATETIME())
  GROUP BY a.a, m.m
)
SELECT
  MonthID = m,
  Account = a,
  YTD = SUM(v) OVER(PARTITION BY a ORDER BY m ROWS UNBOUNDED PRECEDING)
FROM s
ORDER BY a,m;

If you are using a version older than SQL Server 2012, then you may want to try some of the alternative approaches here:

*

*Best approaches for grouped running totals

A: First you will need a table that has all of the months you may need in it which I'll call MonthValue (20140101, 20140201, etc..)
Your query will look like this:
SELECT MonthValue.DateCode, #Tran.AccountID,
  (SELECT Sum(Value) FROM #Tran as sub
   WHERE sub.AccountID = #Tran.AccountID
    AND sub.DateCode BETWEEN DATEADD(day, -DAY(MonthValue.DateCode) + 1, DateCode) AND MonthValue.DateCode) AS YTD
FROM MonthValue LEFT OUTER Join #Tran ON MonthValue.DateCode = #Tran.DateCode
GROUP BY MonthValue.DateCode, #Tran.AccountID

I didn't test it, but it should at least get you close to what you need.

A: WITH TestData AS (
SELECT
    DATEADD(DAY,(-1*DATEPART(DAY,CONVERT(DATETIME,DateCode)))+1,CONVERT(DATETIME,DateCode)) DateCode,
    AccountCode,
    Value
FROM (
    VALUES ('20140101', '1', 5),
    ('20140106', '1', -3),
    ('20140201', '1', 6),
    ('20140401', '1', 3),
    ('20140101', '2', 3),
    ('20140201', '2', 7),
    ('20140501', '2', 6)
) AS T (DateCode, AccountCode, Value)
)
SELECT DISTINCT
    TD1.DateCode, TD1.AccountCode,
    (SELECT SUM(TD2.Value) Total
     FROM TestData TD2
     WHERE TD2.AccountCode = TD1.AccountCode AND TD2.DateCode <= TD1.DateCode) Total
FROM TestData TD1
ORDER BY TD1.AccountCode, TD1.DateCode;

You have to find a way to group the dates into the month of the year, and then perform the calculation such as the above query.