text:
Q: Django internationalization doesn't work in my project I read the documentation, read some blogs and started applying internationalization in my project, but it doesn't work. Probably something is going wrong. Please take a look what is it that I am doing wrong.
I am a windows user, so I started installing gettext versions both shared and static from this link.
then I made following changes in settings.py:
LANGUAGE_CODE = 'fr'

MIDDLEWARE = [
    "django.middleware.locale.LocaleMiddleware",
    ...
]

LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale')
]

I already set the language code to French language. Then in my template namely index.html I added following code:
{% load i18n %}

<!-- within block content -->
{% trans "Hi" %}

Now that everything is set I run following code in console:
django-admin makemessages -l fr

I received this message:
UnicodeDecodeError: skipped file requirements.txt in . (reason: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte)
processing locale fr

I have no idea if above stated error has anything to do with translating the text of the template. Anyway, then in django.po within locale directory I translated that text of template to french as following:
#: .\templates\index.html:29
msgid "Hi"
msgstr "Salut"

and run django-admin compilemessages, but when I run it the text is not translated. I don't know why? I followed every step for this basic setup.
Thank you for time and reading.
edit: This is the app structure of my project. Apologies that I don't know other way other than taking its screenshot. The translation content is in index.html

A: Having a similar project structure, it worked for me set LOCALE_PATH to
LOCALE_PATH = (os.path.join(PROJECT_DIR, "locale"),)

and put my locale directory into portfolio/portfolio directory.


text:
Q: Is it possible to link a Range and a Numerical HTML input? Is there a way to link the values of a <input type="range"> and an <input type="number">?
I would like to make changes to either the slider or to the numerical input and have both fields be updated. For some reason I have only been able to get an undefined value from the range element as of yet.
Here is my current JavaScript and HTML for this part of the document:

function updateTextInput1(val) {
  alert(val);
  document.getElementById('num1').value = val;
}
<input class="inputRange" type="range" min="0" max="100" onchange="updateTextInput1(this.val)" />
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

A: The error is: this.val instead of this.value

function updateTextInput1(val) {
  alert(val);
  document.getElementById('num1').value = val;
}
<input class="inputRange" type="range" min="0" max="100" onchange="updateTextInput1(this.value)" />
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

A: To display everytime the range or input text is changing you can use oninput and onchange on the input range, and also onkeypress and onchange on the input type text :

function updateTextInput1(val) {
  val = val > 100 ? 100 : val;
  val = val < 0 ? 0 : val;
  document.getElementById('range').value = val;
  document.getElementById('num1').value = val;
}
    <input class="inputRange" id="range" type="range" min="0" max="100" oninput="updateTextInput1(this.value)" onchange="updateTextInput1(this.value)" />
    <input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" onkeypress="updateTextInput1(this.value)" onchange="updateTextInput1(this.value)" />

A: It's not working because updateTextInput1(this.val) should be updateTextInput1(this.value):

function updateTextInput1(val) {
  document.getElementById('num1').value = val;
}
<input class="inputRange" type="range" min="0" max="100" onchange="updateTextInput1(this.value)" />
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

However, I'd suggest using unobtrusive JavaScript, though.
Just attach an input event to each element. In doing so, both elements will be in sync.

var range = document.querySelector('.inputRange');
var field = document.getElementById('num1');

range.addEventListener('input', function (e) {
  field.value = e.target.value;
});
field.addEventListener('input', function (e) {
  range.value = e.target.value;
});
<input class="inputRange" type="range" min="0" max="100" value="0" />
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

Or you could use a more compact approach and select the sibling element:

document.querySelector('.inputRange').addEventListener('input', updateValue);
document.getElementById('num1').addEventListener('input', updateValue);

function updateValue (e) {
  var sibling = e.target.previousElementSibling || e.target.nextElementSibling;
  sibling.value = e.target.value;
}
<input class="inputRange" type="range" min="0" max="100" value="0"/>
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

A: You should bind event using js/jq. And to link both, you could target specific sibling element (or any other relevant transversal method):

$('.inputRange, .inputNumber').on('input', function(){
  $(this).siblings('.inputRange, .inputNumber').val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="inputRange" type="range" min="0" max="100" value="0"/>
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Limit of sum of series Let $$\sum_{i=1}^\infty c_i^{(0)}$$
be a positive convergent series. Then the series:
$$\sum_{i=1}^\infty c_i^{(1)}=\sum_{i=1}^\infty \ln(1+c_i^{(0)})$$
is also a positive convergent series.
Generally let take $c_i^{(N+1)}=\ln(1+c_i^{(N)})$ and define the sum:
$$S^{(N)}=\sum_{i=1}^\infty c_i^{(N)}$$
What can we say about the limit:
$$\lim_{N\rightarrow\infty} S^{(N)}.$$
which is certainly exist. Is it zero? Is it nonzero? (given $\{c_i^{(0)}\}$)

A: A start: Use Comparison. Note that if $x\ge 0$ then $0\le \ln(1+x)\le x$.


text:
Q: practical usage of hadoop map reduce hive pig hbase Hello,
I am learning Hadoop and after reading the material found on the net (tutorials, map reduce concepts, Hive, Ping and so on) and developed some small application with those I would like to learn the real world usages of these technologies.
What are the everyday software we use that are based upon Hadoop stack?

A: If you use the internet, there are good changes that you are indirectly impacted from Hadoop/MapReduce from Google Search to FaceBook to LinkedIn etc. Here are some interesting links to find how widespread Hadoop/MR usage is
Mapreduce & Hadoop Algorithms in Academic Papers (4th update – May 2011)
10 ways big data changes everything
One thing to note is Hadoop/MR is not an efficient solution for every problem. Consider other distributed programming models like those based on BSP also.
Happy Hadooping !!!

A: Here are some sample mapreduce examples which will be helpful for beginners..
1.Word Count
2.SQL Aggregation using Map reduce
3.SQL Aggregation on multiple fields using Map reduce
URL - http://hadoopdeveloperguide.blogspot.in/


text:
Q: Trying to read contents of a file, but failing? What's wrong with this code? I'm new to python and have been learning it for almost 4 months now. A few days ago, I decided to try to make a small mailing system. Just to learn Files. I tried reading the contents of the file, but the program just closes.
Here's the code:
    def userlogin():
        f1 = open("user.txt","r")
        name1 = raw_input("Enter username: ")
        s1 = f1.readlines()
        print s1

I have called the function after that. Also, I have a file created with stuff written in them. I also tried the read() and readline() functions, but it doesn't seem to work. As soon as the program reaches this stage, it asks for Username..and then abruptly closes the window. Can anyone help me?


text:
Q: Htaccess to rewrite url for an existing php app I have developed a PHP application and I want to rewrite the URLs to make it cleaner,
I have multiple pages, each page can have 0 or multiple GET variables,
Example of what I want to achieve:
index.php   ->   /
/index.php?var1=aaa&var2=bbb&var3=ccc   ->   /var1/aaa/var2/bbb/var3/ccc
/product.php?var4=ddd&var5=eee   ->   /product/var4/ddd/var5/eee
/products-list.php   ->   /products-list/
etc...
Can anyone help me with a full .htaccess file to achieve this result?
And is there a way to make the PHP read the GET params or do I need to add a function to create a $_GET array from the URL on each page?
Thank you.

A: These simple rules will rewrite the examples you give in the question:
RewriteEngine on
RewriteEngine ^/?products-list/?$ /products-list.php [QSA,END]
RewriteRule ^/?product/([^/+])/([^/+])/([^/+])/([^/+])/?$ /product.php?$1=$2&$3=$4 [QSA,END]
RewriteRule ^/?([^/+])/([^/+])/([^/+])/([^/+])/([^/+])/([^/+])/?$ /index.php?$1=$2&$3=$4&$5=$6 [QSA,END]

You might have to add some conditions to prevent interference with other rules or rewriting loops. But that is nothing we can know without insight into your specific situation and setup.


text:
Q: DataTables - checkbox with 'onchange' not working I am using dataTables and want to include a checkbox that will update my data when changed (select, deselect). The data is displayed in the table with the checkbox on each row; however:

*

*this.checked is not recognised (returns 'undefined'); and

*When I select or deselect a checkbox I get an error in the console log: Uncaught SyntaxError: Unexpected token ','

The code is:
{data: null,
  className: "center",
  render: function(data,type,row) {
      return ("<input type='checkbox' id=" + data.cdId + " name='update' onchange='ymActivityPatrolFunction(" + data.cdId + ", " + this.checked + ")' style='zoom: 2.0;'>")
     },
},

Which gives:

A: You can pass only this inside your function then to get other value you can use attr("id") to get cdId value and checked to get checked values i.e : true/false.
Demo Code :

var data = [{
    "cdId": "1gh",
    "name": "Tiger Nixon",
  },
  {
    "cdId": "2htf",
    "name": "Garrett Winters"
  },

];

var table = $('#example').DataTable({
  data: data,
  columns: [{
      targets: 0,
      data: "cdId",
      render: function(data, type, row) {
        //use only `this` and change data to `data.cdId` this is for dmo only..
        return ("<input type='checkbox' id=" + data + " name='update' onchange='ymActivityPatrolFunction(this)' style='zoom: 2.0;'>")
      },
      className: "center"
    },
    {
      "data": "name"
    }
  ]
});

function ymActivityPatrolFunction(checkeds) {
  //get id..and check if checked
  console.log($(checkeds).attr("id"), checkeds.checked)

}

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.16/datatables.min.css" />

      Checkbox
      Name

      Checkbox
      Name


text:
Q: Does the use of $\delta(\omega-\omega_1)$ for retrieving amplitude of a single Fourier-component of a periodic function violate Fubuni's requirements? I've got a non-negative function $f(x)=a+b\cos(\omega_1 x)$ for $a,b,\omega_1 \in \mathbb R$ and I need to represent $b^2$ as a square of the Fourier-transform of a whatever function.
As a physicist I do my best first without (very much) checking if the transformations are equivalent:
\begin{align}
b&={\mathscr{F}\{f(x)\}(\omega)}\vert_{\omega=\omega_1}\tag{1}\\\\
&=\int_{-\infty}^{+\infty}\mathscr{F}\{f(x)\}\delta(\omega-\omega_1)d\omega\tag{2}\\\\
&=\frac 1{\sqrt{2\pi}}\int_{-\infty}^{+\infty}\mathscr{F}\{f(x)\}\mathscr{F}\{e^{-i\omega_1 x}\}d\omega\tag{3}\\\\
&=\frac 1{2\pi}\int_{-\infty}^{+\infty}\mathscr{F}\{f(x)*e^{-i\omega_1 x}\}d\omega\tag{4}\\\\
&=\frac{1}{2 \pi} \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(-i \omega_{1}\left(x-x^{\prime}\right)\right) d x^{\prime}\right) \exp (i \omega x) d x\right) d \omega\tag{5}\\\\
&=\frac{1}{2 \pi} \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) \exp \left(-i \omega_{1} x\right) d x^{\prime}\right) \exp (i \omega x) d x\right) d \omega\tag{6}\\\\
&=\frac{1}{2 \pi} \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}\right) \exp \left(-i \omega_{1} x\right) \exp (i \omega x) d x\right) d \omega\tag{7}\\\\
&=\frac{1}{2 \pi} \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}\right) \exp \left(i (\omega-\omega_{1}) x\right) d x\right) d \omega\tag{8}\\\\
&=\frac{1}{2 \pi} \int_{-\infty}^{+\infty}\left(\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}\right)\left(\int_{-\infty}^{+\infty} \exp \left(i\left(\omega-\omega_{1}\right) x\right) d x\right)\right) d \omega\tag{9}\\\\
&=\frac{1}{2 \pi}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}\right) \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} \exp \left(i\left(\omega-\omega_{1}\right) x\right) d x\right) d \omega\tag{10}\\\\
&=\frac{1}{2 \pi}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}\right) \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} \exp \left(i\left(\omega-\omega_{1}\right) x\right) d \omega\right) d x\tag{11}\\\\
&=\frac{1}{2 \pi}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}\right) \iint_{-\infty}^{+\infty} \exp (i \omega x) \exp \left(-i \omega_{1} x\right) d \omega d x\tag{12}\\\\
&=\frac{1}{2 \pi}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}\right) \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} e x p\left(-i \omega_{1} x\right) d \omega\right) \exp (i \omega x) d x\tag{13}\\\\
&=\frac{1}{2 \pi} \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}\right) \exp \left(-i \omega_{1} x\right) d \omega\right) \exp (i \omega x) d x\tag{14}\\\\
&=\frac{1}{2 \pi} \int_{-\infty}^{+\infty}\left(\int_{-\infty}^{+\infty} {\left[f(x) * \exp \left(-i \omega_{1} x\right)\right](x)} d \omega\right) \exp (i \omega x) d x\tag{15}\\\\
&=\frac{1}{2 \pi} \int_{-\infty}^{+\infty}\left[f(x) * \exp \left(-i \omega_{1} x\right)\right](x)\left(\int_{-\infty}^{+\infty} d \omega\right) \exp (i \omega x) d x\tag{16}\\\\
&=\frac{1}{2 \pi} \mathcal{F}\left\{\left[f(x) * \exp \left(-i \omega_{1} x\right)\right](x)\right\}(\omega) \cdot \int_{-\infty}^{+\infty} d \omega\tag{17}\\\\
\end{align}
Where the last factor is the overall volume of the reciprocal to $x$ space. This quantity has a prefactor of $2\pi$ and units of those inverse to $\int_{-\infty}^{+\infty}dx$.
From (6) to (7) was used, that $\exp \left(-i \omega_{1} x\right)$ is not a function of $x'$; from (8) to (9) - that $\int_{-\infty}^{+\infty} f\left(x^{\prime}\right) \exp \left(i \omega_{1} x^{\prime}\right) d x^{\prime}$ doesn't depend on $x, x'$ and $\omega$; throughout (10)-(12) - the Fubini's (or Fubini-Tonelli's?) theorem is applied; from (12) to (13) the action is performed as, for example, here in the proof of the multiplication theorem.
My questions are

*

*Can either of Fubini's or Fubini-Tonelli's theorems be applied where they are applied in this derivation?

*Are all the transformations legit (and in which sense)?

My fear is, that either the integrability of $\exp \left(i\left(\omega-\omega_{1}\right) x\right)$ is not met here, or, possibly, other requirements. I'd appreciate any help.


text:
Q: create the admin system for my program via ADT linkedlist class Attraction {
    protected:
        int id;
        string name;
        int typeID;

    public:
        Attraction(int id, string name, int typeID):id(id),name(name),typeID(typeID){};

        // getters and setters
        int getId(){return id;}
        void setId(){this->id=id;}
        string getName(){return name;}
        void setName(string name){this->name=name;}
        int getTypeID(){return typeID;}
        void setTypeID(){this->typeID=typeID;}

        virtual void display()=0;//abstract class

};
// City object
class City {
        friend ostream& operator<< (ostream& ,City &);
        private:
        int id;
        string name;

        // vector might changed to your own ADT in milestone 2, since STL only acceptable in milestone 1
        vector<City*> directFlight; // adjacent connected cities
        LinkedList<Attraction*> attractions; // contained attractions
        public:
        City(int id, string name):id(id),name(name){};

        // getters and setters
        int getId(){return id;}
        void setId(int id){this->id=id;}
        string getName(){return name;}
        void setName(){this->name=name;}
        void addAttraction(int pos,Attraction*attraction)
        {
            attractions.insert(pos,attraction);
        }
        //bool isConnected(int cityID); // Check city is directly connected
        /*Attraction* getAttractions(int index)
        {
            return this->attractions[index];
        }*/

};

Use an ADT stack to implement a depth-first search to answer whether city A and city B are connected by flights, either directly or indirectly.
- To store the flight map of cities, implement an adjacency matrix using a dynamic 2D array.
can anyone give me an suggestion how to use the ADT stack to implement a DFS?
i dont understand this part,anyone can guide me?
from my attraction class and City class and Attraction on top,how to implement this two things?


text:
Q: Set Multiple Environmental Variables On Invocation of Rake Task I can invoke a Rake task and set a single environmental variable like this:
$ ONE=1 rake temp:both

But how do I set two environmental variables?
This doesn't work:
 $ ONE=1 TWO=2 rake temp:both

This works, but is confusing to read:
$ ONE=1 rake temp:both TWO=2

How can I pass more than one env before the call to rake?

A: Agree with @Ernest; it should work.  Here's a sample...
Sample rake task to echo vars:
task :echo_env do
  puts "VAR1: #{ENV['VAR1']}"
  puts "VAR2: #{ENV['VAR2']}"
end

Execute task:
VAR1=first VAR2=second bundle exec rake echo_env

Output:
VAR1: first
VAR2: second


text:
Q: Security of a self-updating web app What are the security concerns of the following scenario? (this is one of those crazy ideas that someone will try, and maybe a it's a good idea, and maybe it's a terrible idea...)
You have Rails app at example.com, and an action at https://example.com/admin/update_app
This action has the following requirements:

*

*It requires https (and redirects if not on https)

*It requires admin access

*The action displays a page with a form that says "Repository password: [              ]"

*This field is filtered out of the server logs, the same way that authentication to the site is filtered out, via the log filtering mechanism in Rails (i.e. this method)

This action does the following

*

*You put your code repository password in the field and hit "Submit"

*The action starts a shell script which pulls the latest updates from the stable branch of your code repository, and applies them to the site (unless repository authentication fails, in which case it stops all further steps)

*The web server is restarted

*An email is sent to the admin saying something simple like, "App update complete"

A: Well, this all remind me re-invented capistrano deploy on server through git repository.
Only problem that:
1) what if it will be conflicts during merge(point 2)?
2) what if webserver will not restart correctly(point 3)?
3) What if branch in your repository is not so stable(point 2)?

A: Don't send the password. The app could be compromised and trojaned or the filtering could fail. Instead, grant the web app read-only access to the repository via a separate account or public access.
Don't restart the server if there are no changes. Then the action is secure even without access control: unless the developer has authorized the update by updating the stable branch, nothing happens. If the stable branch is not so stable, create a separate production branch for this.
Stop the webserver before doing the update. The app might not be secure or safe to use as a mix of files from different versions.
Make sure the web server doesn't serve any metadata files left by the VCS.


text:
Q: Openshift Connection to closed by remote host I am using openshift as my production server for django app. However today I have had trouble running a simple update script that takes about 1 minute to update my database. I got disconnected within few seconds after I run it.
Connection to app-domain.rhcloud.com closed by remote host.
Connection to app-domain.rhcloud.com closed.

I tried to run it with nohup ./script &, but there is no error log in honup.out (except warning, so I guess it is run but killed). I tried to run it without nohup as well.
I also tried to run it from ./manage.py shell, logged out as well and script did not finish.
I've read that I might have problem with ssh keys. So I deleted my keys in ~/.ssh/ folder and created new ones with rhc setup tool.
Last option that comes to my mind is to add my script to .openshift/cron/ folder, but it is really bad solution, to create cron every time I want to run something for more than a few seconds (I get disconnected within 5 seconds).
Did openshift implement something to kill processes taking to much cpu for a minute or two?

A: I've been struggling here for 6 hours and just after posting this question I found what was the problem.
I had two models in my script. Stock (8000 objects) and Dividend (240 000 objects). I wanted to save some sql queries and I prefetched dividends for all stocks. After removing prefetch_related everything worked.
So openshift kills process/disconnects you, if you allocate too much memory (RAM) I guess.


text:
Q: AddressSanitizer: negative-size-param: (size=-2) The real code is very big with multithreading, but if to simplify it, I have the next sanitizer output and code sample:
==8808==ERROR: AddressSanitizer: negative-size-param: (size=-2)
    #0 0x55f43c1eedf0 in memmove (/home/bin/my_app+0x4ddf0)
    #1 0x7f8a76af1b70 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_replace(unsigned long, unsigned long, char const*, unsigned long) (/usr/lib/x86_64-linux-gnu/libstdc++.so.6+0x11eb70)
    #2 0x7f8a32036d6b in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::assign(char const*) /usr/include/c++/6/bits/basic_string.h:1269
    #3 0x7f8a32036d6b in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::operator=(char const*) /usr/include/c++/6/bits/basic_string.h:605
    #4 0x7f8a32036d6b in my_class::my_func(const char* str)
    ...

class my_class {
public:
void my_func(const char* str) {
 str_ = str;
}
std::string str_;
}

And... I just can't imagine a way how to reproduce it with simple example.
If str == nullptr OR any random value like str == 0x7ff01749d1b6, AddressSanitizer will report SEGV on unknown address 0x000000000000(OR 0x7ff01749d1b6)
If str points to a freed heap memory, AddressSanitizer will report heap-use-after-free error.
If str is a string without \0, AddressSanitizer will report heap-buffer-overflow error.
Can any one suggest how to reproduce negative-size-param error with std::string and const char*? I hope this undestanding helps me to find mistake in my real code...


text:
Q: Circled inline numbers and letters Based on Good way to make \textcircled numbers?, is there a simple way to make the circles look exactly the same for numbers and all letters (i.e. size and placement)?
When one inserts an a in the circle, the node is drawn slightly lower than the node for a number.
\documentclass{article}

\usepackage{tikz}
\newcommand*\circled[1]{\tikz[baseline=(char.base)]{
    \node[shape=circle, draw, inner sep=1pt,
        minimum height=12pt] (char) {#1};}}

\begin{document}
This is \circled{a} \circled{1} balloon.
\end{document}

EDIT
Based on the answer by @koleygr and the post circled letters: same size as uncircled letters, I find this solution the most pleasing and versatile:
\newcommand*{\circled}[2][]{\tikz[baseline=(C.base)]{
    \node[inner sep=0pt] (C) {\vphantom{1g}#2};
    \node[draw, circle, inner sep=3pt, yshift=1pt]
        at (C.center) {\vphantom{1g}};}}

A: Edit after accepted:
\documentclass{article}

\makeatletter
\usepackage{tikz}
\usetikzlibrary{calc}
\newcommand*\circled[1]{\tikz[baseline=(char.base)]{
    \node[shape=circle, draw, inner sep=1pt,
        minimum height={\f@size*1.6},] (char) {\vphantom{WAH1g}#1};}}
\makeatother

\begin{document}
This is \circled{a} \circled{1} balloon.

\noindent\foreach \letter in {A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,V,U,W,X,Y,Z,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,1,2,3,4,5,6,7,8,9,0,.,/}
{%
\circled{\letter}\space%
}
\end{document}

Output:

Not really perfect because of different base on chars (but it is better from
the bellow answer)
Checking the same code in the document environment above with below definition of circled:

As you can see with previous (below) code the sizes change between small and capital letters.
Old answer:
A \vphantom in your definition will help:
\documentclass{article}

\usepackage{tikz}
\newcommand*\circled[1]{\tikz[baseline=(char.base)]{
    \node[shape=circle, draw, inner sep=1pt,
        minimum height=12pt] (char) {\vphantom{1g}#1};}}

\begin{document}
This is \circled{a} \circled{1} balloon.
\end{document}

Output:


text:
Q: Correctly type in parsing json When parsing a json response, one of the keys can come as a string "value" or null.
I'm parsing the response as:
  @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({
           "status",
           "code",
           "exception"
    })

    public class Response {

    private String status;
    private long code;
    private String exception;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getException() {
        return exception;
    }

    public void setException(String exception) {
        this.exception = exception;
    }

When I get null, I have error. How can I do it correctly?
I try @JsonInclude(JsonInclude.Include.NON_NULL), but it's not work
public class JsonParserResponse  throws UnsupportedEncodingException, JsonParseException, IOException {
    Response resp= new Response();
try{
        JSONObject outerObject = new JSONObject({"status":null,"code":0,"exception":""} );
       resp.setStatus(outerObject.getString("status")); System.out.printf("name=%s , value=%s\n", "status", outerObject.getString("status"));
             resp.setCode(outerObject.getInt("code")); System.out.printf("name=%s , value=%s\n", "code",outerObject.getInt("code"));
             resp.setException(outerObject.getString("exception")); System.out.printf("name=%s , value=%s\n","exception" ,outerObject.getString("exception"));
}catch(Exception e) {
            e.printStackTrace();
        }

I have error^
JSONObject["status"] not a string.
    at org.json.JSONObject.getString(JSONObject.java:639)
    at ru.JsonParserResponse.parseResult(JsonParserResponse.java:161)
    at ru.JsonParserResponse.main(JsonParserResponse.java:74)

A: this will help
add @JsonIgnoreProperties(ignoreUnknown =true) on Response class, that will ignore null values (com.fasterxml.jackson.annotation.)
and no need to use JsonProperty when your variable name same as your JsonProperty

A: This code should work (it seems you have wrong formatting of json):
    String json = "{\"status\":null,\"code\":0,\"exception\":\"\"}";

    JSONObject outerObject = new JSONObject(json);

    Response resp = new Response();

    resp.setStatus(outerObject.getString("status"));
    resp.setCode(outerObject.getInt("code"));
    resp.setException(outerObject.getString("exception"));

A: import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
Try this once at your class hope this will help you.
@JsonInclude(Include.NON_NULL)
public class Response {
    // code.....
}


text:
Q: SELECT Statement - Syntax error in query expression ' ' Trying to SELECT a row in my excel file. I'm using it as a database. I'm pretty sure the problem is either in my query or in my excel file.
SELECT * FROM [tableName$] where _columnNum1 = 'testData123'"
I've tried doing this code for a while
SELECT * FROM [tableName$]
and it worked. So every time I add a WHERE clause, it causes the error. What seems to be the problem here?
The error says Syntax error in query expression '_columnNum1 = 'testData123''
UPDATE: I forgot to add this, I've already googled this thing for some time now, and the error is about data types. But since I'm using excel as a database, I can't really manipulate data types around them. Or can I? Anyway maybe the error is about data types.

A: After hours of searching, finally got the answer. I simply added brackets on the column name. I didn't need them when I was inserting data in my excel file.
I have the string sql of
SELECT * FROM [tableName$] where _columnNum1 = 'testData123'"
when it should be
SELECT * FROM [tableName$] where [_columnNum1] = 'testData123'"
I got the answer here:
SOURCE: OLE CALL to Excel with WHERE clause
Another note, for people who has trouble inserting data in their excel where the data does not go to the first row, the source might be the answer, too.


text:
Q: Canvas line behaviour when 0 < lineWidth < 1 Out of curiosity I wanted to try to set the lineWidth < 1 because the 1px lines looked fat even with my resolution set correctly. Unsurprisingly it doesn't work but there is this weird behaviour on Chrome and Firefox (not tested elsewhere):

On the left is with lineWidth = 1, center is lineWidth = 0.5 and right is lineWidth = 0.1
They were generated with this code:
ctx.lineWidth = 0.1;

        lis.each(function(i) {

            sx = $(this).offset().left;
            sy = $(this).offset().top;

            ex = sx - (20 * (6-i));
            ey = wh - 80 - (20 * (i + 1));
            eey = ey - (20 * i);

            // Horizontal
            ctx.moveTo(sx,sy+7);
            ctx.lineTo(ex, sy+7);
            ctx.stroke();

            // Vertical
            ctx.moveTo(ex,sy+7);
            ctx.lineTo(ex, ey);
            ctx.stroke();

            // Horizontal
            ctx.moveTo(ex,ey);
            ctx.lineTo(ww - bg_img_width + 100, eey);
            ctx.stroke();
        });

They are printed in the order their children appear so it starts with Alpha each time and ends with Epsilon.
Can anyone explain why the lines get thiner as the loop progresses when 0 < lineWidth < 1? Is this intended? Can it be used for cool stuff?

A: First thing to remind is that points in a canvas are centered on (0.5;0.5) , so ,to draw a clean 1px wide line, one has to draw at integer coordinates + (0.5, 0.5).
Then to emulate thickness, the renderer will play on opacity : a 0.5 line will be rendered less opacity to make it look 'weaker'.
Notice that this is the way the antialiasing works also : it diffuses the point on several neighbor points with a lower weight to simulate the thickness of the line.
You can play with the below fiddle were i compare several ways to draw a triangle.
I think we have same visual effect than with lineWidth=0.5 when we draw with 0.8 opacity for instance.
The two first lines are here to show the the difference in render when using integer coordinates vs when using integer + 0.5 coordinates. We see that when using integer coordinates, the lines overlap on two pixels and seems wider.
We see also that antialiasing is not that good since the diagonal always seems thicker (same on Chrome or Firefox here).
http://jsbin.com/voqubexu/1/edit?js,output


text:
Q: On $xOy$ plane, what is the equation of the vertical line passing through $(x,0)$? This seems to be a trivial question but I failed to find a good notation for it. Surely the vertical line passing through $(a,0)$ has the equation $x=a$. But $x=x$ does not seem to be a good equation for the vertical line passing through $(x,0)$.
I have to tag "relations" instead of "functions" as this line does not represent a function.

A: The problem is that the $x$ you're using for the term "$xy$ plane" (or just the name of the axis) and the $x$ used in the name of the point $(x,0)$ simply have  two different meanings, so even attempting to write them like this results in obvious problems.
$x$ in the case of the $x$ axis simply represents a variable, an indeterminant, the input value to your function/relation, whatever you choose to call it.
In the case of $(x,0)$, it is meaning to reference the first coordinate of the pair that the point represents.
The only way to treat these together would be like ... $x$ as a parameterization of the real number line / $x$-axis while in the $xy$ plane, i.e.
$$\text{the x-axis} = \{ (x,0) \mid (x,y) \in \Bbb R^2 \}$$
which is obviously not what you want.
The conclusion being, be very careful with what you name things. In the situation posed, you either get what you don't want or pure nonsense out of using $x$ (or any other such dummy variable) in multiple ways at the same time. Rename the axes, or rename the point. If you decided to work with the $zy$ plane instead, your equation would be $z=x$. If you renamed the point, call it $(x_0,0)$ for instance, then the line $x=x_0$ makes perfect sense as a satisfactory definition.


text:
Q: Intellij: Search through the source of maven dependencies in a project Is it possible to search for a bit of text through the source code of all the maven dependencies of a project?
For example: If you import the following sample maven project: https://github.com/ajorpheus/javadoc-mem-test/tree/search-in-jars, searching for tempHeaders should turn up AbstractClientHttpRequest.java as a search result.
Is there a plugin that allows one to do this?
If Intellij does not support this, would you know of an IDE-agnostic way to do this given a maven project? I have looked at tools like jarexplorer but they don't seem to do the job.

A: If I understand your requirement correctly, what you are trying to do is possible.
First in the Maven pane you need right click on dependencies and select 'Download Sources'.
Once that is done, follow Ashutosh Jindal instructions to search in your code and the dependencies code.

A: I found how to do this !
Use the 'Project and Libraries' Custom Scope.

A: in IntelliJ IDEA 2018, you can do this: ctrl+shift+f

thanks @Ashutosh Jindal

A: I have faced the same problem. There is two way to search in Intellij.
1. Ctrl + shift + F
2. navigate - > search everywhere or use Ctrl + N
To search in external libraries , you have to make sure they are downloaded first in your system then only you can search anything among them.

A: For IntelliJ 2020 go to the main menu, select Navigate | Search Everywhere or press Shift twice to open the search window.
For more information check here:
https://www.jetbrains.com/help/idea/searching-everywhere.html#search_all
Search everywhere example

A: First you need to download the source from maven tool bar


text:
Q: Creating mysql view with an existing table name on every http request for roles purposes I need to add permissions and roles to my app, But I wouldn't like to go file by file method by method, The kind of roles I need is for example showing only specific records from database depending on the user connected.
Exemple: I have a "contracts_types", And "contracts" table, When listing "contracts" I use a JOIN with "contracts_types" so that I show the contract type as well, So If the contract type doesn't exist, The contract wouldn't be shown, What I'd like to do, Is to create some sort of a view every time user is connected, The view should contain an image of the table with a filter:
CREATE VIEW contracts_types AS SELECT * FROM contracts_types WHERE contractTypeId IN( USER AUTHORISED CONTRACTS TYPES IDS )

I'm not sure if this is possible, If it is, Is there a performance issues creating the same view on every http request for each user connected, I mean , Other users will be connected and the same view name will be created, I'm looking for a similar solution where I don't need to go to every select statement I made and add the contractTypeId filter, Thanks.

A: "So If the contract type doesn't exist, The contract wouldn't be shown" -- That's what this does:
SELECT ...
    FROM contracts AS c
    JOIN contract_types AS ct  ON ct.type = c.contract_type

Or is your question more involved?
You cannot do any kind of filtering on rows of a table without having some kind of filter in the query.
SELECT ...
    FROM contracts AS c
    JOIN contract_types AS ct  ON ct.type = c.contract_type
    JOIN role_can_see AS ucs  ON rcs.type = c.contract_type
    WHERE rcs.role = ?

(and fill in the role that the user belongs to)
If the user is in multiple roles, then
    WHERE rcs.role IN (...)

But this is effectively implementing "roles" yourself.


text:
Q: Connect to SQL Server 2008 Express database using C# I am developing a Winforms application in which I am using SQL Server 2008 Express Edition as backend. But I am getting error:

Additional information: An attempt to attach an auto-named database for file D:\Hardik\Hardik\dotnet\TestApplication\TestApplication\bin\Debug\MyDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

My code is:
private void Form1_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "Select * From MyTable";
    cmd.CommandType = CommandType.Text;

    da = new SqlDataAdapter();
    da.SelectCommand = cmd;

    dt = new DataTable();
    ds = new DataSet();

    da.Fill(ds, "Login");
    dt = ds.Tables[0];

    dataGridView1.DataSource = dt;
}

and my app.config file is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <connectionStrings>
       <add name="MyConnection"
            connectionString="Server=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True; User Instance=True"
            providerName="System.Data.Client"/>
   </connectionStrings>
</configuration>

Where I am wrong?

A: use double slash instend of single slash.
A UNC path uses double slashes or backslashes to precede the name of the computer.
<connectionStrings>
    <add name="MyConnection" connectionString="Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True; User Instance=True" providerName="System.Data.Client"/>
  </connectionStrings>

for instance failure
As you got the error "instance failure", that might be the error with your SQL Server instance..
Make sure your SQL Server instance(MSSQLSERVER) is running, where you can check in: Services list. TO get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter. That takes you to services management console, where you can check whether your instance in running or not..
If the problem still persists, then try using: Data Source=.\SQLEXPRESS instead.. :)


text:
Q: How to resolve FileNotFoundError UserDict.py when building a PIP project using Hatchling? I encountered the problem below when trying to build a pip package for a new release of my [SkillMetrics][1] package. I was following the instructions for [Packaging Python Projects][2] using the Hatchling build system instead of the standard setuptools.
% python3 -m build
* Creating venv isolated environment...
* Installing packages in isolated environment... (hatchling)
* Getting dependencies for sdist...
* Building sdist...
* Building wheel from sdist
* Creating venv isolated environment...
* Installing packages in isolated environment... (hatchling)
* Getting dependencies for wheel...
* Building wheel...
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pep517/in_process/_in_process.py", line 351, in <module>
    main()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pep517/in_process/_in_process.py", line 333, in main
    json_out['return_val'] = hook(**hook_input['kwargs'])
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pep517/in_process/_in_process.py", line 249, in build_wheel
    return _build_backend().build_wheel(wheel_directory, config_settings,
  File "/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-env-tzuwjpjg/lib/python3.10/site-packages/hatchling/build.py", line 41, in build_wheel
    return os.path.basename(next(builder.build(wheel_directory, ['standard'])))
  File "/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-env-tzuwjpjg/lib/python3.10/site-packages/hatchling/builders/plugin/interface.py", line 144, in build
    artifact = version_api[version](directory, **build_data)
  File "/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-env-tzuwjpjg/lib/python3.10/site-packages/hatchling/builders/wheel.py", line 318, in build_standard
    record = archive.add_file(included_file)
  File "/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-env-tzuwjpjg/lib/python3.10/site-packages/hatchling/builders/wheel.py", line 59, in add_file
    file_stat = os.stat(included_file.path)
FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-via-sdist-z4709rdv/skillmetrics-1.1.9/mitmenv/lib/python2.7/UserDict.py'

ERROR Backend subprocess exited when trying to invoke build_wheel

A: It turns out the problem occurs because of the presence of a mitmenv directory containing any old builds. To resolve the problem I simply removed the directory and all its contents. The build then ran flawlessly using python3:
% python3 -m build
* Creating venv isolated environment...
* Installing packages in isolated environment... (hatchling)
* Getting dependencies for sdist...
* Building sdist...
* Building wheel from sdist
* Creating venv isolated environment...
* Installing packages in isolated environment... (hatchling)
* Getting dependencies for wheel...
* Building wheel...
Successfully built skillmetrics-1.2.1.tar.gz and skillmetrics-1.2.1-py3-none-any.whl

I'm posting the problem with solution here to help others save their time in packaging a python project.


text:
Q: Neovim stop compiling typescript with Neomake and Typescript-Vim I am writing Typescript in Neovim, with plugins leafgarland/typescript-vim and benekastah/neomake, among others, and whenever I save the file gets compiled.
My understanding (I could be wrong) is that when a file is opened, created or saved Neomake is run as indicated by au BufRead,BufNewFile,BufWritePost * Neomake. I still want this to happen so that I can get error messages displayed on save, but I don't want it to compile the Typescript file I am working on.
Removing typescript-vim stops the compilation but there are no error messages, sytax highlighting or auto-indentation.
Relevant code from nvim/nvimrc
let g:neomake_typescript_tsc_maker = {
        \ 'args': ['--module', 'system', '--target', 'ES5', '--experimentalDecorators'] }

let g:neomake_warning_sign = { 'text': '!', 'texthl': 'WarnMsg' }
let g:neomake_airline = 1

au BufRead,BufNewFile,BufWritePost * Neomake

Here are the rest of my dotfiles which contain the rest of the nvimrc.
Thanks in advance :)

A: By adding the --noEmit flag to the args of neomake when settings the typescript maker, a compiler javascript file no longer appears in the directory upon save.
let g:neomake_typescript_tsc_maker = {
    \ 'args': ['--module', 'system', '--target', 'ES5', '--experimentalDecorators', '--noEmit'] }


text:
Q: php minify - rewritten URL cache by browser I am trying to create rewritten URL for CSS/JS with php minify. At tools.pingdom I recieved this message:
The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources:
http://www.xxx.xx/assets/minify/css-combined.css
http://www.xxx.xx/assets/minify/js-combined.js
At the root I have .htaccess containing expires and header rules:
<IfModule mod_expires.c>
ExpiresActive on
# Perhaps better to whitelist expires rules? Perhaps.
ExpiresDefault      "access plus 1 month"
# cache.appcache needs re-requests
# in FF 3.6 (thx Remy ~Introducing HTML5)
ExpiresByType text/cache-manifest "access plus 0 seconds"
# Your document html
ExpiresByType text/html "access plus 1 month"
# Data
ExpiresByType text/xml "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType application/json "access plus 0 seconds"

# RSS feed
ExpiresByType application/rss+xml "access plus 1 hour"

# Favicon (cannot be renamed)
ExpiresByType image/x-icon "access plus 1 week"

# Media: images, video, audio
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"

# HTC files  (css3pie)
ExpiresByType text/x-component "access plus 1 month"

# Webfonts
ExpiresByType font/truetype "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType font/woff "access plus 1 month"
ExpiresByType application/x-font-woff   "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"

# CSS and JavaScript
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType text/javascript "access plus 1 year"

<IfModule mod_headers.c>
    Header append Cache-Control "public"
    Header append Vary User-Agent
    <FilesMatch "\.(js|css|xml|gz|woff)$">
        Header append Vary: Accept-Encoding
    </FilesMatch>
</IfModule>

in the folder of minify there is following .htaccess rules:
RewriteEngine on

RewriteRule ^(.*).js$ index.php?g=$1
RewriteRule ^(.*).css$ index.php?g=$1

Could you please help me? What am i doing wrong?
Thank you=)
Best regards,
Russianroot

A: closing of IfModule may fix your problem
<IfModule mod_expires.c>
i modify this for you

<IfModule mod_expires.c>
ExpiresActive on
# Perhaps better to whitelist expires rules? Perhaps.
ExpiresDefault      "access plus 1 month"
# cache.appcache needs re-requests
# in FF 3.6 (thx Remy ~Introducing HTML5)
ExpiresByType text/cache-manifest "access plus 0 seconds"
# Your document html
ExpiresByType text/html "access plus 1 month"
# Data
ExpiresByType text/xml "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType application/json "access plus 0 seconds"

# RSS feed
ExpiresByType application/rss+xml "access plus 1 hour"

# Favicon (cannot be renamed)
ExpiresByType image/x-icon "access plus 1 week"

# Media: images, video, audio
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"

# HTC files  (css3pie)
ExpiresByType text/x-component "access plus 1 month"

# Webfonts
ExpiresByType font/truetype "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType font/woff "access plus 1 month"
ExpiresByType application/x-font-woff   "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"

# CSS and JavaScript
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType text/javascript "access plus 1 year"
</IfModule>
<IfModule mod_headers.c>
    Header append Cache-Control "public"
    Header append Vary User-Agent
    <FilesMatch "\.(js|css|xml|gz|woff)$">
        Header append Vary: Accept-Encoding
    </FilesMatch>
</IfModule>


text:
Q: Platform-dependent behavior of fread with large nitems parameter I created the test program below in an attempt to debug an issue in a larger system. The program attempts to fread a large chunk of data from a small file, but I've found that the behavior of the program differs across platforms.
Expected behavior
The behavior that I expect, and that I see on some platforms (e.g., Mac OS X, CentOS 6.4), is for the program to read N bytes (the size of the file) and then terminate with the EOF condition:

Read 2 bytes.
OK. EOF

Anomalous behavior
On some platforms (e.g., CentOS 6.6), the program reports 0 bytes read and fails with an error:

Read 0 bytes.
NOOOOOOOOOOOOOO!!!! Error: Operation not permitted

On these platforms, I can get the code to work as expected by reducing the chunk size "enough", but I'm not sure how to determine an acceptable size programmatically...
Questions

*

*Am I using fread correctly?

*Is there a more portable approach I should be using?

*Any suggested workarounds?

Code
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
    FILE* file = fopen("test.txt", "rb");
    size_t chunk = 0x7FFFFFFF;
    char* buf = malloc(chunk);
    if (buf == NULL) {
        printf("malloc failed\n");
        return 1;
    }
    int count = fread(buf, 1, chunk, file);
    printf("Read %i bytes.\n", count);
    int eof = feof(file);
    if (eof) {
        printf("OK. EOF\n");
    }
    int err = ferror(file);
    if (err) {
        printf("NOOOOOOOOOOOOOO!!!! Error: %s\n", strerror(err));
        return 1;
    }
    free(buf);
    return 0;
}

For my test, I created test.txt with echo "a" >test.txt.


text:
Q: How to use Lightning Web Component inside Visual Force Pages? I want to achieve file upload functionality in LWC component through Visual force page.
Here, my visual force page code
My Apex Page, Aura Application, HTML an JS code :

<apex:page showheader="false" sidebar="false">
   <apex:includelightning />
   <div id="LightningComponentid" />

   <script>
        $Lightning.use("c:aH_UDC_AmadeusFileUpload_POC", function() {
            $Lightning.createComponent("c:aH_UDC_FileUploadLWC_POC",
            {
                recordid :  "{!$CurrentPage.parameters.id}",
            },
            "LightningComponentid", // the Id of div tag where your component will be rendered
            function(cmp) {
                console.log('Calling the LWC Component');
                 console.log('record id : ' + "{!$CurrentPage.parameters.id}");
            });
        });
   </script>
</apex:page>

import { LightningElement, api } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class AH_UDC_FileUploadLWC_POC extends LightningElement {
    @api recordId;

    get acceptedFormats() {

        return ['.TXT', '.BMP', '.JPEG', '.PNG', '.PDF', '.XLS', '.DOC', '.DOCX', '.XLSX', '.JPG', '.MSG', '.PPT', '.PPTX', '.GIF', '.SVG', '.EPS', '.CDR', '.ZIP','.bak'];
    }
    handleUploadFinished(event) {

        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        let uploadedFileNames = '';
        for(let i = 0; i < uploadedFiles.length; i++) {
            uploadedFileNames += uploadedFiles[i].name + ', ';
        }
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: uploadedFiles.length + ' Files uploaded Successfully: ' + uploadedFileNames,
                variant: 'success',
            }),
        );
    }
}
<aura:application extends="ltng:outApp" access="Global">
    <aura:dependency resource="c:aH_UDC_FileUploadLWC_POC"/>
</aura:application>

<template>
   <lightning-card title="LWC File Upload Example" icon-name="custom:custom19">
      <lightning-file-upload label="Attach receipt"
                             name="fileUploader"
                             accept={acceptedFormats}
                             record-id="aAp290000004Nn2CAE"
                             onuploadfinished={handleUploadFinished}
                             multiple>
      </lightning-file-upload>

   </lightning-card>
</template>

lightning-file-upload is not working properly. what is missing in code?
Please help me.

A: This is expected behavior, unfortunately.  Each standard lwc component has documentation, that explains where this component can work as expected. Because you are using aura as a parent container for lwc, check aura documentation for the component, for example lightning:button. Targets are saying:

pay attention Lightning Out / Visualforce is present here. That means this component will work embedded in VF page.
However, file:Upload has limited set of targets:

pay attention Lightning Out / Visualforce is missing here. This works correctly only in lightning experience, mobile app, and in community.


text:
Q: Gitorious: private mode for projects How do we make a project private in Gitorious? Does Gitorious support it at all? I searched around but couldn't find anything useful, except that Gitorious doesn't seem to have a private mode for projects. Thanks in advance.

A: If you really need private repositories, and you are looking for a free alternative, try BitBucket. Unlimited private repositories, for free!

A: It's not possible in Gitorious at the moment/maybe never. There is an outstanding merge request at the moment here but there is no update as to when it will hit the mainline (i.e. Gitorious.org).
If you want private repositories then you need to host Gitorious yourself - it's easy enough to install, and then make the entire install private.

A: Gitorious now has support for private repos. Get the latest version and add enable_private_repositories: true to config/gitorious.yml.  The Gitorious wiki page is https://gitorious.org/gitorious/pages/PrivateRepositories.

A: There is a fork of Gitorious called YouSource which has private repositories. The repo is here and there's also a detailed installation guide for it.

A: As of Nov 2011, there is a new supported Private Repositories feature being planned, keep tracking of it and support if you can.
Also note that, the private repository feature may be only enabled if you have a local installation.

A: As of version 2.2.0, Gitorious supports private repositories. You should check out private-repos branch and you will be able to create private repositories.
More details can be seen in wiki page https://gitorious.org/gitorious/pages/PrivateRepositories


text:
Q: VB - Maths Quiz Check Answer I am currently doing a project and am trying to make my own maths quiz. Basically, I have 3 labels and a textbox. In the first and third label a number is randomly generated. In the second label, a mathematical operator is selected (either +, - or ÷). In the textbox, the user will input an answer to the equation, which brings me to the question i would like to ask:
I can do everything up to this point fine but i can't get my head around a code that will check whether the answer inputted into the textbox is correct.
I have tried...
 If lbloperator.Text = "+" & txtsum.Text =num1 +  num2 Then
        msgbox("CORRECT")
    End If

but it doesnt work.
In the end i would like to replace the msgbox with a counter to count the number of correct answers attained over the duration of the quiz. I have tried other things also and have been getting the error:

Conversion from string "" to type 'Double' is not valid.

If it helps, a button is put in place to randomize the operator and the number in the labels and to check if the answer is correct.
Thanks

A: Perhaps this will help.
Given these functions:
    Dim dictionary = New Dictionary(Of String, Func(Of Double, Double, Double))() _
        From _
        { _
            {"+", Function(x, y) x + y}, _
            {"-", Function(x, y) x - y}, _
            {"*", Function(x, y) x * y}, _
            {"/", Function(x, y) x / y} _
        }

    Dim process As Func(Of String, String, String, Double) = _
        Function(op, x, y) _
            dictionary(op)(Double.Parse(x), Double.Parse(y))

You can now do:
    Dim operator = TextBox1.Text ' "+"
    Dim num1 = TextBox2.Text ' "5"
    Dim num2 = TextBox3.Text ' "4"
    Dim result = process(operator, num1, num2) ' 9

Please let me know if this helps and how I can expand on it to get you where you need to go.

A: I would suggest that you use a select statement so for example try something t like this; assumes four textboxes below each other top one for first number, second for operator, third for second number last for result.  Converting to decimal to allow for people entering something like 2,5, case else allows for fact they may not enter a proper operator.
        Dim correctResults As Integer

    Private Sub CheckResult()
        Dim num1 As Decimal = CDec(textBox1.text)
        Dim num2 As Decimal = CDec(TextBox3.Text)
         Dim operator as String = TextBox2.Text
        Dim result As Decimal = CDec(TextBox4.text)

 Select Case operator

            Case "+"

                If result = num1 + num2 Then
                    correctResults += 1
                End If
            Case "-"
                If result = num1 - num2 Then
                    correctResults += 1
                End If

            Case "*"

                If result = num1 * num2 Then
                    correctResults += 1
                End If

            Case "/"

                If result = num1 / num2 Then
                    correctResults += 1
                End If

            Case Else

                Exit Sub

        End Select
    End Sub


text:
Q: Поменять дату по нажатию на button Есть график на котором можно выбирать диапазон например с 2010-1-01 по 2020-2-02 . Я попытался сделать чтоб по нажатию на кнопку забивалась конкретная дата типа с 2015-1-10 и по нажатию на button должна по идее забиваться сюда  pointStart:Date.UTC(YY,MM,DD) вот такая дата var YY = 2015 ;var MM = 1 ;var DD = 10 ; но ничего не происходит ( .

 var interval = 3600 * 1000 ;
    var YY = 2014 ;
    var MM = 1 ;  // 0-11
    var DD = 5 ;  // 1-31

    var chart11 = new Highcharts.StockChart({
        chart: {
        backgroundColor: '#ffffff',
    shadow: {
            color: 'rgba(0, 0, 0, 0.08)',
            offsetX: 5,
            offsetY: 5,
            opacity: '0.5',
            width: 10
        },
    renderTo: "chart1",
    type: "spline"
  },
    rangeSelector: {buttons: [{type: 'day',count: 1,text: 'Д'}, {type: 'week',count: 1,text: 'Н'}, {type: 'month',count: 1,text: 'М'}, {type: 'year',count: 1,text: 'Г'}],buttonTheme: {
                visibility: 'hidden'
            },},
    rangeSelectorTo :{enabled: false,}    ,

    time: {

        useUTC: true},
    title: {
    style:{"fontSize": "27px"} ,
    text: "AG-4"
           },
    subtitle: {text: ''},
    xAxis: {
    //allowDecimals: false,
    //tickInterval: 1 * 3600 * 1000,
    tickInterval: 3600 * 1000*24*30,
    type: 'datetime',
    max: Date.UTC(2020, 0, 1),
    dateTimeLabelFormats: {
    hour: '%H:%M',
    day: '%e. %b',
    week: '%e. %b',
    month: '%b \'%y',
    year: '%Y',
    //format: '{x:%H:%M}',
    //day: '%b %e',
    //week: '%b %e'
       },
          },
    yAxis: {
     "fontSize": '21px',
                offset: 45,
                color: '#c9c7c7',
                //min: 0,
                //max: 100,
                //tickInterval: 20,
                labels: {
                formatter: function () {return (this.value > 0 ? '' : '') + this.value + '%';},
                style: {fontSize: '14px',fontFamily: 'Verdana, sans-serif',fontWeight: 'bold',}
                       },
                title: {text: ''}
            },

      exporting: {enabled: true,buttons: {contextButton: {menuItems: ['downloadCSV', 'downloadXLS']}}},
      credits: {enabled: false},
      tooltip: {
        shared: true,
        useHTML: true,
        headerFormat: '{point.key}
',
        pointFormat: '
{series.name}: 	' +
            '{point.y} %
',
        footerFormat: '
',
        valueDecimals: 2
            },
  legend: {enabled: true},
  plotOptions: {
      series:{
          useUTC: true,
          pointStart:Date.UTC(YY,MM,DD),
          pointInterval: interval
          //tickInterval: 24 * 3600 * 1000 ,
          //pointEnd: Date.UTC (2018, 1, 10),
      },

    area: {
      connectNulls: false,
      stacking: "normal",
      lineColor: "#666666",
      lineWidth: 1,
      marker: {
        lineWidth: 1,
        lineColor: "#666666"
      }
    }
  },
  series: [
    {color: 'rgba(172,199,255,255)', name: "-10",dataGrouping: {enabled: true},
      data: [34, 21, 20, 20, 19,34, 21, 20, 20, 19,43,87]  },
    {color: 'rgba(188,255,218,255)', name: "10-12,5",dataGrouping: {enabled: true},
      data: [80, 30, 10, 45, 77,80, 30, 10, 45, 77,23,77] },
    {color: 'rgba(200,240,255,255)', name: "12,5-14",dataGrouping: {enabled: true},
      data: [12, 34, 89, 55, 23,12, 34, 89, 55, 23,54,98] },
    {color: 'rgba(255,191,191,255)', name: "14-18",dataGrouping: {enabled: true},
      data: [88, 12, 56, 94, 22,88, 12, 56, 94, 22,34,34] },
    {color: 'rgba(227,208,241,255)', name: "+18",dataGrouping: {enabled: true},
     data: [10, 30, 28, 40, 299,10, 30, 28, 40, 299,44,54] },
  ],

    },);

    $('#button').click(function() {

    var YY = 2015 ;
    var MM = 1 ;  // 0-11
    var DD = 10 ;  // 1-31
    alert ('132');

    chart11.series[0].setData([50, 50, 20, 20, 50,50, 20, 20, 20, 50,50,50],true);
    chart11.series[0].apply(this.pointStart[Date.UTC(2015,1,1)]);

    });

 <button id="button" style="position:absolute;left: 1400px;top:180px;z-index: 99999">дата</button>


text:
Q: Parent fields are all nil when accessed by child (embedded 1-n) I have a 1-n relationship defined as follows:
class User
  field :email, type: String
  embeds_many :papers
end

class Paper
  embedded_in :user
end

If I try and access the parent fields (user) from the child (paper) like so:
User.all.map(:papers).flatten.first.user.email

Then I get nil :(
Accessing like this works fine though:
User.all.first.papers.first.user.email

A: It's a mispelling lire report on comment. To call a method on a map,you need use & before your symbol.
Try:

User.all.map(&:papers).flatten.first.user.email


text:
Q: SELECT one column if the other is null I want to select a2.date if it's there, but if it's NULL I want to select a1.date (a2 is being left-joined). This:
SELECT a2.date OR a1.date
       ...

Simply returns a boolean result (as one would expect), how do I get the actual value of the non-null column though? (a2.date is preferred, but if it's null then a1.date)

A: Use a CASE statement for the select.
SELECT CASE WHEN a2.date IS NULL THEN a1.date
    ELSE a2.date END AS mydate

A: Check out the COALESCE function.
Takes a variable number of arguments and returns the first non-null one. It works fine with joins.

A: SELECT COALESCE(a2.date, a1.date) ...

A: The ANSI means is to use COALESCE:
SELECT COALESCE(a2.date, a1.date) AS `date`
   ...

The MySQL native syntax is IFNULL:
SELECT IFNULL(a2.date, a1.date) AS `date`
   ...

Unlike COALESCE, IFNULL is not portable to other databases.
Another ANSI syntax, the CASE expression, is an option:
SELECT CASE
         WHEN a2.date IS NULL THEN a1.date
         ELSE a2.date
       END AS `date`
   ...

It requires more direction to work properly, but is more flexible if requirements change.


text:
Q: load_dotenv .env not working when running pyinstaller executable from path search I have this small python .exe created with pyinstaller that use load_dotenv's .env to load in some environment variables like so:
It runs perfectly when I run the executable directly. For example by doing  .\auto-log.exe from the program directory
Then I added the program path to the Path environment variable so that I run it anywhere by entering the executable's name auto-log. Windows 10 manages to find my program correctly but the environment variables in the .env file aren't get loaded and return None
I'm wondering what's causing the issue and how I can fix this.

A: After an hour or 2 of debugging, I realized the process by doing the path search method, started in a different directory rather than the actual location where the executable is located.
C:\Users\{USER}\AppData\Local\Temp\{TEMP-DIR}

Thus, the load_dotenv couldn't find the relative .env


text:
Q: What are the specific steps to enable the ZeroMQ extension for PHP 7.3? I am trying to enable the ZeroMQ extension for PHP on Windows.
I've got a PHP 7.3 ZTS installation on my x64 Windows 10. Since the official zeromq/php-zmq is no longer maintained, I've tried using the latest release from alexat/php-zmq, but to no avail. This is what I tried doing:

*

*Download and extract the latest ZeroMQ release.

*Copy libzmq.dll to php7.3.x and to php7.3.x/ext.

*Download and extract the php-zmq extension.

*Copy php_zmq.dll to php7.3.x/ext.

*Append extension=zmq to my php.ini (which I've gotten from php --ini).

Subsequent php -v tells me that PHP Warning: PHP Startup: Unable to load dynamic library 'zmq' (tried: php7.3.x\ext\zmq (...), php7.3.x\ext\php_zmq.dll (The specified module could not be found.)) (emphasis mine). I have also tried modifying extension_dir, but it does point to the correct directory.
Prompted by the startup warning, I've tried altering php.ini to extension=zmq123456, which certainly did not exist in the extension directory, however PHP greeted me (correctly, this time around) with the same warning.
Some have suggested mine to be a duplicate of another question, however in my case PHP is incorrectly acting like the extension library php_zmq.dll is not even present where expected, while it clearly and verifiably is. Can you see the problem and perhaps describe comprehensively, how I should properly enable the ZeroMQ extension?


text:
Q: Java Multi-threaded Client Server application using MySQL database I am having a problem with the following Threaded Client Server program. All it should do is get values from text fields and on button press to save the data to the SQL db table. While I build everything it all builds successfully but the ClientGUI (swing) will not open. I believe my problem is in the the ConnectionCW class but cannot figure out what exactly I am supposed to do in the void run. Could you take a look and advice me on how to change the ConnectionCW to work fine? Thanks in advance! The code is down here:
Servercode:
package networkclientserver;

import java.io.*;
import java.util.*;
import java.net.*;

public class Server
 {

public static void main(String[] args) throws Exception
{
    int connectionCount = 0;  // Count of clients connecting
    Thread connThread;
    System.out.println("Server starting");

    try
    {
        ServerSocket ss = new ServerSocket(2000);
        while (true)
        {
            Socket s = ss.accept();
            // Network n;
            connectionCount++;
            System.out.println("Connection " + connectionCount + " made");

            //Create and start thread to process client requests
            connThread = new Thread(new ConnectionCW(s)
            {
            });
            connThread.start();
        }
    } catch (IOException e)
    {
        System.out.println("Trouble making a connection" + e);
    }
}

}

ClientGUI:
package networkclientserver;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import javax.swing.JComponent;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ClientGUI extends javax.swing.JFrame
  {

ObjectInputStream ios = null;
ObjectOutputStream oos = null;
Socket s;

public ClientGUI()
{

    initComponents();
    try
    {

        this.s = new Socket("127.0.0.1", 2000);
        this.ios = new ObjectInputStream(s.getInputStream());
        this.oos = new ObjectOutputStream(s.getOutputStream());

    } catch (IOException e)
    {
        System.out.println("Error connecting with the Server  " + e);
    }

       }

public static void main(String args[])
{

            ClientGUI gui = new ClientGUI();
            gui.setVisible(true);

}

  }

ConnectionCW:
 package networkclientserver;

 import java.io.*;
 import java.util.*;
 import java.net.*;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.util.logging.Level;
 import java.util.logging.Logger;

 class ConnectionCW implements Runnable
 {

private Socket s;

ConnectionCW(Socket s)
{
    this.s = s;

}

public void run()
{

    try
    {
        this.insertIntoTable();
    } catch (Exception ex)
    {
        Logger.getLogger(ConnectionCW.class.getName()).log(Level.SEVERE, null, ex);
    }
}  // end of method run*/

public void insertIntoTable() throws Exception
{

    ObjectInputStream oois = new ObjectInputStream(this.s.getInputStream());
    Network netW = (Network) oois.readObject();

    try
    {

        Connection conn = getConnection();
        PreparedStatement create = conn.prepareStatement("INSERT INTO datatopology (numberNodes,numberHubs,numberSwitches,topologyStructure,country,status) VALUES ('" + netW.getNNodes() + "','" + netW.getNHubs() + "','" + netW.getNSwitches() + "','" + netW.getTopology() + "','" + netW.getCountry() + "','" + netW.getStatus() + "')");
        create.executeUpdate();
        oois.close();

    } catch (Exception e)
    {
        System.out.println(e);
    } finally
    {
        System.out.println("Function complete!");
    }

}

public Connection getConnection() throws Exception
{
    try
    {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/networkstopology";
        String username = "user";
        String password = "pass";
        Class.forName(driver);

        Connection conn = DriverManager.getConnection(url, username, password);
        System.out.println("Connected to MySQL!");
        return conn;

    } catch (Exception e)
    {
        System.out.println(e);
    }
    return null;
}

 }


text:
Q: odoo calculate age from a date field and today date I want to get an age between a field and today date
from openerp import models, fields, api, _
from openerp import SUPERUSER_ID
from datetime import date

class report_purchase_stock(models.Model):
_name='report.purchase.stock'

etaw_update = fields.Date('ETA Warehouse') // 2022-01-24
etaw_age = fields.Char('Days in Warehouse')

I have tried something like this from the forum but it return empty
@api.onchange('etaw_update')
def set_age(self):
    for rec in self:
        if rec.etaw_update:
            dt = rec.etaw_update
            d1 = datetime.strptime(dt, "%Y-%m-%d").date()
            d2 = date.today()
            rd = relativedelta(d2, d1)
            rec.etaw_age = str(rd.years) + ' years'

What I want is something like 1 month 14 days

A: I assume that etaw_update is a date where the product entering warehouse for the first time, and etaw_age is the total days where that product has been stored. Is that right?
If that so, you may want to define a current_date variable which will get the todays date, and then you can subtract that current_date with etaw_update
@api.onchange('etaw_update')
  def set_age(self):
    for rec in self:
     current_date = date.today()
     date_in_your_field = rec.etaw_update

     rec.etaw_age = current_date - date_in_your_field
     print(str(rec.etaw_age))

Please let me know if this what you need

A: Add this code at beginning :
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta


text:
Q: difference between continue and quit in Emacs Lisp debugger (progn
  (print 11)
  (/ 1 0)
  (print 22)
  (/ 2 0)
  (print 33))

When I press C-M-x on that expression, Emacs invokes debugger when it fails at (/ 1 0). When I press c for continue instead of q for quit, debugger still exits without executing (print 22) or (/ 2 0). The only difference here is that c exits with the message
progn: Arithmetic error

What is an example code where c and q make big difference and when should I type c rather than q?

A: The difference can be shown in any code that does not stop the execution, i.e. does not contain an error (for example, when called by debug).

A: The difference is easiest to see when you use debug-on-signal.  With this setting, the debugger gets called when an error is signalled, even if that error is handled by an enclosing condition-case.  In such a situation c will continue the normal execution (i.e. signal the error, which in turn causes the handler code to be run, which may then continue execution normally).

A: At first it seemed to me like a very obvious question,
but after trying to build an example, I actually had to look in the info.
So let me summarize what I've clarified for myself:
c in edebug is not the same as c in gdb.
This one just stops for one second at each breakpoint and eventually quits.
I don't see at the moment how it can be useful to anyone.
The equivalent is instead g: this one will continue until next breakpoint
and stop there.
Here's a code example:
(defun foo ()
  (setq x (loop for i from 1 to 100
             collecting (* i i)))
  (setq y (nth 5 x))
  (incf y))

(foo)

To edebug it:

*

*Paste this code into *scratch*

*Move point inside foo and C-u C-M-x (calls edebug-defun)

*Move point to y in setq y and M-x edebug-set-breakpoint

*Move point to the closing paren in (foo) and C-j

*You're now in edebug. Here you could do step 3 with the shortcut b
instead of M-x ...

*You'll find that proceeding with SPC is tedious, since it will
move though each statement of the loop each time.

*But if you press g you'll skip past the whole loop, ending up
in the statement that you're supposedly interested in.

A: Another difference is with respect to recursive edit. For example, I could invoke query-replace and then enter recursive edit and then type (/ 1 0) and evaluate it to enter debugger. Now if I press q, we are back to top level and no longer running query-replace. But if I press c instead, I am still inside recursive edit.
Update another difference. While in debugger, c is bound to debugger-continue which is a wrapper around exit-recursive-edit
and q is bound to top-level. That means any difference known about exit-recursive-edit vs top-level applies. See Recursive Edit - Emacs Manual for difference.
Here's an example adapted from an example in Recursive Editing - Emacs Lisp  Manual to test differences.
(defun simple-rec ()
  (forward-word 1)
  (message "111")
  (debug)
  (message "222")
  (forward-word 1))


text:
Q: XML parsing in VBA I am having troubles parsing XML returned from an API.  My main point on this is to get the "used" and "limit" properties of one of the nodes (with xPath).
For now I don't even manage to explore the whole XML tree, so here I come asking for help
The returned XML looks like this:
 <?xml version="1.0" encoding="UTF-8"?>
<QueryResultRecords xmlns="http://www.xmlns.loc/sub" type="application/some.app.query+xml" href="https://my.api.call.com/query?has_cheezburger" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.xmlns.loc/sub http://my.api.address.com/schema/master.xsd">
    <OnlyNodeType Name="name1" link="hhttp://my.api.address.com/a5d11b73dffe" Used="240640"  Limit="0"  />
    <OnlyNodeType Name="name2" link="http://my.api.address.com/03b11042ccd4"  Used="10240"  Limit="409600" />
    <OnlyNodeType Name="name3" link="http://my.api.address.com/1cf43be18e2e"  Used="11934947"  Limit="20971520" />
</QueryResultRecords>

I roughly understand how XMLDom works in VBA, but searching the web, I managed to write this, which obviously doesn't work...
Dim XMLDOC As MSXML2.DOMDocument60
Dim nodelist As IXMLDOMNodeList
Set XMLDOC = New MSXML2.DOMDocument60
XMLDOC.async = False
XMLDOC.validateOnParse = False
XMLDOC.Load (myhttpresponse)

Namespace = "xmlns: 'http://www.xmlns.loc/sub' "
Call XMLDOC.setProperty("SelectionNamespaces", Namespace)
Call XMLDOC.setProperty("SelectionLanguage", "XPath")

XPath = "/"

Set nodelist = XMLDOC.SelectNodes(XPath)
For i = 0 To nodelist.Length - 1
    Set Node = nodelist.NextNode
    Debug.Print Node.Text
Next i

I think it is an xml-treeing problem (I didn't understand something on XMLDom?) or an xmlns/xsi problem, and there I stuck completely.
Could Anyone help me on this?

A: You must choose a namespace prefix for every namespace you want to use, even if there is no prefix in the XML.
Here I use sub to refer to the http://www.xmlns.loc/sub namespace.
Option Explicit

Sub Test()
    Dim XmlDoc As MSXML2.DOMDocument60
    Dim OnlyNodeType As MSXML2.IXMLDOMElement

    Set XmlDoc = GetXml("https://my.api.call.com/query?has_cheezburger")
    XmlDoc.setProperty "SelectionNamespaces", "xmlns:sub='http://www.xmlns.loc/sub'"

    For Each OnlyNodeType In XmlDoc.SelectNodes("//sub:OnlyNodeType")
        Debug.Print OnlyNodeType.GetAttribute("link")
    Next OnlyNodeType
End Sub

Function GetXml(url As String) As MSXML2.DOMDocument60
    With New MSXML2.XMLHTTP60
        .Open url
        .Send
        Set GetXml = .responseXML
        GetXml.setProperty "SelectionLanguage", "XPath"
    End With
End Function

XML has the convenience facility of default namespaces (namespace declarations without an explicit prefix, like xmlns="http://foo" as opposed to xmlns:foo="http://foo"). This convenience facility does not exist for XPath. Here every namespace reference must be explicit.
As long as the namespace URI matches, you can choose any prefix you like.


text:
Q: hibernate query for fetching entity on multiple collection values I want to fetch an entity that contains two matching collection entities.
public class A {
    long id;
    Set<B> bs;
}

public class B {
    String name;
    String value;
}

If I have the following table data
Table A
ID     Name
1      pluto
2      earth
3      mars

Table B
ID     A_ID     NAME     VALUE
1       1       abc       123
2       1       xyz       789
3       2       abc       456
4       2       xyz       789
5       3       abc       123

I want to fetch all "A's" that has at least 1 B with name='abc' and value='123' AND 1 B with name='xyz' and value='789'.  I want only the A named 'pluto' in this example as 'earth' doesn't have the correct value for "abc" and mars is missing "xyz".
Do I have to use a subselect to do this?

A: you probably want to use a one-to-many association between A and B...
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html#assoc-unidirectional-12m
... afterwards you can find plenty of examples of querying that association, e.g....
HQL and one-to-many queries


text:
Q: How to write javascript code for BMI_Calculator.html? I'm supposed to write javascript code for an html page that will calculate a persons BMI and tell them what it means (the number). The rules of the test were to not change the html on the page, but to just write the javascript code and link it to the html page. That's all. I have copied the html page just in case you guys might wanna have a look at it. Here is what the BMI Calculator is supposed to do using javascript:

*

*Person enters name, selects gender, enters weight and height. The application will calculate the persons BMR, BMI, and tell what it means (i.e. saying "you are too thin", "you are healthy", or "you are overweight").
and it will display an image of a thin, healthy, or overweight person which is a png image.

*If they do not enter a name, an error message prompts them to enter a name. The name must be at least five characters long.

*If they do not select a gender, then an error message prompts them to please select a gender. The gender is represented by a radio button. The user selects male or female.

*If the user does not enter a weight, an error message prompts them to please enter a weight.

*If height is not entered, an error message prompts them to please enter a height.

*If you are a male, you're BMR is calculated as: BMR = 10*(weight+6.25)(height-5)(age+5).

*If you are a female, you're BMR is calculated as: BMR = 10*(weight+6.25)(height-5)(age-161).

*If the BMI is less than 18.5: "you are too thin".

*If the BMI is between 20 to 25: "you are healthy".

*If the BMI is greater than 25: "you are overweight".

Also, please don't put the question on hold or delete it. This is important for me and I need help. If you want help, please don't. It took me a long time to write this question.
Here is the html that I am supposed to write the javascript code for:

  <title> BMI Calculator </title>

BMI Calculator

    <form name="bmiForm" onsubmit="return false;">
      <fieldset>
        <legend>Enter your Details:</legend>
        Name:
        <input type="text" id="user" size="25" required>

        Gender:
        <input type="radio" id="rbMale" name="gender"> Male
        <input type="radio" id="rbFemale" name="gender">Female

        Age:
        <input type="number" id="age" size="10" required>

        Weight(kg):
        <input type="number" id="weight" size="10" required>

        Height(cm):
        <input type="number" id="height" size="10" required>

      </fieldset>

      <button onclick="calculate()">Calculate BMI</button>
      <button type="reset" onclick="clearErr()">Reset</button>

      <fieldset>
        <legend>Result:</legend>
        Your BMR:
        <input type="text" name="bmr" id="bmr" size="18" readonly>

        Your BMI:
        <input type="text" name="bmi" id="bmi" size="10" readonly>

        This Means:
        <input type="text" name="meaning" id="meaning" size="25" readonly>

      </fieldset>

  </form>

And here is the javascript I wrote for it. I know it's horrible. The problem is the code does not work. Nothing works.
 function GenderType() {
   var GenderType = document.getElementsByName("rbMale","rbFemale");

   if(rbMale == "Male") {
     GenderType.innerHTML = "Male";
   } else {
     rbFemale == "Female";
     GenderType.innerHTML = "Female";
   }
 }

 function validate() {
   var name = document.getElementById("name");
   var age = document.getElementById("age");
   var male = document.getElementById("male");
   var female = document.getElementById("female");
   var weight = document.getElementById("weight");
   var height = document.getElementById("height");

   error = false;

   var reName = /^[a-zA-Z ]{5,}$/;
   if (reName.test(name.value) == false) {
     nameError.innerHTML = "Name must be eight letters or more";
     error = true;
   } else {
     nameError.innerHTML = "";
   }

   age = parseInt(age.value);
   if ( isNaN(age)  || age < 0 || age > 65) {
     ageError.innerHTML = "Age must be in range 0-65";
     error = true;
   } else {
     ageError.innerHTML = "";
   }

   weight = parseInt(weight.value);
   if ( isNaN(weight) || weight < 0) {
     weightError.innerHTML = "Weight must be greater than 0";
     error = true;
   } else {
     weightError.innerHTML = "";
   }

   height = parseInt(height.value);
   if (isNaN(height) || height < 0) {
     heightError.innerHTML = "height must be greater than 0"
     error = true;
   } else {
     heightError.innerHTML = "";
   }

   if ( !male.checked & !female.checked) {
     genderError.innerHTML = "Select value";
     error = true;
   } else {
     genderError.innerHTML = "";
   }
 }

 function BMRCalculate () {
   if ( validate()==false ) {
     var GenderType = document.getElementById("rbMale","rbFemale").value;
     var age = document.getElementById("age").value;
     var female = document.getElementById("rbFemale");
     var male = document.getElementById("rbMale");
     var weight = document.getElementById("weight");
     var height = document.getElementById("height");
     var BMIValue = weight/( (height/100)*(height/100) );
     var BMRValue;
     var ThisMeans = document.getElementById("meaning");

     if(GenderType == male) {
       BMRValue = 10*(weight+6.25)*(height-5)*(age+5);
     } else {
       GenderType = female;
       BMRValue = 10*(weight+6.25)*(height-5)*(age-161);
   }

   if (BMIValue<18.5) {
     ThisMeans = "you are too thin";
     document.write(ThisMeans);
   } else if (BMIValue>18.5 && BMIValue<25) {
     ThisMeans = "you are healthy";
     document.write(ThisMeans);
   } else {
     ThisMeans = "You are not healthy";
     document.write(ThisMeans);
   }
 }

A: Mate, @gavgrif gave you some very good tips, but about the code...try to start over and think the problem again.


text:
Q: Firing different linkbuttons in a Repeater and saving the value of each in an arraylist Im using a repeater to display some products in an online shop for a school project. This is how the front end looks with the repeater
<asp:Repeater ID="Repeater1" runat="server"  OnItemCommand="rptList_ItemCommand">
    <ItemTemplate>

      <asp:ImageButton ID="imgProd" runat="server" style="width:150px; height:150px;"    ImageUrl='<%# DataBinder.Eval(Container.DataItem, "productImg")%>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "productID")%>' CommandName="ViewIndividProd"/>

      <asp:Label ID="lbName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "productName")%>' />

      <asp:Label ID="lbUnitPrice" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "unitPrice")%>'/>

      <asp:Label ID="lbRatings" runat="server" Text=''>Ratings</asp:Label>

      <asp:LinkButton ID="linkCart" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "productID")%>' CommandName="AddToCart">Add to Cart</asp:LinkButton>

    </ItemTemplate>
</asp:Repeater>

As you can see I've added on the OnItemCommand in the Repeater tag so that this is invoked whenever one of the buttons(image/link) is fired. That works perfectly fine for both commandname AddToCart and ViewIndividProd. However, i want to store the the productid of a specific item that was invoked by the particular button. In my case now, it only stores ONE productid in the arraylist at a time and 'forgets' the productid that was stored previously when another linkbutton is clicked.
Question How do i make it such that everytime a linkbutton in the repeater is fired, it remembers the productid  pertaining to the linkbutton that was fired and save these ids into the arraylist?
This is how the back end looks
ArrayList cart = new ArrayList();
protected void rptList_ItemCommand(object sender, RepeaterCommandEventArgs e) {
    if (e.CommandName == "ViewIndividProd") {
        Session["productID"] = e.CommandArgument.ToString();
        Response.Redirect("IndividProduct.aspx");
    }
    if (e.CommandName == "AddToCart") {

        string prodid = e.CommandArgument.ToString();
        cart.Add(prodid);
        Session["ShoppingCart"] = cart;
        Response.Redirect("IndividCat.aspx");
    }
    msg.Text = "Shopping cart: " + String.Join(",", cart.ToArray());
}

Your feedback would be much appreciated.

A: You need to understand the Asp.net Page life cycle.
A new instance of your Page object is created on every request.
Values from your input are populated into it.
Your array list is getting recreated every time.
If you want the values to persist, you will have to store your arraylist in the ViewState or the Session
Refer: How to: Save Values in View State
  void Page_Load(object sender, EventArgs e)
  {
    if (ViewState["arrayListInViewState"] != null)
    {
      PageArrayList = (ArrayList)ViewState["arrayListInViewState"];
    }
    else
    {
      // ArrayList isn't in view state, so we need to create it from scratch.
      PageArrayList = CreateArray();
    }
    // Code that uses PageArrayList.
  }

A: We can store comma separated or JSON value in either  Session or hidden variable (If you are on the same page and opening new page in different tab then we can use hidden variable also). So every time an button has been click we can append the product id.


text:
Q: Change href based on requested view I am trying to figure out how i can change links on a _layout.cshtml based on the requested view.
When I am on the Home/Index I want the href to be '#Unhealthy' but when im on any other page, I want it to redirect back to the home page '/Home/Index/#Unhealthy'
When on other page

When on Home/Index

How can I determine the requested view to swap this value?
*Note: I suppose if I cant do it at the server I can always change the values with javascript/jquery

A: use razor if your using MVC note i did this answer because you tagged MVC. If you are doing a MVC application this is by far the best way it can be done, no need for any javascript.
@if (window.location.pathname == "/"){

}
else{

}

if you did want to do it the jQuery way this would work:
Jquery:
$( document ).ready(function() {
  if (window.location.pathname == "/"){
   $("#Link").prop("href", "#Unhealthy")
  }
  else {
    $("#Link").prop("href", "/Home/Index/#Unhealthy")
  }
});

html:

A: @{
    var controller = ViewContext.RouteData.Values["controller"].ToString().ToLower();
    var action = ViewContext.RouteData.Values["action"].ToString().ToLower();
}

A: The answer by Josh Stevens should work using MVC razor code but you could use same code on each page using @Html.ActionLink overloads
A quick search finds this link that is old syntax but concept correct
Without Testing try
@Html.ActionLink("Link Text", "Index", "Home", null, null, "Unhealthy", null, null)


text:
Q: How to make a block for header font styling at customizer via function.php? I am trying to make a section block to change font size at the customizer for the header, I can change font color with generate_css but not able to change size?
my code for changing color is bellow, I need help to make code for changing size.
class header_font_color {
    public static function register ( $wp_customize ) {

        $wp_customize->add_setting('header_emakers_fontcolor', array(
            'default' => 'No'
        ));

        $wp_customize->add_control(new WP_Customize_Control($wp_customize, 'header_emakers_fontcolor-control', array(
            'label' => 'Display the Header Font Color?',
            'section' => 'colors',
            'settings' => 'header_emakers_fontcolor',
            'type' => 'select',
            'choices' => array('No'=> 'No', 'Yes' => 'Yes')
        )));

        $wp_customize->add_setting( 'header_emakers_fontcolor',
            array(
                'default'    => '#000000',
                'type'       => 'theme_mod',
                'capability' => 'edit_theme_options',
                'transport'  => 'refresh',
                'sanitize_callback'  => 'esc_attr',
            )
        );

        $wp_customize->add_control( new WP_Customize_Color_Control(
            $wp_customize,
            'mytheme_header_emakers_fontcolor',
            array(
                'label'      => __( 'Header Font Color', 'customtheme' ),
                'settings'   => 'header_emakers_fontcolor',
                'priority'   => 10,
                'section'    => 'colors',
            )
        ) );

    }

    public static function header_outputt() {
        ?>

        <style type="text/css">

            <?php self::generate_css('.header-main *',  'color', 'header_emakers_fontcolor'); ?>
        </style>

        <?php
    }

    public static function generate_css( $selector, $style, $mod_name, $prefix='', $postfix='', $echo=true ) {
        $return = '';
        $mod = get_theme_mod($mod_name);
        if ( ! empty( $mod ) ) {
            $return = sprintf('%s { %s:%s; }',
                $selector,
                $style,
                $prefix.$mod.$postfix
            );
            if ( $echo ) {
                echo $return;
            }
        }
        return $return;
    }

}

add_action( 'customize_register' , array( 'header_font_color' , 'register' ) );

add_action( 'wp_footer' , array( 'header_font_color' , 'header_outputt' ) );


text:
Q: Using scatterview as a region with Prism throws an exception I'm playing around with Surface and I'm trying to use a scatterview as a module region.
<s:ScatterView cal:RegionManager.RegionName="{x:Static common:RegionNames.MainRegion}"></s:ScatterView>

What happens is that when I run the app, a exception is thrown. With a litle reflection I got to the place where the exception occours:
The DelayedRegionCreationBehavior tries to create the region:
protected virtual IRegion CreateRegion(DependencyObject targetElement, string regionName)
{
    try
    {
        // Build the region
        IRegionAdapter regionAdapter = this.regionAdapterMappings.GetMapping(targetElement.GetType());
        IRegion region = regionAdapter.Initialize(targetElement, regionName);

        return region;
    }
    catch (Exception ex)
    {
        throw new RegionCreationException(string.Format(CultureInfo.CurrentCulture, Resources.RegionCreationException, regionName, ex), ex);
    }
}

Then the ItemsControlRegionAdapter attemps to the set region target ItemsSource:
protected override void Adapt(IRegion region, ItemsControl regionTarget)
{
    bool itemsSourceIsSet = regionTarget.ItemsSource != null;

    #if !SILVERLIGHT
    itemsSourceIsSet = itemsSourceIsSet || (BindingOperations.GetBinding(regionTarget, ItemsControl.ItemsSourceProperty) != null);
    #endif

    if (itemsSourceIsSet)
    {
        throw new InvalidOperationException(Resources.ItemsControlHasItemsSourceException);
    }

    // If control has child items, move them to the region and then bind control to region. Can't set ItemsSource if child items exist.
    if (regionTarget.Items.Count > 0)
    {
        foreach (object childItem in regionTarget.Items)
        {
            region.Add(childItem);
        }
        // Control must be empty before setting ItemsSource
        regionTarget.Items.Clear();
    }

    regionTarget.ItemsSource = region.Views;
}

The scatterview fires a notification of the ItemsSource change and class the ItemsControlHelper is called :
internal static bool IsItemsReadOnly(ItemsControl itemsControl)
{
    IList itemsControlItems = GetItemsControlItems(itemsControl);
    if (!itemsControlItems.IsReadOnly)
    {
        return itemsControlItems.IsFixedSize;
    }
    return true;
}

I think that the GetItemsControlItems returns null, causing the exception.
Any thoughts on how to overcome this situation?

A: I think this is a known issue with ScatterView. We are aware of the issue, and will fix it for the future. If it is the same issue we have seen, it has to do with the ItemsSource of the ScatterView being an IList<foo> or some other "generic" list. If you could change your ItemSource to be a simple IList (not an IList<foo>), I think that would resolve your issue.
I hope this helps,
-Luis Cabrera
Software Design Engineer, Microsoft Surface


text:
Q: Find all elements of quotient ring I am studying the definitions of rings, ideals, and quotient ring, but I have a bit problem to apply the theory into the practice.
I would like to find all elements of quotient ring $\mathbb{Z}[i]/I $ , where $\mathbb{Z}[i] =\{ {a+bi|a, b∈ \mathbb{Z}}\}$ - Gaussian integers and $I$ is ideal $I = (2 + 2i) $.
How one can find all elements of such a quotient ring? What is the algorithm?
Thanks in advance.

A: When you mod out by an ideal, you are essentially introducing an identity that allows you to rewrite some elements in a different form.
In this case, we are beginning with the Gaussian integers -- which have the form $a+bi$ for integers $a$ and $b$ -- and introducing the identity $2+2i=0$.  What that relation does is allow you to replace any occurrence of $2i$ with $-2$.  (Or vice versa).  The effect of this is that you can rewrite any Gaussian integer in the form $a + bi$ where $b$ is either 0 or 1 -- just keep peeling off multiples of $2i$ and exchanging them for $-2$.  For example, in this ring $$4 + 7i = 4 + (1 + 6)i = 4 + i + 6i = 4 - 6 + i = -2 + i$$
So you can think of this ring as having two types of elements in it:

*

*Some elements are of the form $a$, where $a \in \mathbb{Z}$, and
those elements add and multiply just like integers normally do.

*The other elements are of the form $a + i$, where $a \in \mathbb{Z}$,
and those elements combine according to the law $(a+i) + (b+i) = a +
   b - 2$.

To finish this up you should think about what happens when you combine elements of both types.  To make sure you really understand what's going on you should also work out what the multiplication laws are for the various types of combinations.

A: Here $\mathbb{Z}[i]/(2+2i)=\{z\in\mathbb{Z}[i]\,|2+2i=0\}=\{\pm1,\pm i,\pm1\pm i,\pm 1 \mp i\}$, we basically consider $\mathbb{Z}[i]$ under modulo $2+2i$.


text:
Q: the keyboard not show in eclipse emulator I am new to android , I've downloaded the latest version of Eclipse and when I use the edittext, the keypad is not visible, what shall I do??
and this is the result in emulator

and this the setting of emulator

A: The keyboard will not pop up if you are emulating a device with a hardware keyboard.
Goto AVD, select your AVD name and click edit. Edit Android Virtual Device dialog will appear. You can verify this

A: Looks like you are emulating a device which has a hardware keyboard.
You can still use your system keyboard to type data into the EditText on the Emulator for testing purposes.
But if you really want to show the keyboard when you click the EditText, you would need to emulate a device which supports only a soft keyboard. Or otherwise, go to AVD Manager in Eclipse and select your the virtual device that you created. Edit AVD and remove hardware keyboard from the properties of the AVD. That way your emulator would be configured only to support a soft keyboard.

A: Just Check it once in AVD Configuration (Goto ->Windows->AVD manager-->Select AVD-->Edit )whether that Hardware Keyboard is checked or not.if it's not checked that it woudn't come.

A: Here, you have enabled the option for hardware keyboard, you can only see the keyboard if you enabled soft keyboard for you AVD, you can use you physical keyboard for interaction or edit your AVD