text:
Q: How to increase the size of memory used by visual studio? I am using Asp.net with C# to re-ranking a collection image based on their content. But, since I run it, I obtained the following error. While my laptop has 4 GB RAM an 320 GB Hard Disk.
exception of type 'system.outofmemoryexception' was thrown
How can increase RAM for running my program?

A: It is nearly impossible to give you a good answer without seeing some code, but odds are that you are not actually running out of memory.
GDI will throw an OutOfMemoryException for many problems that are not related to memory at all.  It can happen when you try to process a file that isn't actually an image, when the file is corrupt, or when it is an image format that GDI doesn't support.
First, check to make sure that every file or data stream you are processing is actually a real image file.  If you are absolutely sure that the files are valid, and the format is supported by GDI, only then would I start looking at actual memory problems.

A: Two options -
  1) there's a bug in your code and it isn't freeing things up.
  2) 4GB of RAM isn't a lot.
Visual Studio will use as much memory as the laptop has.  But you can "extend" it by enabling Virtual Memory - which I suspect is disabled on your computer.  Virtual Memory (aka paging file) allows the Operating System to use diskspace.
However, it will be slow because RAM is written/read to disk as needed.  You laptop is probably already slow enough.
Your best bet is to buy more RAM for your laptop.  8GB would be good enough (it is what I have on my "play around" laptop) --- 16GB is even better!
To enable virtual memory on Windows 7 - Open the System Properties (search for it or press the  and Pause button).  Select tab "Advanced" and open Performance Settings.  Next select "Advanced" tab and press "Change..."    Automatically Manage Paging and/or "System managed size"  ("No paging file" disables Virtual Memory).
It is disabled by default because of the performance impact.  Your PC will be slower because it reads/writes to disk...which is many times slower than Memory (RAM).  But it works.
If you can - Buy more memory.  You'll be happier.


text:
Q: search function for files I have found a piece of code for Android(Java) which searches sd-card for a given file name(string)
in case that the file exists in sd-card it works fine but if there's no file with that name it will throw null pointer exception.
Can anyone help me please? or give me another alternative?
here's the code:
public File findFile(File dir, String name) {
    File[] children = dir.listFiles();

    for(File child : children) {//the exception is thrown here!
        if(child.isDirectory()) {
           File found = findFile(child, name);
           if(found != null) return found;
        } else {
            if(name.equals(child.getName())) return child;
        }
    }

    return null;
}

Here's the logcat results:
threadid=1: thread exiting with uncaught exception (group=0x400205a0)
FATAL EXCEPTION: main
java.lang.NullPointerException
at ir.zinutech.ssn.Settings.findFile(Settings.java:93)//>> which is "for(File child : children) { "
at ir.zinutech.ssn.Settings.findFile(Settings.java:95)//>> which is "File found = findFile(child, name);//the exception is thrown here!"
at ir.zinutech.ssn.Settings.onClick(Settings.java:69)
at android.view.View.performClick(View.java:2532)
at android.view.View$PerformClick.run(View.java:9293)`end`

A: I think you can modify the code a little. Because not all of recursion case return a value/object.
package vinhnt.example;

import java.io.File;

public class Finder {
    public static void main(String... args) {
        File result = findFileInDirectory(new File("C:/"), "Finder.class");
        if (result == null) {
            System.out.println("File not found");
        }else {
            System.out.println(result.getAbsolutePath());
        }

    }
    public static File findFileInDirectory(File dir, String name) {
        File[] children = dir.listFiles();
        if (children==null) return null;

        for(File child : children) {
            if(child.isDirectory()) {
               File result = findFileInDirectory(child, name);
               if (result!=null) return result;
            } else {
                String fileName = child.getName();
                if(name.equals(fileName)) {
                    System.out.println(fileName);
                    return child;
                }
            }
        }
        return null;
    }
}

A: Thanks to @njzk2 and @VinhNT helping me i figured out how to solve it, the problem was just as @VinhNT said, some folders couldn't be reached so I modified code so that it won't get trapped in such casses, here's how I handeled it:
File sourceFile = findFile(Environment.getExternalStorageDirectory(),"x.apk");
            if (sourceFile==null){
                Toast.makeText(getApplicationContext(),
                        "Couldn't find x.apk file in your SD card",
                        Toast.LENGTH_LONG).show();
                break;
            }

and in search function :
public File findFile(File dir, String name) {
    File[] children = dir.listFiles();
    try{
        for(File child : children) {
            if(child.isDirectory()) {
               File found = findFile(child, name);
               if(found != null) return found;
            } else {
                if(name.equals(child.getName())) return child;
            }
        }
    }catch(Exception e){
        //ignore here because we have no access to this folder
        return null;
    }

    return null;
}

hope it helps other people who get stuck like me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Writing a unit test in c# with an interface? I have this PasswordManager method that I need to create a unit test for, that I'm trying to get the most code coverage for.
I know that you must call the class, but with the interface IPasswordStorage, I'm not sure where to start.
 public class PasswordManager
{
    public interface IPasswordStorage
    {
        string LoadPassword();
        void SavePassword(string pswd);
    }

    public PasswordManager(IPasswordStorage passwordStorage)
    {
        m_EncryptedPassword = DEF_ENCRYPTED_PASSWORD;

        if ( passwordStorage != null )
        {
            m_PasswordStorage = passwordStorage;

            string encryptedPassword = m_PasswordStorage.LoadPassword();
            if ( encryptedPassword != "" )
            {
                m_EncryptedPassword = encryptedPassword;
            }
            else
            {
                m_PasswordStorage.SavePassword(m_EncryptedPassword);
            }
        }
    }

Any help would be appreciated


text:
Q: Disable google analytics when using jquery/jstree I'm building a jstree tree viewer which ultimately will be behind a firewall and I noticed that my script is calling ga.js from an anonymous function in my top level script.
So how do I disable this an an elegant way without digging through all the JavaScript? I don't think the requests will be satisfied when requested, but it will keep asking for it every time the page loads, which is a nuisance.
This is my code, other than the jquery 1.10, jquery cookie and jtree pre 1.0 boilerplate.
    $("#myTree")
    .jstree({
            "json_data" : {
               "ajax" : {
                  "type" : "GET",
                  "url" : "xxxxxxx.cgi",
                  "data" : function (n) {  return { id : n.attr ? n.attr("id") : 0 }; },
                  "success": function (new_data) { return new_data; }
                  "progressive_render" : true
                },
            },
            "plugins" : [ "themes", "json_data", "ui", "checkbox"],
     });

A: Just do a search for ga.js and remove the call manually.  You can comment it out, etc.  Once JavaScript is loaded, it will remain in memory, even removing from it from the DOM, will not remove it from memory.  I found this our recently.  So don't let it load into memory is my point.


text:
Q: Get value of twodimensinal dynamic array from storred pointer adress Im trying to get all values of a dynamic array initialised like this:
      string** structure= new string*[nombre_attributs]();
            for(int j=0; j<nombre_attributs; j++){
                structure[j]= new string[2]();
            }

I can fill it with no problem. I then keep a pointer to this array in an array of pointers called adresses_structures.
How can I now acces the data in this array?
This attempt:
    string  *test = adresses_structures[i];
    cout << "Value:" << *(test+0)<<endl;
    cout << "Value:" << *(test+1)<<endl;
    cout << "Value:" << *(test+2)<<endl;

doesn't work for all values from the second line in the array.
I have tried tons of combinations as
    for(int k=0; k<2;k++){
            for(int j=0;j<2;j++){
      cout << "Truc:" << *(test + k*2 + j)<<endl;

           }
    }

but nothing seem to be able to get the values on the second line.
Thanks for any advice.

A: I assume, that string** structure is the same as adresses_structures here.
When You are doing *(test+1) You move by one byte from test address. You should move by size of string object (check sizeof(string)). Like this: *(test+1*sizeof(string)) or *(test+2*sizeof(string))


text:
Q: Content div showing underneath fixed footer div I am in the process of redesigning a launch page I have.  Currently I have been able to get my footer div to run along the bottom of the page and centered by having a fixed position, which I am using as the menu.  The only issue I am running into, however, is since this footer/menu div has a transparent background, if the content div above it contains more information than can fit on the page, the text is showing underneath the footer/menu div, making the menu unreadable.  Is there any way I can make the content div's height run only to the top of this fixed footer/menu, so the text from the content does not run underneath?
My CSS I have set up like so:
/*Global Settings*/
@import url(http://fonts.googleapis.com/css?family=Istok+Web);

* { margin: 0; outline: medium none; padding: 0; }

body { font: .9em 'Istok Web',sans-serif; background: url('../images/iQwallpaper.jpg') center center no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }

/*DIVS*/
div.header-outer { max-width: 100%; margin: 20px 20px 20px 20px; }

div.menu-outer { width: 100%; background: rgba(255,255,255,0.2); position: fixed; bottom: 0px; }

div.dashboard { max-width: 100%; max-height: 80%; overflow: auto; margin: 0 auto; }

div.left { float: left; }

div.right { float: right; }

/*MENU*/
#centeredmenu { float:left; width:100%; overflow:hidden; position:relative; }

#centeredmenu ul { clear:left; float:left; list-style:none; margin:0; padding:0; position:relative; left:50%; text-align:center; }

#centeredmenu ul li { display:block; float:left; list-style:none; margin:0; padding:0; position:relative; right:50%; }

#centeredmenu ul li a { display:block; margin:0; padding: 20px; color:#FFFFFF; text-decoration:none; }

#centeredmenu ul li a:hover { background:#369; color:#fff; }

#centeredmenu ul li a.dashboard { background: rgba(255,51,51,0.3); }

#centeredmenu ul li a.dashboard:hover { background: rgba(255,51,51,0.6); }

img.icon { height: 200px; display: inline; margin: 25px 50px 25px 50px; }

.white { color: #f2f2f2; }

The HTML in the  tag is as follows:

iQlaunch

v 14.0.0 alpha

a bunch of text to get it to fill the page

Dashboard

Customer Sites

Support Tools

Important Numbers

Helpfiles for Everyone

Helpfiles for Support

Internal Sites

Scheduling

Staff Phone Directory

Training Presentations

Mobile News Sites

Any ideas?

A: Which section has all your content?  I would suggest changing the "overflow" CSS setting to hidden or scroll.
http://www.w3schools.com/cssref/pr_pos_overflow.asp

A: I actually figured out how to do what I wanted.  I ended up creating two parent divs:
div.menu-outer { width: 100%; display:block; position: fixed; bottom: 0px; background: url('../images/iQwallpaper.jpg') center center no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; /*background: rgba(255,255,255,0.2);*/ }

div.menu-inner { background: rgba(255,255,255,0.2); }

The first parent div uses the same background settings as body, and then the second parent div inside the first one applies a transparent colour.  This makes it appear to be transparent from the body, but it really isnt. :)


text:
Q: Using wrong namespace in the Rails controller I have a controller: "/app/controllers/analyst/test_orders_controller.rb".
In this file I have:
class Analyst::TestOrdersController < ApplicationController
  def new
    @order = Order.new
  end
end

But I have an error:
uninitialized constant Analyst::TestOrdersController::Order

But I don't want to use Analyst::TestOrdersController::Order.new, I just want to use Order.new. It is strange. What is the problem?

A: Use ::Order.new
The interpreter is looking for the definition of Order under the Analyst module namespace, this happens because the application models are loaded lazily so the file models/order.rb has not been read yet. Adding the general namespace tells it search for the definition in the Rails paths.
The way to confirm this is to add some random function call in the Order model body and see that it's not executed unless you call ::Order explicitly.

A: try:
module  Analyst
  class TestOrdersController < ApplicationController
    def new
      @order = Order.new
    end
  end
end

I think it has to do with module nesting:
https://cirw.in/blog/constant-lookup


text:
Q: Image size standardisation with scale grid so I have some images that have some sort of color and scale grid placed inside. The grid sizes used when taking photos are all fixed but their sizes may be different in each image.
The final goal is to feed them into machine learning models.
An example image is shown below:

I wonder how I can automatically resize the images so each grid appears to be of the same size shown?
My thoughts:
Detect the crosses shown in the grid, or the black and white boxes, then find their apparent lengths in the image.
Compute the ratio (actual length)/(apparent length) for each image
Rescale the image with this ratio by multiplying all dimensions with this ratio.
However, there is problem of camera distortion. We cannot simply use one ratio to apply to all parts of the image when there is distortion.
I am also not sure how to detect the crosses, or the black and white boxes within the image and obtain their coordinates. It seems that opencv has a findchessboard function but there isn't one specifically for this type of grids. Maybe I should simply detect corners or boxes? Though how can I make sure the boxes are the ones I want and fetch their metadata for computing lengths?
And how can I do camera calibration here?
Appreciate any guidance!


text:
Q: Ionic CSS changes are not persistent when after ionic serve / cordova run android commands I am developping an app on Ionic version 3.9.2, for android tablets. I am working under windows 10 with Visual Studio Code.
In my plaform folder, I have only one device : my physical Android device.
The way I process to fix some CSS details is that I simply launch a
ionic serve command, find my HTML element, and update the main.css file located in the www/build folder (I am not using SCSS).
This works okay until I decide to check if everything looks good on my android tablet : I will launch a cordova run android, and then all the CSS changes are lost - even if I go back on my browser, and launch a new ionic serve.
Please note that I am talking about very basic styles, like colors and font size, not platform-specific styles.
I am not sure this behavior is because of the target device itself; it's looks like the changes will be included successfully on my testing platform until I decide to change the platform, and then the new platform will erase my changes because it's taking over the building process.
Is that possible ?
Maybe should I stop switching between those 2 commands ?
Or maybe should I edit both CSS files (www/build/main.css and platforms/android/assets/www/build/main.css) at the same time, which require a lot more work ?
Any help appreciated.

A: Oh of course, I shouldn't edit this CSS file.
Instead, edit the right SCSS file inside the SRC folder.
Thanks for your answer.


text:
Q: Devise users - show only the false boolean I would like to show in my index the users that are waiting to be approved (false = unnaproved). I followed the steps in this link(controllers and views):
https://github.com/plataformatec/devise/wiki/How-To%3a-Require-admin-to-activate-account-before-sign_in
I have tried many ways, but nothing seems to work. My code is:
controller:
def index
if params[:approved] == "false"
    @users = User.find_by_approved(false)
else
   @users = User.all
end

end
View index
<% @users.each do |users| %>

                <%= users.name%>
                <%= users.email %>
                <%= users.approved %>
                <%= link_to "Aprobar", desaprobado_path(users) %>

            <%end%>

The index show me all the users (false and true), not only the false ones.
Any idea? thanks! greetings from Chile and excuse my english.


text:
Q: How to use doxygen to produce a pdf with custom latex stylesheet and commands? How to use doxygen to produce a pdf with custom latex stylesheet and commands ?
I need to document this code :
~\doxygenLaTex> more main.cpp
#include <iostream>
//! \page MainPage Main program
//! This program is meant to say hello!
int main() {std::cout << "Hello World!"; return 0;}

I need to get a pdf document with my custom style mystyle.sty which includes custom LaTex commands, like \mytable, I need to use inside the doc :
~\doxygenLaTex> more mystyle.sty
\NeedsTeXFormat{LaTeX2e}[1999/01/01]
\ProvidesPackage{mystyle}[2018/05/28]

\newcommand*{\mytable}{%
  \begin{tabular}{ll}
    1 & 2 \\
    3 & 4 \\
  \end{tabular}
}

\endinput

So I look for how to use doxygen for that :
~\doxygenLaTex> ls
Doxyfile main.cpp mainpage.dox mystyle.sty

~\doxygenLaTex>  more .\mainpage.dox
//!
//! \mytable
//!
//! \page MainPage
//!

~\doxygenLaTex> grep LATEX_EXTRA_STYLE .\Doxyfile
# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
LATEX_EXTRA_STYLESHEET = mystyle.sty

~\doxygenLaTex> grep ALIASES .\Doxyfile
ALIASES                = "mytable=\\mytable"

Despite reading the doc, it didn't work: I get command as text ! Running doxygen; cd latex; make pdf; AcroRd32.exe refman.pdf gives :

I googled this and found Doxygen: include custom latex command or How to get Doxygen to recognize custom latex command which unfortunately didn't help me.
Tried a bit more stuffs, but did not work either :
~\doxygenLaTex> git diff
diff --git a/Doxyfile b/Doxyfile
-ALIASES                = "mytable=\\mytable"
+ALIASES                = "mytable=\mytable"

~\doxygenLaTex> git diff
diff --git a/Doxyfile b/Doxyfile
-ALIASES                = "mytable=\\mytable"
+ALIASES                = "mytable=@mytable"

The problem seems to be I get this kind of things :
~\doxygenLaTex\latex> more .\_main_page.tex
This program is meant to say hello!

\textbackslash{}mytable

But not
~\doxygenLaTex\latex> more .\_main_page.tex
This program is meant to say hello!

\mytable

What did I miss ?
Additional question : is there a way to not use doxygen.sty but really only mystyle.sty to avoid any kind of conflicts ?
~\doxygenLaTex\latex> grep usepackage refman.tex
\usepackage{doxygen}
\usepackage{mystyle}

Franck
Note : Windows 10, doxygen 1.9.1
EDIT
When googling before posting, I tested \latexonly. This
~\doxygenLaTex> git diff
diff --git a/Doxyfile b/Doxyfile
-ALIASES                = "mytable=\\mytable"
+ALIASES                = "\\latexonly mytable=\\mytable \\endlatexonly"

Or this
~\doxygenLaTex> git diff
diff --git a/Doxyfile b/Doxyfile
-ALIASES                = "mytable=\\mytable"
+ALIASES                = "\latexonly mytable=\\mytable \endlatexonly"

was not working. But, indeed, it turns out this
~\doxygenLaTex> git diff
diff --git a/mainpage.dox b/mainpage.dox
-//! \mytable
+//! \latexonly \mytable \endlatexonly

does work and produce almost the result I expected:

But now I have another problem : the real \mytable is no table and needs to be set not here :
~\doxygenLaTex\latex> more .\_main_page.tex
This program is meant to say hello!

 \mytable

But actually here
~\doxygenLaTex\latex> more .\refman.tex
\begin{document}
 \mytable

Is there a way to locate LaTex commands here ? And ideally to not use doxygen.sty but really only mystyle.sty to avoid any kind of conflicts ?

A: When I understand it correct you want to use the LaTeX command \mytable in your LaTeX output / resulting pdf.
Most steps done are correct thought the problem is that \mytable is a LaTeX command and not a doxygen command, so you have to make it known in the doxygen parsed comment.
For this there are a few possibilities:

*

*the \latexonly ... \endlatexonly i.e. in the comment add:
  \latexonly
  \mytable
  \endlatexonly

*use it as a formula
\f[ \mytable \f]

Of course you can pack the above snippets in a dedicated ALIASES.
So all in all I used:
Doxyfile
LATEX_EXTRA_STYLESHEET = mystyle.sty

main.cpp
#include <iostream>
/** \page MainPage Main program
 * This program is meant to say hello!
 *
 * \latexonly
 * \mytable
 * \endlatexonly
 *
 * \f[ \mytable \f]
 */
int main() {std::cout << "Hello World!"; return 0;}

mystyle.sty
\NeedsTeXFormat{LaTeX2e}[1999/01/01]
\ProvidesPackage{mystyle}[2018/05/28]

\newcommand*{\mytable}{%
  \begin{tabular}{ll}
    1 & 2 \\
    3 & 4 \\
  \end{tabular}
}


text:
Q: In Pyspark, what happens when you groupBy the same column as you used in partitionBy? I have a dataset that was partitioned by column ID and written to disk. This results in each partition getting its own folder in the filesystem. Now I am reading this data back in and would like to call groupBy('ID') followed by calling a pandas_udf function. My question is, since the data was partitioned by ID, is groupBy('ID') any faster than if it hadn't been partitioned? Would it be better to e.g. read one ID at a time using the folder structure? I worry the groupBy operation is looking through every record even though they've already been partitioned.

A: *

*You have partitioned by ID and saved to disk

*You read it again and want to groupby and apply a pandas udf

It is obvious the groupby will look through every record, and so will most functions. But using a pandas_udf which groupby("ID") is going to be expensive because it will go through an unnecessary shuffle.
You can optimize performance by using groupby spark_partition_id() since you have already partitioned by the column you want to groupby on.
EDIT:
If you want file names, you can try:
from  pyspark.sql.functions import input_file_name

df.withColumn("filename", input_file_name())


text:
Q: Checking linear independence using coordinates If we want to check if some vectors are linearly independent we could get their coordinates relatively to some basis we know and check if the vectors formed by these coordinates are linearly independent; nice and short - if $[ \{ v_{1},v_{2},...,v_{n} \} ]_{B_{1}}$ are linearly independent, where $B_{1}$ is some basis, then $ \{ v_{1},v_{2},...,v_{n} \}$ are independent.
I'm sorry for not being quite eloquent, but the truth is I'm not sure about this and I can't understand why it works. I will leave an example.
Let $\mathbb{P}_{2}$ be the space formed by all polynomials with degree two or less. Let's consider the following vectors:
$$v_{1} = 1;\\ v_{2} = 2+x;\\ v_{1} = 3 + x^{2} $$ We want to check if they span the space, namely if they form a basis for $\mathbb{P}_{2}$.
So to solve this we actually start by building the coordinates vectors relatively to the standard $\mathbb{P}_{2}$ basis (B = {1, x, $x^{2}$}):
$[v_{1}]_{B} = \begin{bmatrix}
1\\
0\\
0\\
\end{bmatrix}, [v_{2}]_{B} = \begin{bmatrix}
2\\
1\\
0\\
\end{bmatrix}, [v_{3}]_{B} = \begin{bmatrix}
3\\
0\\
1\\
\end{bmatrix}$
If these vectors form a basis for $\mathbb{R}_{3}$$ ^{*}$, so does the original ones for $\mathbb{P}_{2}$. I can't understand why is that. I would really appreciate any answer in advance.
*to check that we would then proceed to build a matrix, let's called it A, with the columns being respectively $[v_{1}]_{B},[v_{2}]_{B} \ and \ [v_{3}]_{B}:$
$$A = \begin{bmatrix}
1&2 &3\\
0&1 &0\\
0&0 &1
\end{bmatrix}$$ and check if this matrix is invertible. Why do we check if the matrix is invertible?

A: Matrix A is invertible if and only if $Ax = 0$ implies $x=0$ (clearly $A^{-1}(Ax) =x$). Write $Ax$ out as
$$\pmatrix{a_{1,1}&a_{1,2}&\cdots&a_{n,n}\\a_{2,1} & a_{2,2} &\cdots &a_{2,n}\\\vdots & \ddots & &\vdots\\\\a_{n,1}&a_{2,n}&\cdots&a_{n,n}}\pmatrix{x_1\\x_2\\\vdots\\x_n} =\\= x_1\pmatrix{a_{1,1} \\ a_{2,1} \\\vdots \\a_{n,1}} + x_2\pmatrix{a_{1,2} \\ a_{2,2} \\\vdots \\a_{n,2}} +\cdots+ x_n\pmatrix{a_{1,n} \\ a_{2,n} \\\vdots \\a_{n,n}}$$
and observe that $Ax$ is simply a linear combination of the columns of $A$. So $Ax$ is zero if and only if the linear combination of its columns according to coordinates of $x$ is zero. Do you see why the invertibility of $A$ is equivalent to the independece of its columns?
Furthermore, linear independence does not depend on the choice of basis. A set of vectors is linearly independent if and only if they are linearly independent in any other basis. Is that clear after seeing the above equivalence?
Edit: wrote it out.


text:
Q: Manipulations of Euclidean domains I am trying to answer the following question

For (a) I have said that a and ab are in the ring R, by the definition of a ring. Therefore, by the definition of a Euclidean domain a=abq+r. As we are told that r is non-zero, we know that $\delta(r)<\delta(ab)$.
For (b) I am less sure how to prove this. We know that $\delta(r)<\delta(ab)$ and $\delta(ab)\ge\delta(b)$, but I'm not sure how to show what is required.

A: For a), you are not given that $r \neq 0$, you need to show this. By definition of an Euclidean domain, you can find $q,r \in R$ but either $r=0$ or $\delta(r) < \delta(ab)$. Suppose $r=0$, then $a=abq$ which implies since $a \neq 0$ and you are in an integral domain that $1=bq$, but that means $b$ is invertible (a contradiction). So $r \neq 0$.
For b), we have $r=a-abq=a(1-bq)$ so $\delta(a) \leq \delta(r)$.


text:
Q: How to parse url in  I have html code on a site:

How to extract "http://img2.site.ru/large/120000/129102-3.jpg" with nokogiri gem?
P.S. Nokogiri is parsing element :
[#<Nokogiri::XML::Element:0x42c1ad8 name="a" attributes=[#<Nokogiri::XML::Attr:0x42c1a7e name="alt" value="Кроссовки adidas. Цвет черный. Категории: Женская обувь, Лучшие отзывы, Кеды, кроссовки, ботинки. Вид 1.">, #<Nokogiri::XML::Attr:0x42c1a74 name="class" value="enabledZoom">, #<Nokogiri::XML::Attr:0x42c1a6a name="href" value="http://img2.site.ru/big/120000/129102-1.jpg">, #<Nokogiri::XML::Attr:0x42c1a60 name="rel" value="zoom-id:Azoom;zoom-width:450;zoom-height:598;zoom-distance:10;zoom-position:right;opacity:50;">, #<Nokogiri::XML::Attr:0x42c1a4c name="rev" value="http://img2.site.ru/large/120000/129102-1.jpg">] children=[#<Nokogiri::XML::Element:0x42c0ee4 name="img" attributes=[#<Nokogiri::XML::Attr:0x42c0e94 name="src" value="http://img2.site.ru/tm/120000/129102-1.jpg">, #<Nokogiri::XML::Attr:0x42c0e8a name="class" value="current">]>]>]

A: You can use the at method if you know the  tag you want is in the first  tag:
doc.at('a img')['src'] => "http://img2.site.ru/tm/120000/129102-3.jpg"

If it's not, then you'll need to isolate the  or the . I'd probably go after the  using something like:
doc.at('a#mt-1334303054133 img')['src'] => "http://img2.site.ru/tm/120000/129102-3.jpg"

If there are multiple  or  tags then your sample isn't good enough and we'd need more information about the HTML you're receiving.


text:
Q: How can I place two views in a single screen using autolayout Constraints I would like to create apps which have 2 views (top & bottom).
The top view is scrollable and contains multiple textfields and labels.
The bottom view is non-scrollable but needs to auto adjust to fit into bottom screen like a keyboard when the screen size is changed (I want it to be usable from iPhone 4 to 6 Plus). The bottom view will contain a custom function button to trigger actions and updates in the top view.
I have this working on Android with LinearLayout, but I'm stuck with iOS.

A: Try to place table view or scroll view in top which will scroll and  a UIView on bottom. make the height of UIView constant and table view or scroll view which you will use in top will change the height according as the screen size. If you got confused the post the comment.
For table view see this tutorial
iOS - Custom table cell not full width of UITableView

Step1 : Place table view and view as below . upper part is table view
  and lower is view

Step2: Place the constraints for view as below
AT first

At second

Step 3: Place the constraints for table view as below

Try and inform me what u got

A: In your case I will suggest to drag all those buttons into a UIView. Then place the buttons with the desired spacing. Select all the buttons and give equal width and equal height constraint. And then give spacing constraints between neighbour buttons or views. And then give constraint for the UIview to the UIViewcontroller


text:
Q: Remove space above table I created a table like this:
{\bf \color{LightBlue} \small repding}
\begin{tcolorbox}[arc=0pt, outer arc=0pt ,colback=ColWhite, colframe = ColWhite]
        \begin{table}[H]
        \begin{tabularx}{\textwidth}{cX}
                     \textcolor{GrayMid}{Code} & \textcolor{GrayMid}{Description} \\
                    [0.3ex]
                    \hline
             \hyperref[fac68b5b180]{RA X} & RA\_O \\ \hline
        \end{tabularx}
    \end{table}
\end{tcolorbox}

But I get an empty line between the heading and the table. Can someone tell me how to get rid of it?

Thanks

A: Use the title={...} etc. options and say top=0pt, for example.
frame hidden is most times better than colframe=white, especially if the background colour isn't white.
\documentclass{article}

\PassOptionsToPackage{x11names,dvipsnames,svgnames}{xcolor}
\usepackage[most]{tcolorbox}
\usepackage{tabularx}
\usepackage{hyperref}

\colorlet{ColWhite}{white}
\colorlet{GrayMid}{black!50}

\begin{document}
\begin{tcolorbox}[enhanced, sharp corners, frame hidden,colback=ColWhite,fonttitle={\bfseries\small}, coltitle={LightBlue}, title={repding},top=0pt]
  \begin{tabularx}{\textwidth}{cX}
    \textcolor{GrayMid}{Code} & \textcolor{GrayMid}{Description} \\
    [0.3ex]
    \hline
    \hyperref[fac68b5b180]{RA X} & RA\_O \\ \hline
  \end{tabularx}
\end{tcolorbox}

\end{document}

Using tabularx= option, which can be used directly in the options, so tcolorbox wraps smoothly around the tabularx environment.
\documentclass{article}

\PassOptionsToPackage{x11names,dvipsnames,svgnames,table}{xcolor}
\usepackage[most]{tcolorbox}
\usepackage{tabularx}
\usepackage{hyperref}

\colorlet{ColWhite}{white}
\colorlet{GrayMid}{black!50}

\begin{document}
\begin{tcolorbox}[enhanced, sharp corners,frame hidden,colback=ColWhite,fonttitle={\bfseries\small}, coltitle={LightBlue}, lefttitle={0pt}, title={repding},top=0pt, tabularx={cX}]
    \textcolor{GrayMid}{Code} & \textcolor{GrayMid}{Description} \\
    [0.3ex]
    \hline
    \hyperref[fac68b5b180]{RA X} & RA\_O \\ \hline
\end{tcolorbox}

\end{document}


text:
Q: Adding condition in Telerik Control There is a grid in which we've two columns

*

*Email

*IsOptin

The value of isOptin could be true or false
So we need to check if Email is isOptin then perform some functionality(which we will write in brackets after Title tag:- Title("here"))
So currently this
columns.Bound(o => o.Email)
               .Title();

is working like picking each email id and performing functionality. Now we need to create a scenario:-
Pick email id and check whether it is Optin or not.
kindly suggest what are the changes or addition need to be done.

A: You can make use of the ternary operator within the ClientTemplate of your bound column to perform a check of the IsOptIn field and display the appropriate field or text repsonse.
Sample below (updated):
columns.Bound(o => o.Email)
    .Title()
    .ClientTemplate("#: data.Email ##: data.IsOptin ? ' (Opt-In)' : '' #");


text:
Q: Determine Charge With Electroscope? You have three separate glass rods, and you know one is positive, one is negative and one is neutral. You also have an electroscope that is positively charged.
How can you determine which rod is positive, negative and neutral?
I think you will be able to determine which rod is negatively charged, as that rod will cause the electroscope leaf to rise. I'm not sure how to differentiate between the positive+neutral though, as both will cause the leaf to collapse. Could you place it next to the negative rod and see which repels?
Essentially it would be great if somebody could explain the actual physics behind the situation. Why will the negative rod cause the leaf to rise and vice versa?
Thanks!

A: I did a google search and found that: When a glass rod is rubbed with a paper towel, the glass becomes positively charged.
Therefore:
1.)ground the electroscope through touching it with you fingers (removing any excess charge); one can assume it is neutral/has no net charged at this point.
2.) touch one of the charged rods to the electroscope. The leaves should rise with an unknown charge.
3.) Vigorously rub the uncharged glass rod with a paper towel to give it a positive charge.
4.) bring the positively charged rod close to the Electroscope. If the leaves are repulsed, then you know that the glass rod of unknown charge was/is of the same charge, and therefore is positively charged. Opposite charges attract. Therfore if the leaves attract one knows that the glass rod of unknown charge was negatively charged.
5.) [check] repeat steps 1-4 to verify that that last rod is of opposite charge.

A: Electrons are able to accelerate more freely then protons within a conductor.  Therefore when a leaf electroscope is negatively induced the charged will move outwards while in a positively charged electroscope the leafs will stay hanging.

A: I think I have a simple, yet correct way for doing this.
Suppose the three rods are A, B and C (with unknown charges.)
Suppose now rod A is positive, If  you bring Rod A to the positively charged electroscope, the electrons on the leaves of the electroscope will be attracted by the positively charged rod and thus will go to the knob. So the leaves will repel more.
Suppose rod B is negative. If you bring Rod B to the positively charged electroscope, the electrons on the knob will repel the negatively charged rod and go on to the leaves. so the leaves will come closer.
Suppose rod C is neutral. If you bring Rod C to the positively charged electroscope, nothing will happen and the leaves will stay as they are (will not move).


text:
Q: Three js in Ionic 2 I'm building an Ionic 2 app, and I'm willing to use three.js with the OBJLoader.
The problem is that nothing is displayed at all, while the .obj is good (I tried 2 .obj), and the texture is also good, as I took them from https://threejs.org/examples/webgl_loader_obj.html (I used the code from this page too, but make it fit into the Typescript behavior)
Here is the result, the canvas is there but not the 3d model
:
I included the three.min.js and OBJLoader.js in my index.html, there is 0 errors excepted this due to the animate callback routine:
HomePage ionViewDidLoad error: Maximum call stack size exceede

The component code is as following :
import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

declare var THREE : any;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  container : any;
  camera : any;
  scene : any;
  renderer : any;
  mouseX : any;
  mouseY : any;
  windowHalfX : any;
  windowHalfY : any;

  constructor(public navCtrl: NavController) {

    this.mouseX = 0, this.mouseY = 0;
    this.windowHalfX = window.innerWidth / 2;
    this.windowHalfY = window.innerHeight / 2;

  }

  init() {
  this.container = document.createElement( 'div' );
  document.getElementById('fuckingcontainer').appendChild( this.container );
  this.camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
  this.camera.position.z = 250;
  //  this.scene
  this.scene = new THREE.Scene();
  var ambient = new THREE.AmbientLight( 0x101030 );
  this.scene.add( ambient );
  var directionalLight = new THREE.DirectionalLight( 0xffeedd );
  directionalLight.position.set( 0, 0, 1 );
  this.scene.add( directionalLight );
  // texture
  var manager = new THREE.LoadingManager();
  manager.onProgress = function ( item, loaded, total ) {
    console.log( item, loaded, total );
  };
  var texture = new THREE.Texture();
  var onProgress = function ( xhr ) {
    if ( xhr.lengthComputable ) {
      var percentComplete = xhr.loaded / xhr.total * 100;
      console.log( Math.round(percentComplete) + '% downloaded' );
    }
  };
  var onError = function ( xhr ) {
    console.log("ERROR");
  };
  var loader = new THREE.ImageLoader( manager );
  loader.load( 'UV_Grid_Sm.jpg', function ( image ) {
    console.log(texture);
    texture.image = image;
    texture.needsUpdate = true;
  } );
  // model
  var loader = new THREE.OBJLoader( manager );
  var that = this;

  loader.load( 'male02.obj', function ( object ) {
    object.traverse( function ( child ) {
      if ( child instanceof THREE.Mesh ) {
        child.material.map = texture;
        console.log(texture.image);
      }
    } );
    console.log(object);
    object.position.y = - 95; that.scene.add( object );
  }, onProgress, onError );
  //

  this.renderer = new THREE.WebGLRenderer();
  this.renderer.setPixelRatio( window.devicePixelRatio );
  this.renderer.setSize( window.innerWidth, window.innerHeight );
  this.container.appendChild( this.renderer.domElement );
  document.addEventListener( 'mousemove', function(event){
    that.mouseX = ( event.clientX - that.windowHalfX ) / 2;
    that.mouseY = ( event.clientY - that.windowHalfY ) / 2;
  }, false );
  //
  window.addEventListener( 'resize', function(event)
  {
    that.windowHalfX = window.innerWidth / 2;
    that.windowHalfY = window.innerHeight / 2;
    that.camera.aspect = window.innerWidth / window.innerHeight;
    that.camera.updateProjectionMatrix();
    that.renderer.setSize( window.innerWidth, window.innerHeight );
  }, false );}

  //
  animate(that) {
  requestAnimationFrame( that.animate(that) );
  that.render();}

  render() {
  this.camera.position.x += ( this.mouseX - this.camera.position.x ) * .05;
  this.camera.position.y += ( - this.mouseY - this.camera.position.y ) * .05;
  this.camera.lookAt( this.scene.position );
  this.renderer.render( this.scene, this.camera );
}

  ionViewDidLoad() {
  this.init();
  this.animate(this);
  }

}

A: You are doing a recursive call with no base case:
    animate(that) {
  requestAnimationFrame( that.animate(that) );
  that.render();}

Check this question for the reason of this error
Try
 animate(that) {
      requestAnimationFrame( that.animate );
      that.render();}


text:
Q: Nodejs, Express mysql always returning ER_BAD_DB_ERROR I'm developing a simple web app with Node.js and Express. I have to query a database using mysql module. Every time I try to query the database it shows up this error:
  code: 'ER_BAD_DB_ERROR',
  errno: 1049,
  sqlMessage: "Unknown database 'moneydb'",
  sqlState: '42000',
  fatal: true

I tried to create e a new database but I have always the same error. Wamp is running. credentials are right beacuse if I navigate to localhost/phpmyadmin i log in with root as username and no password.
I post here the relevant code:
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

index.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');

// connection setup
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'moneydb'
});

// connect to database
connection.connect((err) => {
    if (err) {
        console.log('Not connected to database');
        throw err;
    } else {
        console.log('Connected to database');
    }
});

// make connection global
global.db = connection;

/*
*  Every page we declare here will be under the index path
*  localhost:3000/ will render home page
*  localhost:3000/disheslist will be under the home page path and will render the disheslist
* */

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

/*GET dish list. */
/*render contains views(pug files)*/
router.get('/dishes', function (req, res, next) {
    let query = "SELECT * FROM `dish` ORDER BY id ASC";

    // execute query
    db.query(query, (err, result) => {
        if (err) {
            // we should redirect to an error page maybe
            res.redirect('/');
        }

        if (result) {
            res.render('dishes', {tableData: result});
        } else {
            res.send("Error");
        }
    });
});

module.exports = router;

dishes.pug
doctype html
html
    head
        title = title
        link(rel='stylesheet', href='/stylesheets/style.css')
    body
    table
        thead
            tr
            th id
            th name
            tbody

What's wrong? Thank you!

A: Problem solved.
I checked which port was used from MySql on wamp and I found the 3308 port. I added the port to the configuration before connecting in the index.js and I got it. Code updated here:
index.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');

// connection setup
const connection = mysql.createConnection({
    host: 'localhost',
    port: 3308,
    user: 'root',
    password: '',
    database: 'dbname'
});

// connect to database
connection.connect((err) => {
    if (err) {
        console.log('Not connected to database');
        throw err;
    } else {
        console.log('Connected to database');
    }
});

// make connection global
global.db = connection;

/*
*  Every page we declare here will be under the index path
*  localhost:3000/ will render home page
*  localhost:3000/disheslist will be under the home page path and will render the disheslist
* */

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

/*GET dish list. */
/*render contains views(pug files)*/
router.get('/dishes', function (req, res, next) {
    let query = "SELECT * FROM `dish` ORDER BY id ASC";

    // execute query
    db.query(query, (err, result) => {
        if (err) {
            // we should redirect to an error page maybe
            res.redirect('/');
        }

        if (result) {
            res.render('dishes', {tableData: result});
        } else {
            res.send("Error");
        }
    });
});

module.exports = router;

Thank you all!

A: Looks like user do not have permission on database server. Looking at the error message seems like request is able to reach server however due to insufficient privileges an error is returned by the server.

A: I commented/took the database: '<DB NAME>' out of the object.
const connection = mysql.createConnection({
  user : 'root',
  host : '127.0.0.1',
  //database : '<db name>',
  port: '3306',
  password : '<your password>'
});

A: problem solved - changed port number. mysql db port is 3360 and in index.js port should be 3360.
await createConnection({
  host: "localhost",
    type: "mysql",
    port: 3360,
    database: "graphqlschema1",
    username: "root",
    password: "sksuman",
    logging: true,
    synchronize: false,
    entities: [],
  });

A: Go to terminal in ubuntu in MySQL. Create a database:
CREATE DATABASE yourdatabasename

It will resolve your issue.


text:
Q: Docker and wazuh container installation I am trying to install wazuh as a docker container and then i get this below error after entering docker-compose up. Please help
docker-compose up
[+] Running 12/12
 ⠿ Volume "single-node_filebeat_etc"             Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_queue"              Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_api_configuration"  Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_etc"                Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_logs"               Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_agentless"          Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_var_multigroups"    Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_integrations"       Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_active_response"    Created                                                               0.0s
 ⠿ Volume "single-node_wazuh_wodles"             Created                                                               0.0s
 ⠿ Volume "single-node_filebeat_var"             Created                                                               0.0s
 ⠿ Container single-node-wazuh.manager-1         Created                                                               0.1s
Attaching to single-node-wazuh.dashboard-1, single-node-wazuh.indexer-1, single-node-wazuh.manager-1
Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/run/desktop/mnt/host/wsl/docker-desktop-bind-mounts/Ubuntu/8f7109a4f50746c8c4118dd0092c7a6ca75ad9de4a8aa814d81043cbe98a9002" to rootfs at "/usr/share/wazuh-indexer/config/certs/admin.pem": mount /run/desktop/mnt/host/wsl/docker-desktop-bind-mounts/Ubuntu/8f7109a4f50746c8c4118dd0092c7a6ca75ad9de4a8aa814d81043cbe98a9002:/usr/share/wazuh-indexer/config/certs/admin.pem (via /proc/self/fd/14), flags: 0x5000: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type

i tried to remove the image and added again but still same

A: The error message that can be seen in the output of the docker-compose up command refers to a problem with the certificates in the Wazuh indexer container, specifically with the admin.pem certificate, when the container starts, it does not find said file (the certificates are generated prior to deployment and are mounted in the container through a volume).
Have you previously generated the certificates as indicated in our documentation? If what you are going to do is a single-node deployment, you don't have to configure anything, just run the following command from the single-node directory of the cloned repository:
docker-compose -f generate-indexer-certs.yml run --rm generator

After executing the above command you should have an output like the following:
Cert tool exists in Packages bucket
05/12/2022 13:46:24 INFO: Admin certificates created.
05/12/2022 13:46:24 INFO: Wazuh indexer certificates created.
05/12/2022 13:46:24 INFO: Wazuh server certificates created.
05/12/2022 13:46:24 INFO: Wazuh dashboard certificates created.
Moving created certificates to destination directory
changing certificate permissions
Setting UID indexer and dashboard
Setting UID for wazuh manager and worker

Once generated, run the docker-compose up command and the deployment should succeed.


text:
Q: Could this be a zero-length partition? Recover External HDD I can see my external hdd. I can mount it and see the folders. However, I cannot open the files. I got an error splicing files I/O. that it cannot open file.
I am using Ubuntu 16.04 LTS
I`ve tried thoses command following the answers of the forum:
kubuntu@kubuntu:~$ sudo fsck /dev/sdb1

fsck from util-linux 2.27.1

e2fsck 1.42.13 (17-May-2015)

fsck.ext2: Attempt to read block from filesystem resulted in short read while trying to open /dev/sdb1
Could this be a zero-length partition?

kubuntu@kubuntu:~$  sudo e2fsck -f -b 32768 -y /dev/sdb1

e2fsck 1.42.13 (17-May-2015)

e2fsck: Attempt to read block from filesystem resulted in short read while trying to open /dev/sdb1
Could this be a zero-length partition?

kubuntu@kubuntu:~$ sudo dumpe2fs -f /dev/sdb1 | grep -i superblock

dumpe2fs 1.42.13 (17-May-2015)

dumpe2fs: Attempt to read block from filesystem resulted in short read while trying to open /dev/sdb1
Couldn't find valid filesystem superblock.

kubuntu@kubuntu:~$  sudo mke2fs -n /dev/sdb1

mke2fs 1.42.13 (17-May-2015)

Creating filesystem with 122096389 4k blocks and 30531584 inodes
Filesystem UUID: 30593375-6af1-4668-a808-7730a09dcd9e
Superblock backups stored on blocks:
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
    4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,
    102400000

kubuntu@kubuntu:~$  sudo e2fsck -f -b 32768 /dev/sdb1

e2fsck 1.42.13 (17-May-2015)

e2fsck: Attempt to read block from filesystem resulted in short read while trying to open /dev/sdb1
Could this be a zero-length partition?

kubuntu@kubuntu:~$  e2fsck -f /dev/sdb1

e2fsck 1.42.13 (17-May-2015)

e2fsck: Attempt to read block from filesystem resulted in short read while
trying to open /dev/sdb1
Could this be a zero-length partition?

kubuntu@kubuntu:~$  mke2fs -n /dev/sdb1

mke2fs 1.42.13 (17-May-2015)

Creating filesystem with 122096389 4k blocks and 30531584 inodes

Filesystem UUID: 59e19e76-7f2e-4676-a744-b8f6a9e2fa43

Superblock backups stored on blocks:
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
    4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,
    102400000

kubuntu@kubuntu:~$  e2fsck -f -b 8193 /dev/sdb1

e2fsck 1.42.13 (17-May-2015)

e2fsck: Attempt to read block from filesystem resulted in short read while
trying to open /dev/sdb1
Could this be a zero-length partition?

kubuntu@kubuntu:~$  dd if=/dev/sdb1 of=/disk2/backup-sdb1.img
dd: failed to open '/disk2/backup-sdb1.img': No such file or directory

kubuntu@kubuntu:~$  mkfs.ext4 -n /dev/sdb1

mke2fs 1.42.13 (17-May-2015)

Creating filesystem with 122096389 4k blocks and 30531584 inodes

Filesystem UUID: f0d78289-4e5d-40ee-a771-903ba6cd8151

Superblock backups stored on blocks:
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
    4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,
    102400000

kubuntu@kubuntu:~$  fsck.ext4 -n -b 32768 /dev/sdb1

e2fsck 1.42.13 (17-May-2015)

fsck.ext4: Attempt to read block from filesystem resulted in short read while
trying to open /dev/sdb1
Could this be a zero-length partition?

Any help to guide me to get back my hard drive would be great. Thank you,


text:
Q: How do I escape EJS template code in node.js to be evaluated on the client side? I use node.js/ejs on the server side and backbone.js on the client side.
Both server side and client side use the same templating style.
So the problem is, if I put template code meant for the client inside a template it still get's parsed on the server side.
If found out that something like this works:
<%- "<%= done ? 'done' : '' %\>" %>

However, IMHO this uglifies the code in a way which makes the whole point of using templates useless.
How would you approach this?
Is there a way to define blocks of code inside EJS-templates which do not get parsed like a {literal}-tag used in other templating languages?
Update: For now I use backbone's _.templateSettings to use different delimiters on the client side.
Update: Here's a similar solution in a JSP context: Underscore.js Templates Within JSP

A: The way I have dealt with this is to override the opening and closing tags on node so that the 2 instances of ejs are lookgin for different tags.
On node you can pass in options
{open:'<%',close:'%>'}

In my case I use <% and <@ for my two versions. Then in node ejs template I have something like this (where name is from backbone and everyauth obviously from node):
<% if(everyauth.loggedIn) %>
<@= name @>
<% } %>

A: I assume the question could be read as following because it was this thread Google provide me at first link:
"How I can escape EJS template code delimiter tag only for limited items?"
tl;dr:
Use <%# %> to break the original parsing code (e.g. <<%# %>%= done ? 'done' : '' %<%# %>> will done the following unparsed code <%= done ? 'done' : '' %>)
Long explanation
Imagine a case I decide to change % by ? using { delimiter: '?' } option (that could be the case here, because we want not to use the same has Backbone.js).
Great, that solves your problem. Imagine now later, for some reason, you use your templating system to generate an XML. This XML will start with <?xml version="1.0" encoding="UTF-8"?>.
You will facing the same issue again. What do? You will change the delimiter again? And after that, you will change again? etc. No, for punctual escaping, what we should is just to be capable to say "Not parse this part of the document as EJS".
So a trick is to avoid EJS understand it's an EJS delimiter parser. So avoid it (in our current case) parse <? (or <% in an original case).
So by simply adding <?# ?> to break the parsing, you will add nothing (the # item is for EJS comment) and you will avoid parser to understand <<?# ?>?xml version="1.0" encoding="UTF-8"?<?# ?>>. The output will be <?xml version="1.0" encoding="UTF-8"?>
Conclusion
In a punctual necessity to avoid EJS parsing, you can just trick the parser to produce the output you need by using <%# %> as a delimiter tag breaker.
For sure, probably in your case, you can just use the marked answer because you will use the EJS tag in a lot of cases.

A: Well, the way that I currently approach this is to use require.js with the text plugin; this allows me to include the templates using AJAX during development time and have them all compiled into an optimized/minified single file bundle during deploy time.
Of course, if you don't use require.js for dependency management of the rest of your JS code this doesn't work nearly as well, but I can't stand to do javascript dev without require.js anymore now that I'm used to it anyway.
Alternately, there may be other similar technologies that you could use to solve the same problem.

A: I use backbone.layout.manager on both the client and server side, because I want my templates to be exactly the same.
The way I solved the template delimiter issue was to render the page on the server side, then inject the raw backbone templates.

A: With new ejs you can add a custom delimiter at client side :
https://github.com/mde/ejs#custom-delimiters
eg :
Custom delimiters can be applied on a per-template basis, or globally:
var ejs = require('ejs'),
    users = ['geddy', 'neil', 'alex'];

// Just one template
ejs.render('<?= users.join(" | "); ?>', {users: users}, {delimiter: '?'});
// => 'geddy | neil | alex'

// Or globally
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});
// => 'geddy | neil | alex'


text:
Q: Javascript get the absolute position (in px) of a caret in a input text or textarea I'm trying to develop an autocomplete that actually positions itself underneath the caret position in an input text and/or textarea instead of just underneath the element. A bit like most IDEs.
I'm currently using the Twitter bootstrap typeahead and I'm seeking to modify it.
I prepared a JS BIN if you got an idea: http://jsbin.com/welcome/34949/edit
With basic syntax:
var autocomplete_values=["hello","dude","rubber","ducky"];

      $(".autocomplete").typeahead({
        source:autocomplete_values
      });

Question
How do I get the absolute position in pixels of a caret in an input text and/or a textarea?
I have absolutely no idea where to start.
Thanks in advance for your help.

A: Using absolute positioning and a dummy element, you can accomplish this quite accurately.
The way I approached this is by having a dummy (invisible) inline element containing the current value of the input. Making sure that this element has the exact same font setup, we can easily measure its width, which we can then use to offset the auto-complete value.
Both the input field and the autocomplete element are absolutely positioned in a relatively positioned container, so they overlap. I gave the autocomplete a z-index lower than the input field and made the input's background transparent so auto-complete does not interfere with clicking the input field.
I used text-indent to get the autocomplete text positioned right, but you can also use the left property to actually move the element.
HTML

    <input type="text" id="foo">

CSS
#container { position: relative; }

#foo, #ac, #dummy {
    font-family: monospace;
    font-size: 16px;
}

#foo, #ac {
    position: absolute;
    top: 0;
    left: 0;
}

#foo {
    z-index: 2;
    border: solid 1px black;
    background: transparent;
}

#ac {
    top: 1px;
    left: 2px;
    z-index: 1;
    color: #999;
}

#dummy { visibility: hidden; }

JavaScript
(using jQuery, but should get the point accross)
$('#foo').keyup(function(event) {
    //get autocomplete value
    var autoComplete = dummyAutoComplete($(this).val());

    //if a value is found, show it in #ac and adjust position
    if (autoComplete !== null) {
        //add in value and make visible
        $('#ac').html(autoComplete).removeClass('hidden');

        //dummy gets the same value as the input, to measure its width
        $('#dummy').html($(this).val());

        //add autocomplete text-indent based on dummy width + some adjustmet
        $('#ac').css('text-indent', $('#dummy').outerWidth() + 'px');
    } else {
        //hide autocomplete
        $('#ac').html('').addClass('hidden');
    }
);

I've got an example running on jsfiddle.

A: I would create a hidden inline-block element whose contents mirror that of the textbox.
Pseudo:
myTextBox.onkeyup = function(){
    myInlineContainer.innerHTML = this.value
}

Once you've got that working, you're just a a few measurements and some math away from positioning your intellisense popup box exactly where you want it over your textbox.
For example, you could get the offsetleft for your intellisense box by modding your inline-element width by your input element's width:
intellisenceLeft = (myInlineContainer.offsetWidth % myTextBox.offsetWidth);

Getting the top might be a little tougher, but nothing a little hacking at couldn't solve.


text:
Q: AutoCompleteTextField not recognized as a textfield? My question is, how do I make it so that AutoComplete will allow the user to skip to the next field, or hit the check button to finish entering in the field like normal text fields do? Right now I can not hit the next button to go to the next field or the finish button when entering data
EDIT: Talking about the built in android keyboard buttons not working on auto completes

A: add attribute android:imeOption="actionNext" in your AutoCompleteTextField
if still it is not working then also add attribute android:inputType="text" (text use just for example).


text: Q: Change of electric vector (and hence polarization) of photon after Compton scattering I want to know how the electric vector (polarization) of individual photon changes after Compton scattering. Is that totally a random process, means the photon electric vector orientation change has uniform probability between $0$ to $2\pi$? I know that after Compton scattering the direction of Compton scattered photons have azimuthal asymmetry (probability high in perpendicular to linear polarization direction - if memory serves).


text:
Q: Django select and delete posts I am making a blog based on Django on guides. I have a list of posts that you can change and delete. How to make it possible to select multiple posts and delete? I don't even know which side to approach the problem. All i need is are ways to complete this problem. I want to complete it by myself, but i need some advices about the ways how to do it

A: there are lots of way to do that and it's usually a combination of frontend and backend, but in Django side you can filter rows (with lets say ids) and bulk delete them like this:
Post.objects.filter(id__in=(1, 2, 3, ...)).delete()

in frontend you should figure out a way to pass ids you want as a list to your Django view/api.


text:
Q: Dataframe will directly connect to RDBMS from Executor or it will go through Driver? In Spark Dataframe im looking for following under the hood explanation for optimization.

*

*Data Frames are special type of RDD, it internally contains Row RDDs.  These RowRDDs are spread across the executors.

*When we write these RowRDDs from executors ( especially while running in YARN-CLIENT mode ) the Row RDDs will be transferred from EXECUTOR to DRIVER and DRIVER writes into Oracle using the JDBC connection.(Is this True?)

*When run the same code in YARN-CLUSTER mode, the Row RDDs are written to Oracle directly from Executor.  This could be a faster approach, but available JDBC connection could limit /slow down the process.

I'm not sure this is what happens under the hood kindly validate this and correct me if im wrong. This will impact a big performance factor.
Thanks in advance.

A: Each executor makes its own connection.
val df = (spark.read.jdbc(url=jdbcUrl,
    dbtable="employees",
    columnName="emp_no",
    lowerBound=1L,
    upperBound=100000L,
    numPartitions=100,
    connectionProperties=connectionProperties))
display(df)

In the Spark UI, you will see that the numPartitions dictate the number of tasks that are launched. Each task is spread across the executors and this can increase the parallelism of the reads and writes through the JDBC interface. Look at the upstream guide to look into other parameters that can help with performance such as the fetchsize option.


text:
Q: Buttons not working on Program I am trying to set up the buttons on the following program, but they will not control the program properly.  I am not sure why they are not working.  The reverse button works, but the start and stop buttons do not.
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ch30 extends Application {
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    FanPane fan = new FanPane();

    HBox hBox = new HBox(5);
    Button btPause = new Button("Pause");
    Button btResume = new Button("Resume");
    Button btReverse = new Button("Reverse");
    hBox.setAlignment(Pos.CENTER);
    hBox.getChildren().addAll(btPause, btResume, btReverse);

    BorderPane pane = new BorderPane();
    pane.setCenter(fan);
    pane.setBottom(hBox);

    // Create a scene and place it in the stage
    Scene scene = new Scene(pane, 200, 200);
    primaryStage.setTitle("Exercise15_28"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage

     //Runnable first = new Begin();

     //Thread first = new Thread();

     //t1.start();

        Thread first = new Thread(new Runnable() {
            @Override public void run() {
                while (true) {
                    try {
                        //Pause
                        Thread.sleep(100);

                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    Platform.runLater(new Runnable() {
                        @Override public void run() {

                          fan.move();

                        }
                    });
                }
            }
        });

                first.start();

   //Timeline animation = new Timeline(
      //new KeyFrame(Duration.millis(100), e -> fan.move()));
    //animation.setCycleCount(Timeline.INDEFINITE);
    //animation.play(); // Start animation

    scene.widthProperty().addListener(e -> fan.setW(fan.getWidth()));
    scene.heightProperty().addListener(e -> fan.setH(fan.getHeight()));

   //btPause.setOnAction(e -> first.wait());
    btResume.setOnAction(e -> first.start());
    btReverse.setOnAction(e -> fan.reverse());
  }

  /**
   * The main method is only needed for the IDE with limited
   * JavaFX support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);

  }
}

class FanPane extends Pane {
  private double w = 200;
  private double h = 200;
  private double radius = Math.min(w, h) * 0.45;
  private Arc arc[] = new Arc[4];
  private double startAngle = 30;
  private Circle circle = new Circle(w / 2, h / 2, radius);

  public FanPane() {
    circle.setStroke(Color.BLACK);
    circle.setFill(Color.WHITE);
    getChildren().add(circle);

    for (int i = 0; i < 4; i++) {
      arc[i] = new Arc(w / 2, h / 2, radius * 0.9, radius * 0.9, startAngle + i * 90, 35);
      arc[i].setFill(Color.RED); // Set fill color
      arc[i].setType(ArcType.ROUND);
      getChildren().addAll(arc[i]);
    }
  }

  private double increment = 5;

  public void reverse() {
    increment = -increment;
  }

  public void move() {
    setStartAngle(startAngle + increment);
  }

  public void setStartAngle(double angle) {
    startAngle = angle;
    setValues();
  }

  public void setValues() {
    radius = Math.min(w, h) * 0.45;
    circle.setRadius(radius);
    circle.setCenterX(w / 2);
    circle.setCenterY(h / 2);

    for (int i = 0; i < 4; i++) {
      arc[i].setRadiusX(radius * 0.9);
      arc[i].setRadiusY(radius * 0.9);
      arc[i].setCenterX(w / 2);
      arc[i].setCenterY(h / 2);
      arc[i].setStartAngle(startAngle + i * 90);
    }
  }

  public void setW(double w) {
    this.w = w;
    setValues();
  }

  public void setH(double h) {
    this.h = h;
    setValues();
  }
}

A: This should be done with a Timeline, I know it's your homework and for some crazy reason your homework has been specified to not use a Timeline.  But for anybody else, don't do it this way, just use a Timeline.
That said...
You mention start and stop buttons of which you have none.  I assume start means resume and stop means pause as those are the buttons you do have. So I will answer accordingly.
The easiest way to deal with this is to use a boolean variable to control whether or not the fan is moving.
Define a member of your application:
private boolean paused = false;

In your thread only move the fan if not paused:
Platform.runLater(() -> { if (!paused) fan.move(); });

Configure your buttons to set your flag:
btPause.setOnAction(e -> paused = true);
btResume.setOnAction(e -> paused = false);

I've just put the pause variable directly in the calling application, but you could encapsulate the pause status inside the fan object if you wished.
Normally when dealing with multi-threaded stuff you have to be careful about data getting corrupted due to race-conditions.  For example, you would use constructs like AtomicBoolean or synchronized statements.  But runLater puts everything on to the JavaFX application thread, so you don't necessarily need to worry about that.
There are alternate mechanisms you could use to ensure that your thread didn't keep looping and and sleeping, such as wait/notify or Conditions, but for a sample like this, you probably don't need that here.
Updated Application
Updated sample demonstrating the suggested modifications, tested on JDK 8u60, OS X 10.11.4.
public class ch30 extends Application {
    private boolean paused = false;

    @Override
    public void start(Stage primaryStage) {
        FanPane fan = new FanPane();

        HBox hBox = new HBox(5);
        Button btPause = new Button("Pause");
        Button btResume = new Button("Resume");
        Button btReverse = new Button("Reverse");
        hBox.setAlignment(Pos.CENTER);
        hBox.getChildren().addAll(btPause, btResume, btReverse);

        BorderPane pane = new BorderPane();
        pane.setCenter(fan);
        pane.setBottom(hBox);

        Thread first = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    break;
                }
                Platform.runLater(() -> { if (!paused) fan.move(); });
            }
        });
        first.setDaemon(true);
        first.start();

        btPause.setOnAction(e -> paused = true);
        btResume.setOnAction(e -> paused = false);
        btReverse.setOnAction(e -> fan.reverse());

        Scene scene = new Scene(pane, 200, 200);
        scene.widthProperty().addListener(e -> fan.setW(fan.getWidth()));
        scene.heightProperty().addListener(e -> fan.setH(fan.getHeight()));
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Aside
Set the daemon status of your thread so that your application shuts down cleanly when somebody closes the main stage.
first.setDaemon(true);


text:
Q: Reaction Roles using JSON files So.. I want to know how could I do the classic events work with my json variables.
Let me explain, I created a json file which memorates the, channelid, reactions, assigned role, and total reactions, of a message. For example if I run the command :
.r <messageID> <emoji> <role> add
The JSON File writes this :
{
  <messageID> :{
       'channelID' : <channelID of the message>
       'reaction(1)' : '<emoji>'  //unicode name value | I used "unicode.name(emoji)"
       'assigned role(1)' : '<role>'
       'total rrs' : 1
  }
}

I ve made everything, but the events, I can t figure them out, I tried with payload, that on_reaction_raw_add/remove functions, but it does not work, or supposely I don t know how to use them..
I also tried with the other ones, on_reaction_add/remove() but I can't figure them out, it does not work, could omeone help me, in case you need more details about the code, you can comment below and I ll edit the message or reply yours.
Thank you,
RVZWN.

A: I assume the events in general, there is an event called 'on_reaction_add' which lets you do something whenever you add a reaction ( 'on_reaction_remove' for when you remove one )
Inside this method, you can get the reaction from the user who placed it.
in the reaction value you can get the actual message by doing reaction.message ( Discord.Message ) and reaction.emoji ( which gives you the actual emoji )
async def on_reaction_add(self, reaction: discord.Reaction, user:
                          discord.Member):
    # Rest of code here about reactions, dumping to json and things

If I didn't answer it correctly then specify what you're asking,
If you need anything else I'll be more than happy to help.


text:
Q: Is it possible to apply an agg function without listing out all the columns if I only need to apply a different function to one column Given
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df
        a           b           c           d
    0   0.569586    0.730646    0.070111    0.226699
    1   0.092704    0.828220    0.190215    0.644188
    2   0.815397    0.281504    0.690391    0.115763
    3   0.614022    0.303781    0.738919    0.551983

I understand we can use df.agg({'a':'sum','b':'mean','c':'max','d':'min'}) to apply multiple functions across multiple columns.
Is it possible to do it without listing out all the columns if I only need to apply one different  function. Something like df.agg({'a':'sum', //df.columns[1:]// : 'mean'})

A: AFAIK, no, you need explicit column names as keys. However, you can build the dictionary like this:
agg_dict = {'a':'sum'}
for c in df.columns[1:]: agg_dict[c] = 'mean'

df.groupby('some_columns').agg(agg_dict)

A: pandas agg function also get list as parameter.
so you can use something like
params = ['sum'] + len(df.columns[1:]) * ['mean']
df.agg([params])


text:
Q: Why is String.GetHashCode() implemented differently in 32-bit and 64-bit versions of the CLR? What are the technical reasons behind the difference between the 32-bit and 64-bit versions of string.GetHashCode()?
More importantly, why does the 64-bit version seem to terminate its algorithm when it encounters the NUL character? For example, the following expressions all return true when run under the 64-bit CLR.
"\0123456789".GetHashCode() == "\0987654321".GetHashCode()
"\0AAAAAAAAA".GetHashCode() == "\0BBBBBBBBB".GetHashCode()
"\0The".GetHashCode() == "\0Game".GetHashCode()

This behavior (bug?) manifested as a performance issue when we used such strings as keys in a Dictionary.

A: Eric lippert has got a wondeful blog to this
Curious property in String
Curious property Revealed

A: This looks like a known issue which Microsoft would not fix:

As you have mentioned this would be a breaking change for some programs (even though they shouldn't really be relying on this), the risk of this was deemed too high to fix this in the current release.
I agree that the rate of collisions that this will cause in the default Dictionary<String, Object> will be inflated by this. If this is adversely effecting your applications performance, I would suggest trying to work around it by using one of the Dictionary constructors that takes an IEqualityComparer so you can provide a more appropriate GetHashCode implementation. I know this isn't ideal and would like to get this fixed in a future version of the .NET Framework.

Source: Microsoft Connect - String.GetHashCode ignores any characters in the string beyond the first null byte in x64 runtime


text:
Q: React. Fromik. Material-ui form submit event testing fails using react-testing-library I have a react app using Formik and Material-ui.
I grabbed the submit button html element,
But fireEvent is not working.
I think the issue is coming from Formik library layer.
'Button' component is a reusable material ui button.
'change fireEvent' tests are passed.
But I receive 'Expected mock function to have been called one time, but it was called zero times.' message for 'submit fireEvent'.
loginForm.test.js
import { Router, MemoryRouter } from 'react-router-dom';
import { queryByAttribute } from 'react-testing-library';
import React, { render, cleanup, fireEvent } from '../../../setupTests';
import LoginForm from '../../../../components/auth/login/loginForm';

afterEach(cleanup);

const mockSubmit = jest.fn();
const mockKeepMeLoggedIn = jest.fn();

const defaultProps = {
  handleSubmit: mockSubmit,
  isSubmitting: false,
  userData: [],
  keepMeLoggedIn: mockKeepMeLoggedIn,
};

const setUp = (props = {}) => {
  const setupProps = { ...defaultProps, ...props };
  const component = render(
    <MemoryRouter>
      <LoginForm {...setupProps} />
    </MemoryRouter>,
  );
  const { container, getByTestId, getByText } = component;
  const getByName = queryByAttribute.bind(null, 'name');
  const usernameInput = getByName(container, 'username');
  const passwordInput = getByName(container, 'password');
  const getByType = queryByAttribute.bind(null, 'type');
  const submitButton = getByType(container, 'submit');

  return { component, usernameInput, passwordInput, submitButton };
};

describe('Login Form Component', () => {
  it('simulate input type and click the form submit button', () => {
    const { usernameInput, passwordInput, submitButton } = setUp();
    fireEvent.change(usernameInput, { target: { value: 'yuch' } });
    expect(usernameInput.value).toBe('yuch');
    fireEvent.change(passwordInput, { target: { value: 'testpwd1234' } });
    expect(passwordInput.value).toBe('testpwd1234');

    fireEvent.click(submitButton);
    expect(mockSubmit).toHaveBeenCalledTimes(1);
  });

loginForm.js
 ...

        import { Formik, Form } from 'formik';
        /* --- Components --- */
        import FormikField from '../../../shared/form/formikField';
        import PasswordField from '../../../shared/form/passwordField';
        import Button from '../../../shared/form/formButton';

        const LoginForm = ({
          keepMeLoggedIn,
          keepLoggedIn,
          userData,
          handleSubmit,
          loginValidation,
        }) => {
          const foundUsername = userData.length !== 0 ? userData[0].username : '';
          const values = { username: foundUsername, password: '' };
          return (
            <Formik
              initialValues={values}
              validationSchema={loginValidation}
              onSubmit={handleSubmit}
            >
              {({ isSubmitting }) => (

                  <Form
                    className="flex flex-column-m center"
                    data-testid="form"
                  >

            <FormikField
              label="아이디"
              name="username"
              type="text"
              icon="filledUser"
              styleName="textField"
              required
            />
           ...
            <Button
              typeValue="submit"
              variantValue="contained"
              buttonName="로그인"
              className="login-btn"
              isSubmitting={isSubmitting}
            />
          </Form>
         ...

      )}
    </Formik>
  );
};

button.js
import React from 'react';
import Button from '@material-ui/core/Button';
import { withStyles } from '@material-ui/core/styles';

const styles = theme => ({
  ...
});

const FormButton = ({
  typeValue,
  variantValue,
  buttonName,
  width,
  isSubmitting,
  classes,
  className,
}) => {
  ...
  return (
    <Button
      type={typeValue}
      variant={variantValue}
      color="primary"
      size="small"
      style={widthStyle}
      className={`${className} ${classes.button}`}
      disabled={isSubmitting}
    >
      {buttonName}
    </Button>
  );
};

Things I have tried.
[ To get submit button ]

*

*const getByType = queryByAttribute.bind(null, 'type');

const submitButton = getByType(container, 'submit');

-> console.log(submitButton) // HTMLButtonElement

-> fireEvent.click(submitButton)

2.

const submitButton = getByText('로그인');

-> console.log(submitButton) // HTMLSpanElement

-> fireEvent.click(submitButton)

*const submitButton = getByTestId('form');

-> console.log(submitButton) // HTMLFormElement

-> fireEvent.submit(submitButton)

[ form ]
1. html 'form' instead of 'Form' from Formik.
import { Formik, Form } from 'formik';

<Formik
      initialValues={values}
      validationSchema={loginValidation}
      onSubmit={handleSubmit}
    >
      {({ handleSubmit, isSubmitting }) => (

          <form
            className="flex flex-column-m center"
            onSubmit={handleSubmit}
            data-testid="form"
          >
          ...
          </form>

A: It actually has to do with how Formik handles the submit. Since it is using a promise, it takes at least a tick before the onSubmit call is being called.
Testing library has a wait utility which waits for a given time. But since we only need to wait for a single tick, we can just omit the duration.
First, import wait from react-testing-library. Then make your it function async and wrap the expect part with a wait function.
I've tested this with a click event on the submit button.
// import wait
import { wait } from 'react-testing-library';

// add async
it('simulate input type and click the form submit button', async () => {
  const { usernameInput, passwordInput, submitButton } = setUp();

  fireEvent.change(usernameInput, { target: { value: 'yuch' } });
  expect(usernameInput.value).toBe('yuch');

  fireEvent.change(passwordInput, { target: { value: 'testpwd1234' } });
  expect(passwordInput.value).toBe('testpwd1234');

  fireEvent.click(submitButton);

  // wrap expect in `await wait`
  await wait(() => {
    expect(mockSubmit).toHaveBeenCalledTimes(1);
  });
});


text:
Q: PAssing PHP variables inside a mysql_query function I want to pass a php variable in mysql_query such as:
$tty = '217';

$num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id =  '.$tty.'");
$num_of_comments1 = mysql_fetch_array($num_of_comments);
$num_of_comments2 = $num_of_comments1[0];
echo $num_of_comments2 ;

However, I am not able to get the value needed in num_of_comments2. It returns a 0 on echo.

A: As the colour coding will show you, your query is wrong. You could also debug it by just echoing your query:
SELECT count(*) FROM comments WHERE img_id =  '.217.'

Clearly incorrect!
$tty = '217';

$sql = mysql_query("SELECT count(*) FROM comments WHERE img_id = ".intval($tty));
$row = mysql_fetch_row($sql);
$number = $row[0];
echo $number;

Alternative one-liner for getting the value:
list($number) = mysql_fetch_row(mysql_query("select count(*) from `comments` where `img_id`=".intval($tty)));

A: This should work:
$tty = '217';

$num_of_comments = mysql_query("SELECT count(*) FROM comments WHERE img_id =  '".$tty."'");
$num_of_comments1 = mysql_fetch_array($num_of_comments);
$num_of_comments2 = $num_of_comments1[0];
echo $num_of_comments2 ;

Use '".$tty."' instead of '.$tty.'

A: Basic PHP syntax:
$num_of_comments = mysql_query("[[...snip...]]=  '.$tty.'");

You never "closed" your string, so you're trying to execute a PHP concatenation INSIDE your string, which won't work. Your query string is literally going to be
WHERE imd_id = '.217.'
                ^---^--- note the concatentation operators

For a "-quoted string, you do NOT need to concatenate:
$num_of_comments = mysql_query([[..snip..] =  '$tty'");
                                              ^^^^^^^---note: no dots

is all you need.


text:
Q: How do I drain a pipeline from within another pipeline? I need to programmatically drain a pipeline from within another pipeline. The DataflowPipelineJob class doesn't have a drain method implemented. Is it possible to call drain on a pipeline from with the Java API?

A: Was able to initiate draining with the following code:
    // spawn child pipe
    DataflowPipelineRunner runner = DataflowPipelineRunner.fromOptions(options);
    DataflowPipelineJob job = runner.run(p);

    // under the some condition later, drain the spawned pipe:
    Dataflow client = com.google.cloud.dataflow.sdk.util.Transport.newDataflowClient(options).build();
    Job content = new Job();
    content.setProjectId(options.getProject());
    content.setId(job.getJobId());
    content.setRequestedState("JOB_STATE_DRAINING");
    client.projects().jobs()
            .update(options.getProject(), job.getJobId(), content)
            .execute();


text:
Q: How to deal with users who click "Back" button after sign out I show a message:

"You are not logged in"

for guests who click a button "submit" on my page. Surely, for logged in users I want to not show the message. I coded this in this way:
<c:if test="${someCondition}">
addMsgToButtonEvent();
</c:if>

It works (almost) perfectly. But, now when user is logged in and:

*

*click sign out (which is in my header and redirects on another page)

*click "Back" button on the browser

The message doesn't appear because my page is not rendered again, addMsgToButtonEvent is not called. I know that I can block "back" button by clearing a history - but this would change too much in business requirements. Is this some soft and effective workaround on this problem?

Edited:
I think the best approach for such problem is invalidating session after sign out. I did it in this way.

A: I've had similar problems with ASP.Net sites and login controls.
You could add a meta tag to the HTML to tell the browser not to cache it - hence the back button will cause the page to be reloaded from the server correctly:
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
<meta http-equiv="EXPIRES" content="0">

Hope that might help :)

A: If caching is problem add the following lines to the top of your JSP
<%
response.setHeader("Cache-Control","no-cache no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

If that does not solve the problem ... you may want to look at how you are handling display code and session invalidation.
Best approach is:
When you create a session assign an named attribute
In order to print the statement check the existence of the named attribute
If named attribute is found ... print the message else do not do it
On logout ... do session.invalid()
Let me know what worked ... and we can dig deeper into this


text:
Q: Decompose a relation to 2NF and preserve all the functional dependencies For example, consider the following relation:
R(A, B, C, D, E)

With the functional dependencies (FDs) shown below:
{A→B,  BC→E,  D→C}

Here candidate key is {AD} and the relation is not in second normal form (2NF) because of the partial dependencies A→B,  D→C.
Now, if I decompose R as follows:
R1(AB) ,  R2(CD),  R3(ADE)

...these relations are now in 2NF, but the FD BC→E is lost.
How can I decompose R to comply with 2NF and preserve the FDs?

A: One decomposition in 3NF (and so also in 2NF) is:
R1(AB)
R2(BCE)
R3(CD)
R4(AD)

This decomposition can be obtained with the so-called synthesis algorithm for 3NF, it is a lossless decomposition and preserves the Functional Dependencies.


text:
Q: Laravel Echo with Pusher and Vue I use Laravel as a server part and Vue Cli as a client.
Also I use https://docs.beyondco.de/laravel-websockets/
But I have a errors in console log when i try connect vue client to laravel websockets.
WebSocket connection to 'ws://http//websockets.test:6001/app/myKey?protocol=7&client=js&version=5.1.1&flash=false' failed: Connection closed before receiving a handshake response

WebSocket connection to 'wss://http//websockets.test:443/app/myKey?protocol=7&client=js&version=5.1.1&flash=false' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

Access to XMLHttpRequest at 'http://sockjs-mt1.pusher.com/pusher/app/myKey/659/6nenb2dd/xhr_streaming?protocol=7&client=js&version=5.1.1&t=1583092642805&n=1' from origin 'http://app.vuesocks.test:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my code in Vue Cli index.js Echo options
window.Echo = new Echo({
  broadcaster: 'pusher',
  key: 'myKey',
  cluster: 'mt1',
  authEndpoint: 'http://websockets.test/broadcasting/auth',
  wsHost: 'http://websockets.test',
  wsPort: 6001,
  disableStats: true,
  auth: {
    headers: {
      Authorization: 'Bearer myToken...',
    },
  },
});

BroadcastServiceProvider.php
Broadcast::routes(['middleware' => 'auth:api']);

channel.php
Broadcast::channel('chat', function () {
    return 'Hello!';
});

if remove wsHost and wsPort then there are no errors, but nothing happens, there is no response from the server.

A: This has probably already been solved but to anyone who is still having trouble getting their frontend to listen for events, what worked for me was reverting pusher-js back to version 5.1.1, found the answer on this issue on the repo: https://github.com/beyondcode/laravel-websockets/issues/365

A: I had the same problem (Laravel and Vuejs), it was working in localhost but when I host to a vps CORS issue was showing in the console.
I changed pushers-js version from 6.0.0 to 5.1.1, that worked for me.


text:
Q: Unable to move file from one s3 bucket to another using boto3 I am trying to move a file from one s3 bucket to another, I am using boto3 copy function but I am getting the following error:
An error occurred (404) when calling the HeadObject operation: Not Found

This is how I am calling the copy function:
 copy_source = {"Bucket": f'{exampleBucket1}', "Key": f'{myFile}'}
 connection.meta.client.copy(copy_source, Bucket=f'{exampleBucket2}', Key=f'{myFile}')
 #connection.Object(f'{exampleBucket1}', f'{myFile}').delete()

can someone plz tell me where am I making mistake?


text:
Q: Trying to orderby with case when clause for MultiDocumentQuery? I am trying to get all my pagetypes from kentico, but I would like to order them by all the page types that starts with the letter "F", first and then the other pages alphabetically.
What I am trying is:
1) MultiDocumentQuery docQuery = DocumentHelper.GetDocuments().Type("forms").OnSite(SiteContext.CurrentSiteID).Published();
2) docQuery.OrderBy("FormName");
But what I need is to order em using something like this (SQL):
SELECT FormName
FROM Forms
order by
  case when FormName like 'C%' then 0 else 1 end,
  FormName
What I cant do is to translate the case when properly to c#, and implement it to docQuery.
So the result should be for example,:

*

*Form1

*Form2

*Form3

*A...

*B...

A: I think I'd look at adding your case statement in the columns rather then the where like this:
CASE WHEN FormName LIKE 'F%' THEN 0 ELSE 1 END AS IsForm

This way you can have a new column called IsForm and can have an Order by of:
IsForm, FormName


text:
Q: Reading a file with File I/O using a char in C++ Please help! Whenever it outputs the array, it prints garbage :( The purpose of my code is for it to go through a long text file, which has a conversion, like this.
2016-20-5: Bob: "Whats up!"
2016-20-5: Jerome: "Nothing bro!"

and for it to take this and break it up to like a format like this:
Person's Name: Bob Message Sent: Whats up! Date: 2016-20-5

(BTW there is a file called "char.txt" and if I use a string it works, but I cant use string because some funcs only accept char*)
Here is what I have so far, still trying to make it print out this:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
    ifstream readchat;
    readchat.open("chat.txt");
    const int MAX = sizeof(readchat);
    char line[MAX];
    char *colon;
    colon = strtok(line, ":");
    while (!readchat.eof())
    {
        while (colon != NULL)
        {
            cout << line;
            colon = strtok(NULL, ":");
        }
    }
    system("pause");
    return 0;
}

A: *

*You can convert a String to a char array / pointer via str.c_str() http://www.cplusplus.com/reference/string/string/c_str/
You can combine this to:
std::string linestr;
std::getline ( readchat,linestr);
char * line = linestr.c_str()`

*Alternative: read direct to array with readchat.read() http://www.cplusplus.com/reference/istream/istream/read/

A: Answer, thanks to Loki Astari!
New code:
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream readchat("chat.txt");
    std::string line;
    while (std::getline(readchat, line, ':'))
    {
        std::cout << line << std::endl;
    }
}

Explanation: Used a string instead of char because it is way more neat and is overall way better. TO read the file into my string I used std::getline(readchat, line, ':') which also took care of cutting the string in the :. Then since readchat was read into line, I printed line out and added a endl to make a new line everytime the string was cut.


text:
Q: Word to describe when a person is interrupted by a trivial correction, distracting from the point? Is there a word for a "technically accurate correction, but one that nobody needed.  Something that causes a digression, which may or may not have been an attempt to diminish the original point by making it seemed flawed"?
I think there should be.
Red Herring doesn't seem to fit, because the context isn't a debate. A specialist of any type (Grammar, English, engineering, science, history, etc) are prone to making this mistake in mixed company.

A: Perhaps a nit:

:  a minor shortcoming
Merriam-Webster

This is more often used in this sense in the word nitpick.

A: How about a "Pedant" (n.)

a person who annoys other people by correcting small errors and giving too much attention to minor details

*

*Merriam Webster

  "All too often, science fiction provokes the pedant in professional scientists, for whom a beautiful story can be ruined by a single petty error." —Jerry A. Coyne, New York Times Book Review, 10 Oct. 1999

Or "Pedantic" (Adj.) would probably work better for your usage.

A: Having gone on a tangent seems right, which is discussion of a mostly irrelevant part of the overall point.

A: This depends on the offending person's motivations:

*

*If the person is concerned about absolute correctness (A "Type C personality"), then he is being Pedantic.
From Wiktionary:

*

*Like a pedant, overly concerned with formal rules and trivial points of learning.

*Being showy of one's knowledge, often in a boring manner.

*Being finicky or fastidious, especially with language.

*If the person is hostile to the victim and wants to disrupt or negate him (As happens constantly in politics and in "news" interviews), then he can be said to Abash the victim.
From Wiktionary:

To make ashamed; to embarrass; to destroy the self-possession of, as by exciting suddenly a consciousness of guilt, mistake, or inferiority; to disconcert; to discomfit.

*Particularly vicious or sustained (a)bashing becomes Heckling.

A: Perhaps rephrasing in order to highlight my word of choice:
     MINUTIAE: the small, precise, or trivial details of something

These sporadic queries about minutiae which you persistently interject
only serve to derail my delivery of all the pertinent facts and
render me incapable of completing my report on the events of last
night.


text:
Q: Laravel 5: FineUploader - Uploads directory isn't writable I am working with Laravel 5 and I am trying to use FineUploder.
Here is what I used
PHP-Traditional
First I was having VerifyCsrfToken error and as a temporary commented out
\App\Http\Middleware\VerifyCsrfToken::class,

From
App/Http/Kernel.php

CsrfToken error gone!
Now I am having "Uploads directory isn't writable" error.
My Route
Route::resource('endpoint','FineUploaderController');

My FineUploaderController
public function store(Request $request)
{
     // dd('store');
     return view('fineupload.endpoint');
}

My upload Folder inside public folder
/uploads/receiptuploads

And endpoint.php
if ($method == "POST") {
header("Content-Type: text/plain");

// Assumes you have a chunking.success.endpoint set to point here with a query parameter of "done".
// For example: /myserver/handlers/endpoint.php?done
if (isset($_GET["done"])) {
    $result = $uploader->combineChunks("/uploads/receiptuploads");
}
// Handles upload requests
else {
    // Call handleUpload() with the name of the folder, relative to PHP's getcwd()
    $result = $uploader->handleUpload("/uploads/receiptuploads");

    // To return a name used for uploaded file you can use the following line.
    $result["uploadName"] = $uploader->getUploadName();
}

echo json_encode($result);
}
// for delete file requests
else if ($method == "DELETE") {
    $result = $uploader->handleDelete("/uploads/receiptuploads");
    echo json_encode($result);
}
else {
    header("HTTP/1.0 405 Method Not Allowed");
}

?>

A: Simple solution: you will need to make the "/uploads" directory writeable for whatever user is running the PHP server. If you have attempted to do this and are stuck with the same result, you have most definitely either assigned the wrong permissions, or are targeting the wrong directory.
Note that you will need to do the same for whichever directory is configured to temporary store file chunks.


text:
Q: Query that returns a single column containing data from multiple columns (ORACLE) I'm trying to write an oracle SQL query that returns a single column containing values from multiple columns.
I have a table named CLIENT
clientid firstname Lastname
1        Steve     Smith
2        James     Hill

I want to return a single column "ALL" like so:
ALL
1
2
Steve
James
Smith
Hill

Is there a simple way to write this query?

A: This involves UNION
SELECT ClientID AS [All]
   FROM Client
  UNION ALL
SELECT FirstName
   FROM Client
  UNION ALL
SELECT LastName
   FROM Client


text:
Q: How do you prove the particle went through both slits? I'm only a casual reader so maybe i misunderstood something so far but here is my current understanding:
The pattern we see from the 2 slit experiment emerges due to two probability waves, one emerging from each slit causing interference with each other (constructive or destructive), even though the two waves are from the same particle.
Which means at least mathematically and making the assumption a particle goes through both slits, we can explain the pattern. But its this assumption made that i don't fully grasp.
How do you physically prove that it went through both slits?
Or is this more of a situation of "well the math works so do you have any better suggestions"?


text:
Q: Expanding textbox stopping page breaks in PDF conversion I have a simple report that has an image and a textbox within the body (a rectangle).  The textbox is set to 'Allow Height to Increase'.  The rectangle is set to 'Page Break After'.
Normally this works fine if the contents of the textbox span a few lines.  However, when the textbox expands over multiple pages the Page Break is ignored.  This only happens when exporting to PDF, yet works as expected in Preview mode.
I'm hoping someone has some insight into this behaviour or can recommend an alternative page structure that will achieve the desired results.

A: Could you please check the Rectangles property

kept contents together on a single page

in a parent Rectangle object, this will always keep items together where possible.
You could also set page setup settings (margins, gutters, printable page size...) to make sure that they are not affects on exported PDF document.