text:
Q: How can I make a subcaptionbox label appear in front of an image? This MWE:
\documentclass{article}
\usepackage[labelfont=bf,size=Large,position=top, skip=-10pt, justification=raggedright, singlelinecheck=false]{subcaption}
\usepackage{graphicx}

\begin{document}
\begin{figure}
\centering
  \subcaptionbox{}{\includegraphics[width=0.5\linewidth]{example-image-a}}
  \subcaptionbox{}{\includegraphics[width=0.5\linewidth]{example-image-b}}

  \caption{Some caption}
\end{figure}

\end{document}

Produces the following output:

In which the labels (a) and (b) are being occluded due to the "skip" option to subcaption. I really want the label to be more to the right than the default, but I do not know how to make subcaption put the label in front of the image. Moreover, I do not understand why the text is placed behind the image in the first place.
How can I put the labels (a) and (b) in front of the text? There does not seem to be any option in caption controlling the "depth" of things.
My endgame is to have a figure as in the image above but with the text in front for each sub figure. The caption must be there where it is now as well.
BTW, the documentclass I have to use (achemso) wont let me use floatrow.

A: I got around it using the accepted answer here:
Put subfigure labels inside figures using subfig package
Here is a MWE:
\documentclass{article}
\usepackage{graphicx}

\newcommand{\subfigimg}[3][,]{%
  \setbox1=\hbox{\includegraphics[#1]{#3}}% Store image in box
  \leavevmode\rlap{\usebox1}% Print image
  \rlap{\hspace*{10pt}\raisebox{\dimexpr\ht1-1.2\baselineskip}{\large\textbf{#2}}}% Print label
  \phantom{\usebox1}% Insert appropriate spcing
}

\begin{document}
\begin{figure}
  \centering
  \begin{tabular}{@{}p{0.5\linewidth}@{\quad}p{0.5\linewidth}@{}}
    \subfigimg[width=\linewidth]{A)}{example-image-a} \\
    \subfigimg[width=\linewidth]{B)}{example-image-b}
  \end{tabular}
  \caption{A caption}
\end{figure}
\end{document}

Which produces the desired output:

However this feels kind of hacky and I still neither know how to do it with subcaption nor understand why the text is placed behind the image there. So if anyone knows I will accept the answer.


text:
Q: Send Mail using Java Mailer API and Actor I am building application that use java mailer api to send mail in play 2.4. Now i want to make this service asynchronous and non blocking. What is the best practice to implements asynchronous and non blocking? I found some example in scala but i want to implement in java.  I have implemented mailer service using actor model but i am getting error. Below is my code
 public class MailerActor extends UntypedActor {
    MailerClient mailerClient;
    @Inject
    public MailerActor(MailerClient mailerClient) {
        System.out.println("inside MailerActor constructor");
        this.mailerClient = mailerClient;
    }
    @Override
    public void onReceive(Object message) throws Exception {
        if(message instanceof NewRequest) {
            Email email = new Email();
            email.setSubject("Activation Link");
            email.setFrom("rec@gmail.com");
            email.addTo("receiver@gmail.com");
            email.setBodyText("hello");
            mailerClient.send(email);
        }

    }
    public static Props props(final MailerClient mailerClient) {
        return Props.create(new Creator<MailerActor>() {
          private static final long serialVersionUID = 1L;
          @Override
          public MailerActor create() throws Exception {
            return new MailerActor(mailerClient);
          }
        });
      }
}

I am calling this actor using below code
 class Controller {
    @Inject MailerClient mailerClient;
        final ActorSystem actorSystem = ActorSystem.create();
        final ActorRef mailerActor = actorSystem.actorOf(MailerActor.props(mailerClient));

public Result sendMail(){
    NewRequest newRequest = new NewRequest();
    mailerActor.tell(newRequest, mailerActor);
    return ok("done");
}

and below is my confg
play{
  modules {
    enabled += "play.api.libs.mailer.MailerModule"
    #enabled += "play.api.db.DBModule"
    #enabled += "play.api.db.HikariCPModule"
  }

  mailer {
      host=smtp.gmail.com
      port=465
      ssl=yes
      tls=no
      user="sender@gmail.com"
      password="axy"
      debug=yes
  }
}

i am getting following exception
[ERROR] [03/19/2016 21:20:54.473] [default-akka.actor.default-dispatcher-5] [akka://default/user/$a] null
java.lang.NullPointerException
    at actors.MailerActor.onReceive(MailerActor.java

redpajama_set_name: RedPajamaStackExchange


text:
Q: Installing Graphics Driver Please tell me how to Install Graphics driver in Ubuntu 16.04.
My netbook specifications:

*

*Acer aspire one d271

*Graphics- Integrated,Intel GMA 3150

*Ram- 2GB

I can't even play the video of 480p it just hangs.
I am a new user so please tell me from the beginning.

A: The Intel graphics are built in. Its your RAM thats low but again, video should not hang. Try turning off other applications when you run video. Also make sure your system has latest updates.


text:
Q: Why my spring boot app couldn't access service of the redis node provided by sentinel but that redis node is actually healthy Platform: Windows 10
JDK: 11
Command to start redis and sentinel:
cd PATH_TO_REDIS\redis_s6379
redis-server.exe redis.windows.conf
redis-server.exe sentinel.conf --sentinel

Redis client: jedis
Detailed log
partial log
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.micrometer.spring.web.servlet.WebMvcMetricsFilter]: Factory method 'webMetricsFilter' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpointHandlerMapping' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping]: Factory method 'endpointHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcEndpoints' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthMvcEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcManagementContextConfiguration.class]: Unsatisfied dependency expressed through method 'healthMvcEndpoint' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration$$EnhancerBySpringCGLIB$$700f4ba6]: Constructor threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$RedisHealthIndicatorConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisConnectionFactory' defined in class path resource [com/corp_name/corp_config/RedisConfig.class]: Invocation of init method failed; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: All sentinels down, cannot determine where is mymaster master is running...

A: The solution for this one is to make sure your sentinel.conf file have the right config.
Add 127.0.0.1 redis-server in your host file. Use "redis-server" as the host value of redis for both the configurations of file("redis.windows.conf") and file("sentinel.conf").
The above solution is inferred from reading the source code file("Connection.java").
redis/clients/jedis/Connection.java:184
Some prerequisite:

*

*windows doesn't support ping the host itself using ipv4 address but mac does.


text:
Q: Assembly forward reference needs override error Using TASM, I have successfully programmed a digital stopwatch (LAP and normal) on emu8086 but when I try to run it on TASM i get the error Forward reference needs override. I know why this error occurs as I have two procedures both including a call of the other procedure so putting one of the procedure before the other one won't work. For example
proc1 proc
;some code
CALL proc2
;some code
ret
endp

proc2 proc
;some code
CALL proc1
;some code
ret
endp

Another solution would be defining/writing the whole procedure instead of calling it but that gives an error of Relative jump out of range. (My code has several jumps too)
My Question is that is there anyway I can remove the forward reference needs override error in my situation?

A: Some other sources seem to suggest that TASM has a multi-pass command line option /m2, which will do the specified number of passes over the source. Two passes should be sufficient in your case, as the first pass will see the definition of proc2 and the second pass can then use it to correctly translate the earlier call proc2.


text:
Q: What did I miss to send a http part post request I am trying to send an image using http multipart request (later I will add another image)
I did this:
HttpClient client = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(
            "http://localhost:8080/ServletExample1/multipart1");
    httpPost.addHeader("Content-Type",
            "multipart/related; boundary=HereItGoes");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody bin = new FileBody(new File("./test.txt"));
    builder.addPart("bin", bin);
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);
    HttpResponse response = client.execute(httpPost);
    String responseString = new BasicResponseHandler()
            .handleResponse(response);
    System.out.println(responseString);

on the server, I print the number of parts, using this:
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
  if (ServletFileUpload.isMultipartContent(request)) {
    Iterator<Part> partsIterator = request.getParts().iterator();
    System.out.println("The number of parts is :" + request.getParts().size());

and the answer is always zero, what mistake did i do ?
Update 1
as @Jon Skeet, I was creating the request before adding the file. Now I reordered the code in which I put the execute as the last line, and I still get the same thing, on the server the number of parts, is still zero

A: Look at when you're calling execute - that's before you build the request properly! Just reorder your code so that you fully build the request, then you post it to get a response, then you use the response. (I'd also be personally surprised if using a URL in a File constructor worked, but maybe there's something funky going on there... normally File refers to a local filesystem file...)


text:
Q: IE Stops Script Execution Using Reference to console.log/error/warn/info If you get a reference to one of the console.log (console.error console.warn console.info) functions in IE 11 and try to call it, it blows up and stops script execution when not using F12 dev tools.
const logFunc = console.log;
logFunc('do some logging'); <-- stops executing further scripts here

If you have dev tools showing, it works fine. So the only way to debug is the old-fashioned alert approach.

A: IE must do some optimizations when you make calls to console log functions when not using their dev tools. But you can call them directly fine, and it won't stop execution:
console.log('log the thing');

But if you get a reference, it fails. So the workaround is to not use references to those functions and always call them directly. You can create wrapper functions that do this.

A: The reason why it is not working is,
Since version 10, Internet Explorer always has a console object. If the developer tools are closed, calls to the console object are simply ignored.
You can copy the method to a variable, but you cannot use the variable to call the method.
Reference:
Console.log Surprises with Internet Explorer 11 and Edge


text:
Q: Why does find_next_sibling in bs4 work on one line of code but not another, very similar, line of code? I'm writing a simple web scraper to get data from the Texas Commission on Environmental Quality (TCEQ) website. The info I need is inside 'td' tags. I'm scraping the appropriate 'td' by referencing the preceding 'th', which all have the same text used to ID. I'm using find_next_sibling to scrape the data into a variable.
Here is my code:
import requests
from bs4 import BeautifulSoup

URL = "https://www2.tceq.texas.gov/oce/eer/index.cfm?fuseaction=main.getDetails&target=323191"

r = requests.get(URL)

soup = BeautifulSoup(r.content, 'html.parser')

###This one works
report = soup.find("th", text="Incident Tracking Number:").find_next_sibling("td").text

###This one doesn't
owner = soup.find("th", text="Name of Owner or Operator:").find_next_sibling("td").text

I'm getting this error: AttributeError: 'NoneType' object has no attribute 'find_next_sibling'. This code has several lines like the two above, and, like them, some of them work and some of them don't. I've looked into the HTML to see if there's another tag, but I'm not seeing it if it's there. Please and thank you for any help!

A: When using the text parameter, you should make sure you provide the text exactly. In your case, there's a space at the end.
soup.find('th', text='Name of Owner or Operator: ').find_next_sibling('td').text

This prints:
\n      \n      \n      \n        \n        PHILLIPS 66 COMPANY\n        \n      \n


text:
Q: Передать в функцию массив Нужно передать в функцию массив чисел и для каждого значения массива выдать alert с его значением, к примеру var someArray = newArray[12, 'str', 234, true], при вводе someArray[1] - с помощью alert будет выводиться сообщение со значением str.
Функция все время выдает undefined, нашел причину: в функцию не передается массив, она его не видит. Проверил несколькими способами, чтобы alert выдал значения каждого массива, но сталкиваюсь с undefined. Подскажите, что делаю не так.

A: Подойдет?

function alertArray(arr) {
  for (i = 0; i < arr.length; i++) {
    alert(arr[i]);
  }
}

var someArray = [12, 'str', 234, true];
alertArray(someArray);

A: var someArray = [12, 'str', 234, true];

function changeArray(arr) {
    for( i = 0; i < arr.length; ++i) {
        alert(arr[i]);
    }
}

changeArray(someArray);

Не знаю как комментировать, честно.
UPD.
Динамически вызов

submitBtn.onclick = function() {
 var someArray = [];
 var inputs = document.getElementsByClassName('test');

 for (var i = 0; i < inputs.length; ++i) {
  someArray.push(inputs[i].value);
 }

 changeArray(someArray);
}

function changeArray(arr) {
    for( i = 0; i < arr.length; ++i) {
  alert(arr[i]);
    }
}
<input type="text" class="test" value="" />
<input type="text" class="test" value="" />
<input type="text" class="test" value="" />
<input type="text" class="test" value="" />
<input type="button" id="submit" value="submit"/>

https://jsfiddle.net/L4oav1nn/

A: Можно так, красиво-лаконично:

[12, 'str', 234, true].map(alert);

Метод объекта Array .map() применит функцию, указанную его аргументом, к каждому элементу массива. В эту функцию первым параметром передаётся значение очередного элемента массива, вторым - его индекс, и третьим – весь массив.
Так – то же, чуть более длинно:
[12, 'str', 234, true].map( function(v){ alert(v);} );


text:
Q: Getting an error install a package on the Terminal to use Hugging Face In VS Cod I am using the steps from the Hugging Face website (https://huggingface.co/docs/transformers/installation) in order to start using hugging face in Visual Studio Code and install all the transformers.
I was on the last process, where I had to type "pip install transformers[flax]", then I got an error, so I installed rust-land, however, I still ended up getting an error;
Requirement already satisfied: transformers[flax] in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (4.22.2)
Requirement already satisfied: filelock in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (3.8.0)
Requirement already satisfied: requests in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (2.28.1)
Requirement already satisfied: tokenizers!=0.11.3,<0.13,>=0.11.1 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (0.12.1)
Requirement already satisfied: huggingface-hub<1.0,>=0.9.0 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (0.10.0)
Requirement already satisfied: packaging>=20.0 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (21.3)
Requirement already satisfied: tqdm>=4.27 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (4.64.1)
Requirement already satisfied: regex!=2019.12.17 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from
transformers[flax]) (2022.9.13)
Requirement already satisfied: numpy>=1.17 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (1.23.3)
Requirement already satisfied: pyyaml>=5.1 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (6.0)
Collecting transformers[flax]
  Using cached transformers-4.22.1-py3-none-any.whl (4.9 MB)
  Using cached transformers-4.22.0-py3-none-any.whl (4.9 MB)
  Using cached transformers-4.21.3-py3-none-any.whl (4.7 MB)
  Using cached transformers-4.21.2-py3-none-any.whl (4.7 MB)
  Using cached transformers-4.21.1-py3-none-any.whl (4.7 MB)
  Using cached transformers-4.21.0-py3-none-any.whl (4.7 MB)
  Using cached transformers-4.20.1-py3-none-any.whl (4.4 MB)
  Using cached transformers-4.20.0-py3-none-any.whl (4.4 MB)
  Using cached transformers-4.19.4-py3-none-any.whl (4.2 MB)
  Using cached transformers-4.19.3-py3-none-any.whl (4.2 MB)
  Using cached transformers-4.19.2-py3-none-any.whl (4.2 MB)
  Using cached transformers-4.19.1-py3-none-any.whl (4.2 MB)
  Using cached transformers-4.19.0-py3-none-any.whl (4.2 MB)
  Using cached transformers-4.18.0-py3-none-any.whl (4.0 MB)
Collecting sacremoses
  Using cached sacremoses-0.0.53-py3-none-any.whl
Collecting jax!=0.3.2,>=0.2.8
  Using cached jax-0.3.21.tar.gz (1.1 MB)
  Preparing metadata (setup.py) ... done
Collecting flax>=0.3.5
  Using cached flax-0.6.1-py3-none-any.whl (185 kB)
Collecting optax>=0.0.8
  Using cached optax-0.1.3-py3-none-any.whl (145 kB)
Collecting transformers[flax]
  Using cached transformers-4.17.0-py3-none-any.whl (3.8 MB)
  Using cached transformers-4.16.2-py3-none-any.whl (3.5 MB)
  Using cached transformers-4.16.1-py3-none-any.whl (3.5 MB)
  Using cached transformers-4.16.0-py3-none-any.whl (3.5 MB)
  Using cached transformers-4.15.0-py3-none-any.whl (3.4 MB)
Collecting tokenizers<0.11,>=0.10.1
  Using cached tokenizers-0.10.3.tar.gz (212 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting transformers[flax]
  Using cached transformers-4.14.1-py3-none-any.whl (3.4 MB)
  Using cached transformers-4.13.0-py3-none-any.whl (3.3 MB)
  Using cached transformers-4.12.5-py3-none-any.whl (3.1 MB)
  Using cached transformers-4.12.4-py3-none-any.whl (3.1 MB)
  Using cached transformers-4.12.3-py3-none-any.whl (3.1 MB)
  Using cached transformers-4.12.2-py3-none-any.whl (3.1 MB)
  Using cached transformers-4.12.1-py3-none-any.whl (3.1 MB)
  Using cached transformers-4.12.0-py3-none-any.whl (3.1 MB)
  Using cached transformers-4.11.3-py3-none-any.whl (2.9 MB)
  Using cached transformers-4.11.2-py3-none-any.whl (2.9 MB)
  Using cached transformers-4.11.1-py3-none-any.whl (2.9 MB)
  Using cached transformers-4.11.0-py3-none-any.whl (2.9 MB)
  Using cached transformers-4.10.3-py3-none-any.whl (2.8 MB)
  Using cached transformers-4.10.2-py3-none-any.whl (2.8 MB)
  Using cached transformers-4.10.1-py3-none-any.whl (2.8 MB)
  Using cached transformers-4.10.0-py3-none-any.whl (2.8 MB)
  Using cached transformers-4.9.2-py3-none-any.whl (2.6 MB)
Collecting huggingface-hub==0.0.12
  Using cached huggingface_hub-0.0.12-py3-none-any.whl (37 kB)
Collecting transformers[flax]
  Using cached transformers-4.9.1-py3-none-any.whl (2.6 MB)
  Using cached transformers-4.9.0-py3-none-any.whl (2.6 MB)
  Using cached transformers-4.8.2-py3-none-any.whl (2.5 MB)
  Using cached transformers-4.8.1-py3-none-any.whl (2.5 MB)
  Using cached transformers-4.8.0-py3-none-any.whl (2.5 MB)
  Using cached transformers-4.7.0-py3-none-any.whl (2.5 MB)
Collecting huggingface-hub==0.0.8
  Using cached huggingface_hub-0.0.8-py3-none-any.whl (34 kB)
Collecting transformers[flax]
  Using cached transformers-4.6.1-py3-none-any.whl (2.2 MB)
  Using cached transformers-4.6.0-py3-none-any.whl (2.3 MB)
  Using cached transformers-4.5.1-py3-none-any.whl (2.1 MB)
  Using cached transformers-4.5.0-py3-none-any.whl (2.1 MB)
  Using cached transformers-4.4.2-py3-none-any.whl (2.0 MB)
  Using cached transformers-4.4.1-py3-none-any.whl (2.1 MB)
  Using cached transformers-4.4.0-py3-none-any.whl (2.1 MB)
  Using cached transformers-4.3.3-py3-none-any.whl (1.9 MB)
  Using cached transformers-4.3.2-py3-none-any.whl (1.8 MB)
  Using cached transformers-4.3.1-py3-none-any.whl (1.8 MB)
  Using cached transformers-4.3.0-py3-none-any.whl (1.8 MB)
  Using cached transformers-4.2.2-py3-none-any.whl (1.8 MB)
Collecting tokenizers==0.9.4
  Using cached tokenizers-0.9.4.tar.gz (184 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting transformers[flax]
  Using cached transformers-4.2.1-py3-none-any.whl (1.8 MB)
  Using cached transformers-4.2.0-py3-none-any.whl (1.8 MB)
  Using cached transformers-4.1.1-py3-none-any.whl (1.5 MB)
  Using cached transformers-4.1.0-py3-none-any.whl (1.5 MB)
  Using cached transformers-4.0.1-py3-none-any.whl (1.4 MB)
Collecting flax==0.2.2
  Using cached flax-0.2.2-py3-none-any.whl (148 kB)
Collecting transformers[flax]
  Using cached transformers-4.0.0-py3-none-any.whl (1.4 MB)
  Using cached transformers-3.5.1-py3-none-any.whl (1.3 MB)
Requirement already satisfied: protobuf in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from transformers[flax]) (3.19.6)
Collecting sentencepiece==0.1.91
  Using cached sentencepiece-0.1.91.tar.gz (500 kB)
  Preparing metadata (setup.py) ... done
Collecting tokenizers==0.9.3
  Using cached tokenizers-0.9.3.tar.gz (172 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting transformers[flax]
  Using cached transformers-3.5.0-py3-none-any.whl (1.3 MB)
  Using cached transformers-3.4.0-py3-none-any.whl (1.3 MB)
Collecting tokenizers==0.9.2
  Using cached tokenizers-0.9.2.tar.gz (170 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting sentencepiece!=0.1.92
  Using cached sentencepiece-0.1.97-cp310-cp310-win_amd64.whl (1.1 MB)
Collecting transformers[flax]
  Using cached transformers-3.3.1-py3-none-any.whl (1.1 MB)
WARNING: transformers 3.3.1 does not provide the extra 'flax'
Collecting tokenizers==0.8.1.rc2
  Using cached tokenizers-0.8.1rc2.tar.gz (97 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: colorama in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from tqdm>=4.27->transformers[flax]) (0.4.5)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from packaging>=20.0->transformers[flax]) (3.0.9)
Requirement already satisfied: idna<4,>=2.5 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from requests->transformers[flax]) (3.4)
Requirement already satisfied: charset-normalizer<3,>=2 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from requests->transformers[flax]) (2.1.1)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from requests->transformers[flax]) (1.26.12)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from requests->transformers[flax]) (2022.9.24)
Collecting joblib
  Using cached joblib-1.2.0-py3-none-any.whl (297 kB)
Requirement already satisfied: six in c:\users\user\desktop\artificial intelligence\.env\lib\site-packages (from sacremoses->transformers[flax]) (1.16.0)
Collecting click
  Using cached click-8.1.3-py3-none-any.whl (96 kB)
Building wheels for collected packages: tokenizers
  Building wheel for tokenizers (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for tokenizers (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [48 lines of output]
      C:\Users\user\AppData\Local\Temp\pip-build-env-hhrbpvks\overlay\Lib\site-packages\setuptools\dist.py:530: UserWarning: Normalizing '0.8.1.rc2' to '0.8.1rc2'
        warnings.warn(tmpl.format(**locals()))
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-310
      creating build\lib.win-amd64-cpython-310\tokenizers
      copying tokenizers\__init__.py -> build\lib.win-amd64-cpython-310\tokenizers
      creating build\lib.win-amd64-cpython-310\tokenizers\models
      copying tokenizers\models\__init__.py -> build\lib.win-amd64-cpython-310\tokenizers\models
      creating build\lib.win-amd64-cpython-310\tokenizers\decoders
      copying tokenizers\decoders\__init__.py -> build\lib.win-amd64-cpython-310\tokenizers\decoders
      creating build\lib.win-amd64-cpython-310\tokenizers\normalizers
      copying tokenizers\normalizers\__init__.py -> build\lib.win-amd64-cpython-310\tokenizers\normalizers
      creating build\lib.win-amd64-cpython-310\tokenizers\pre_tokenizers
      copying tokenizers\pre_tokenizers\__init__.py -> build\lib.win-amd64-cpython-310\tokenizers\pre_tokenizers
      creating build\lib.win-amd64-cpython-310\tokenizers\processors
      copying tokenizers\processors\__init__.py -> build\lib.win-amd64-cpython-310\tokenizers\processors
      creating build\lib.win-amd64-cpython-310\tokenizers\trainers
      copying tokenizers\trainers\__init__.py -> build\lib.win-amd64-cpython-310\tokenizers\trainers
      creating build\lib.win-amd64-cpython-310\tokenizers\implementations
      copying tokenizers\implementations\base_tokenizer.py -> build\lib.win-amd64-cpython-310\tokenizers\implementations
      copying tokenizers\implementations\bert_wordpiece.py -> build\lib.win-amd64-cpython-310\tokenizers\implementations
      copying tokenizers\implementations\byte_level_bpe.py -> build\lib.win-amd64-cpython-310\tokenizers\implementations
      copying tokenizers\implementations\char_level_bpe.py -> build\lib.win-amd64-cpython-310\tokenizers\implementations
      copying tokenizers\implementations\sentencepiece_bpe.py -> build\lib.win-amd64-cpython-310\tokenizers\implementations
      copying tokenizers\implementations\__init__.py -> build\lib.win-amd64-cpython-310\tokenizers\implementations
      copying tokenizers\__init__.pyi -> build\lib.win-amd64-cpython-310\tokenizers
      copying tokenizers\models\__init__.pyi -> build\lib.win-amd64-cpython-310\tokenizers\models
      copying tokenizers\decoders\__init__.pyi -> build\lib.win-amd64-cpython-310\tokenizers\decoders
      copying tokenizers\normalizers\__init__.pyi -> build\lib.win-amd64-cpython-310\tokenizers\normalizers
      copying tokenizers\pre_tokenizers\__init__.pyi -> build\lib.win-amd64-cpython-310\tokenizers\pre_tokenizers
      copying tokenizers\processors\__init__.pyi -> build\lib.win-amd64-cpython-310\tokenizers\processors
      copying tokenizers\trainers\__init__.pyi -> build\lib.win-amd64-cpython-310\tokenizers\trainers
      running build_ext
      running build_rust
      error: can't find Rust compiler

      If you are using an outdated pip version, it is possible a prebuilt wheel is available for this package but pip is not able to install from it. Installing from the wheel would avoid the need for a Rust compiler.

      To update pip, run:

          pip install --upgrade pip

      and then retry package installation.

      If you did intend to build this package from source, try installing a Rust compiler from your system package manager and
ensure it is on the PATH during installation. Alternatively, rustup (available at https://rustup.rs) is the recommended way to
download and update the Rust compiler toolchain.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for tokenizers
Failed to build tokenizers
ERROR: Could not build wheels for tokenizers, which is required to install pyproject.toml-based projects

Do you know how I can successfully install this into VS Code and use Hugging Face properly?

A:    If you did intend to build this package from source, try installing a Rust compiler from your system package manager and
ensure it is on the PATH during installation. Alternatively, rustup (available at https://rustup.rs) is the recommended way to
download and update the Rust compiler toolchain.
      [end of output]

That's the primary error that you're having. You're going to need to install the rust-lang compiler in order to finish the install.


text:
Q: How do I create a jquery function with callbacks How do I create a plugin / jquery function with the use of the following
$("#button").click(function(){
  $.confirm({
     yes : function(){
        // some code
     },
     no : function(){
        // Some code
     }
  });
});

A: First, define the plugin
$.confirm = function(params) {
    if (confirm(params.message))
        params.yes();
    else
        params.no();

    return this; //to allow chaining
}

Now you can use this plugin as
$('#button').click(function(){
    $.confirm({
        message: "Are you sure?",
        yes: function(){},
        no: function(){}
    });
});


text:
Q: Echo post title in array I am using Imbalance 2 theme from wpshower.  I want to add alt and title tags so they show up in the loop on the homepage.  My title and alt tags are the same as the post title...  so, I want to echo the post title in the array.  I have been playing around but can't seem to figure it out.  I'm a newbee to php, so all and any help will be appreciated. Below is the code from my theme...  What do I need to put inside of the '' to echo the post title?  Thanks in advance...
<a class="transparent" href="<?php the_permalink(); ?>"><?php the_post_thumbnail('homepage-thumb', array('alt' => '', 'title' => '')) ?>

A: Try this:
<a class="transparent" href="<?php the_permalink(); ?>">
    <?php the_post_thumbnail('homepage-thumb', array('alt' => get_the_title(), 'title' => get_the_title())) ?>


text:
Q: How to output pairs of NewsHeadLines and their URLs by Node.js I would like to ask for your help to solve my problem;
I tried a web-scraping program below, but I could not let it output in an array. I would be so happy if you could kindly take care of this.
const app = express();
const port = 5000;

const axios = require('axios');
const cheerio = require('cheerio');

const URL = "https://jen.jiji.com/";
const data = [];

axios(URL).then((response)=>{
    const htmlParser = response.data;
    const $ = cheerio.load(htmlParser);
    $(".category-news-box", htmlParser).each(function(){

// In this code below, I cannot let it work...
        const title = $(this).find("li.arrow03>a").text();
        const artURL = "https://jen.jiji.com/" + $(this).find("li.arrow03>a").attr("href");
        data.push({title, artURL});
    })
//all headlines are included in the first value of an array.

}).catch((error)=>console.log("ERROR OCCURED"));

app.listen(port, console.log("RUN")) ```


text:
Q: Help me identify a component I'm trying to identify a component which I'm not entirely sure what it is.
Here's an image:

The component I'm asking about is circled in red.
The product is a reader + transmitter for water meters (click here).
The sensor somehow either reads the digits from the water meter, or a small rotating disc, to know the water consumption.
Can anybody identify it? My best guess is a linear CMOS sensor, but not sure how would it fit with the application.
Thanks!

A: This is a magnetic reed switch.  The device in question is a paddle wheel flow sensor.  The wheel (impeller) has magnets, which pass near the reed switch on each turn.  When a magnet passes, the reed switch closes.  The frequency of closures is proportional to the flow rate.
 (picture from here)

"Radiomodule scans the readings from water meter counter using an optical sensor..."

I suspect a mismatch between the text and the photo.  Maybe, the sensing method changed at some point, but the photo didn't get updated.
Here's a teardown of another paddle wheel flow meter.  That one is similar in that it has a magnet in the impeller.  It's different in that it uses a hall effect sensor instead of a reed switch.


text:
Q: reduce() vs. fold() in Apache Spark What is the difference  between reduce vs. fold with respect to their technical implementation?
I understand that they differ by their signature as fold accepts additional parameter (i.e. initial value) which gets added to each partition output.

*

*Can someone tell about use case for these two actions?

*Which would perform better in which scenario consider 0 is used for fold?

Thanks in advance.

A: There is no practical difference when it comes to performance whatsoever:

*

*RDD.fold action is using fold on the partition Iterators which is implemented using foldLeft.

*RDD.reduce is using reduceLefton the partition Iterators.

Both methods keep mutable accumulator and process partitions sequentially using simple loops with foldLeft implemented like this:
foreach (x => result = op(result, x))

and reduceLeft like this:
for (x <- self) {
  if (first) {
    ...
  }
  else acc = op(acc, x)
}

Practical difference between these methods in Spark is only related to their behavior on empty collections and ability to use mutable buffer (arguably it is related to performance). You'll find some discussion in Why is the fold action necessary in Spark?
Moreover there is no difference in the overall processing model:

*

*Each partition is processed sequentially using a single thread.

*Partitions are processed in parallel using multiple executors / executor threads.

*Final merge is performed sequentially using a single thread on the driver.


text:
Q: What is the maximum length of a custom url protocol using synchronous pluggable protocols in internet explorer? I'm running into a hard limit in Internet Explorer with application protocol's that exceed 508 characters in length. This limit is not enforced in other browsers, chrome etc...
The documentation on MSDN(1) does not seem to mention the maximum permissible length in the scheme-specific portion of the URI or total length including scheme.
508 characters is well below general limits for urls in IE reported to be 2083 characters (2).
Does anyone know if this is expected behavior, i'm using IE8, or perhaps I've got something wrong here?
References:

*

*Asynchronous Pluggable Protocols

*Maximum URL length is 2,083 characters in Internet Explorer

A: I recently ran into this same problem and come up with the following solution.  If you try to assign the URL directly like this:
 document.location.href = theUrlWithTheCustomProtocol;

you will run into this 508 character limit error and in IE8 you'll get a JavaScript error saying something about The "data area passed to a system call is too small."
To get around this problem, I switched from the above code to using JQuery to create an hidden iframe like this:
// Remove old frame
$('#hiddenIFrame').remove();

// Add new one
$('<iframe />', {
    'id': 'hiddenIFrame',
    'name': 'hiddenIFrame',
    'src': theUrlWithTheCustomProtocol,
    'style': 'display: none;'
}).appendTo("body");

This gets around the IE 508 character limit using document.location.href and this solution works for IE, FireFox, Chrome, and Safari.

A: 508 + some bookkeeping = 512 bytes

I think that the browser, after splitting off the protocol, stores it in a temporary buffer of a fixed size. Why, I don't know, and this seems like behaviour that might change in the future. Don't bank on it.
I'm also wondering why you'd need a protocol this long. Even a GUID is only 36 characters when expressed as hex digits plus dashes.


text:
Q: XML requests to eBay's API using Google Apps Script returns 'The API call "GeteBayOfficialTime" is invalid or not supported in this release' error The function I'm correctly using returns a message saying, "The API call "GeteBayOfficialTime" is invalid or not supported in this release."
function GetTime() {
    var site = "https://api.ebay.com/ws/api.dll";
    var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \
           <GeteBayOfficialTimeRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\"> \
             <RequesterCredentials> \
               <eBayAuthToken>*******</eBayAuthToken> \
             </RequesterCredentials> \
           </GeteBayOfficialTimeRequest>";
    var payload =
      {
        "Content-Type": "text/xml",
        "X-EBAY-API-SITEID": "0",
        "X-EBAY-API-COMPATIBILITY-LEVEL": "759",
        "X-EBAY-API-CALL-NAME": "GeteBayOfficialTime",
        "XML": xml
      };

  var options =
    {
      method:"POST",
      payload:payload
    };
  var response = UrlFetchApp.fetch(site, options);

  var xml = response.getContentText();
};

After a bit of searching, I found that the main cause of this problem is incorrect headers, however, I'm not sure how else to set them other than what is currently implemented.

A: You are passing in both the headers and xml into the request's payload. The headers should be passed in via their own field. The updated code below should work for you.
function GetTime() {
    var site = 'https://api.ebay.com/ws/api.dll';

    var xml = '<?xml version="1.0" encoding="utf-"?> \
        <GeteBayOfficialTimeRequest xmlns="urn:ebay:apis:eBLBaseComponents"> \
            <RequesterCredentials> \
                <eBayAuthToken>*********</eBayAuthToken> \
            </RequesterCredentials> \
        </GeteBayOfficialTimeRequest>';

    var headers = {
        'Content-Type': 'text/xml',
        'X-EBAY-API-SITEID': '0',
        'X-EBAY-API-COMPATIBILITY-LEVEL': '861',
        'X-EBAY-API-CALL-NAME': 'GeteBayOfficialTime'
    };

    var options = {
        method: 'POST',
        headers: headers,
        payload: xml
    };

    var response = UrlFetchApp.fetch(site, options);

    var xml = response.getContentText();
};


text:
Q: Request body could not be parsed. Make sure request body matches specified content-type: application/json I am calling an API with the below code at the server side. It keeps bringing the error: Request body could not be parsed. Make sure request body matches specified content-type: application/json
The Server side code is below:
[HttpPost]
    public async Task<JsonResult> BVNMatch()
    {
        var secretKey = ConfigurationManager.AppSettings["paystack_SecretKey"];
        using (var httpClient = new HttpClient())
        {
            using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.paystack.co/bvn/match"))
            {
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {secretKey}");
                request.Content = new StringContent("{ bvn: \"22******\",\n      account_number: \"068*****\",\n      bank_code: \"034\",\n      first_name: \"uth***\",\n      last_name: \"ji***\"\n  }");
                request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                var response = await httpClient.SendAsync(request);
                var jsonString = await response.Content.ReadAsStringAsync();
                BVNMatch myDeserializedClass = JsonConvert.DeserializeObject<BVNMatch>(jsonString);
                return Json(myDeserializedClass);
            }
        }
    }

Below is the client side Ajax call:
 // Testing the BVNMatch Paystack API
                $("#btnGetBVN").click(function () {
                if ($('#BVN').val() == '' || $('#BVN').val() == undefined) {
                    alert('Please Enter Customer BVN');
                    return false;
                }
                $('.spinner').css('display', 'block');  //if clicked ok spinner shown

                $.ajax({
                    type: "POST",
                    url: "@Url.Action("BVNMatch", "Transactions")",
                  //  data: '{bvn: "' + $("#BVN").val() + '" }',
                   contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert(response.message);
                        $('#Firstname').val(response.data.bvn);
                        $('#Surname').val(response.data.is_blacklisted);

                      //  $('#Phone_Number').val(response.data.mobile);

                        $('.spinner').css('display', 'none');
                    },
                    failure: function (response) {

                        alert('BVN Does Not Exist Or Error Processing Request');
                        $('.spinner').css('display', 'none');
                    },
                    error: function (response) {

                        alert('BVN Does Not Exist Or Error Processing Request');
                        $('.spinner').css('display', 'none');
                    }
                });
                });

A: Issue was resolved by putting quotes around the Content JSON
[HttpPost]
public async Task<JsonResult> BVNMatch()
{
    var secretKey = ConfigurationManager.AppSettings["paystack_SecretKey"];
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.paystack.co/bvn/match"))
        {
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {secretKey}");
            request.Content = new StringContent("{ **"bvn": \"22******\",\n      "account_number": \"068*****\",\n      "bank_code": \"034\",\n      "first_name": \"uth***\",\n      "last_name": \"ji***\"\n  }"**);
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            var response = await httpClient.SendAsync(request);
            var jsonString = await response.Content.ReadAsStringAsync();
            BVNMatch myDeserializedClass = JsonConvert.DeserializeObject<BVNMatch>(jsonString);
            return Json(myDeserializedClass);
        }
    }
}


text:
Q: GPU Basic : Why handle Floating point numbers for computer graphics I am just learning on GPU and in this video(https://www.youtube.com/watch?v=lGmPy8xpT4E&t=4278s) as well as other architecture diagrams of GPU, each Streaming multiprocessor is shown to have multiple ALUs. But in my understanding ALUs can handle only Integer numbers whereas GPUs must handle floating numbers for which multpile FPUs would be desired. Why does the architecture specify ALUs then?
Secondly, for graphics, what is the need for handling floating point numbers? I cannot comprehend a pixel or co-ordinate position in a screen being a floating point number?
PS: I understand its a very basic question, but I am unable to find out a proper resource/answer yet on these despite having read many articles/videos for GPUs.


text:
Q: JavaScript Appear in IE? I have this ajax_update script that updates file.php every 60 seconds.. Now file.php outputs this after updated a table:
<div id="message" style="display: none;" onclick="closeNotice()">this works
</div>

What I am trying to do is that after file.php have updated a field in the database(points), there will come up a message like stackoverflow at the top(just like when you earn a badge) saying that you have received 1 point. anyway:
Here's my update script:
function addpoints()  {
  var postFile = 'addpoints.php?userid='+ $('#user_id_points').val();
  $.post(postFile, function(data){
    $("#points").html(data).find("#message").fadeIn("slow")
    setTimeout(addpoints, 5000);
  });
}

Now, i have  in my index.php, and a load function addpoints script..
But why will this only appear in FF and not in IE?
I have checked with w3c validator, if it could be unclosed tags or something, i fixed all problems and now i have no errors, but still it doesnt work.
So what to do?
You can see my site here: http://azzyh.dk/newgen/area/member/indextest.php
(use FF and you will see the message at the top, use IE and you wont see anything)
Im pretty lost. thank you

A: Other browsers can be more forgiving of errors in your files than IE. IE will encounter an error and simply stop processing. By default, it will not notify you. Here is your error:
Message: Expected ')'
Line: 41
Char: 243
Code: 0
URI: http://azzyh.dk/newgen/area/member/indextest.php
If you run Firebug, you will see Firefox report the same error as well.

A: <body onload="MM_preloadImages('images/index_01.gif',... ,'images/index_10.gif, ...">

Missing closing quote for index_10.gif image.


text:
Q: How do I tell sendmail to use localhost port 2525 as a smart relay? I have a remote system setup on a very restrictive network. Unfortunately I have yet to find a way to have them run an email relay, or to allow the system to connect out to send mail.
There is no way to connect in, instead the system connects out using SSH (which happens via an HTTPS proxy) and uses the -R flag to forward a port on our system back to the remote system so we login.
I am not aware of a way to have sendmail use a https proxy for outbound connections. Instead, I have used -L to forward localhost:2525 to our mail server, but I can't work out how to have sendmail use this as its smart relay.
I have the following in my mc file
define(`SMART_HOST', `[10.10.22.4]')
define(`RELAY_MAILER_ARGS', `TCP $h 2525')

10.10.22.4 is the system's IP address, I also tried 127.0.0.1 with identical results..
The maillog looks like..
Jun 16 06:50:36 remotehost sm-mta[49702]: starting daemon (8.12.9p2): SMTP+queueing@00:30:00
Jun 16 06:50:36 remotehost sm-msp-queue[49703]: starting daemon (8.12.9p2): queueing@00:30:00
Jun 16 06:51:52 remotehost sendmail[50072]: r5G6poHi050072: from=user, size=46, class=0, nrcpts=1, msgid=<201306160651.r5G6poHi050072@remotehost>, relay=user@localhost
Jun 16 06:51:54 remotehost sm-mta[50129]: r5G6pqM2050129: from=<user@remotehost>, size=373, class=0, nrcpts=1, msgid=<201306160651.r5G6poHi050072@remotehost>, proto=ESMTP, daemon=Daemon0, relay=localhost [127.0.0.1]
Jun 16 06:51:54 igarashi1 sendmail[50072]: r5G6poHi050072: to=user@outside.host, ctladdr=user (19999/19999), delay=00:00:04, xdelay=00:00:02, mailer=relay, pri=30041, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (r5G6pqM2050129 Message accepted for delivery)
Jun 16 06:52:05 remotehost sm-mta[50137]: r5G6pqM2050129: to=<user@outside.host>, ctladdr=<user@remotehost> (19999/19999), delay=00:00:11, xdelay=00:00:11, mailer=esmtp, pri=30368, relay=mail.outside.host. [203.31.81.10], dsn=4.0.0, stat=Deferred: Connection reset by mail.outside.host.

ie it appears to ignore the smart relay part. Yes, I have checked the cf file is changing :) I  have also restarted sendmail completely (not just sent it a HUP).

A: Suggested Fix:
Specify mailer in smart host definition:
define(`SMART_HOST', `relay:[10.10.22.4]')

Explanation:
I assume [10.10.22.4] is an IP address of local IP inteface. It makes it listed on sendmail's list of local email domain ($=w). Sendmail ignores "mailer-less" relays to names/addresses listed in $=w. (Sendmail does it in MailerToTriple rule set).


text:
Q: How many CAL needed for SQL server Just wish to know, if I have only created one user login under SQL server however several people uses an application that uses that single ID to communicate with the database. Would this situation requires only one user CAL?

A: Assuming you're referring to Microsoft SQL server, each user or device that connects to the SQL server requires a CAL unless the server is licensed with a Core based license, see Microsoft SQL Licensing Guide(PDF).  It does not matter if they are all using the same login to connect, such as an application using a single SQL authentication account.
If you have multiple SQL servers and they are all CAL-licensed, then the same user CAL's can be used to access multiple servers as long as the CAL is the same or higher version than the SQL server.


text:
Q: Rails app returning 401 Unauthorized while logging in only in production I can't login in my app that is deployed on Heroku, so that one is in production. On my local machine the one that runs the development it does work without a problem. Both the databases are exactly the same as they are dump copies of each other.
I verified the user does exist in the remote database and the password is given in correctly, both local and remote version are from the same branch and are synced.
I've tried this solution, but my config/initializers/session_store.rb looks like this:
# Be sure to restart your server when you modify this file.
FilteredWeb::Application.config.session_store :cookie_store, key: '_filtered-web_session', domain: :all

Someone also suggested changing the encryption key in config/initializers/devise.rb but I don't see where to do this and neither do I understand the logic behind it.
Versions
devise (2.2.3)
rails (3.2.13)

A: I had the same exact error... removing the domain: :all fixed it for me.
See a similar issue on github


text:
Q: AJAX jquery form submitting an error message I am trying to a Jquery Ajax contact form from treehouse's blog Click here i have tried to edit the form slight by removing the 'message field'. From the HTML and JS
I am receiving an error message after submitting my details in the form. Code pen link
Below is a snippet of my code.
HTML  :
<form id="ajax-contact" class="main-contact submit-fade ajax-form" action="register.php" method="POST">

            Name
            <input type="text" class="form-control" name="name" placeholder="Name" required>

            Email
            <input type="text" class="form-control" name="email" placeholder="Email">

    <input type="submit" class="btn btn-success">
</form>

JS :
var form = $('#ajax-contact');
var formMessages = $('#form-messages');

$(form).submit(function(e) {

    e.preventDefault();
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })
    .done(function(response) {
        // Make sure that the formMessages div has the 'success' class.
        $(formMessages).removeClass('error');
        $(formMessages).addClass('success');

        // Set the message text.
        $(formMessages).text(response);

        // Clear the form.
        $('#name').val('');
        $('#email').val('');
        //$('#message').val('');
    })
    .fail(function(data) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');

        // Set the message text.
        if (data.responseText !== '') {
            $(formMessages).text(data.responseText);
        } else {
            $(formMessages).text('Oops! An error occured and your message could not be sent.');
        }
    });

});

PHP :
<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
        $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $message = trim($_POST["message"]);

        // Check that data was sent to the mailer.
        if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        // FIXME: Update this to your desired email address.
        $recipient = "hello@example.com";

        // Set the email subject.
        $subject = "New contact from $name";

        // Build the email content.
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Message:\n$message\n";

        // Build the email headers.
        $email_headers = "From: $name <$email>";

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            http_response_code(200);
            echo "Thank You! Your message has been sent.";
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    }

?>

A: Remove all message variables and conditions from php file.
Your code look like this:
<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);

    // Check that data was sent to the mailer.
    if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "hello@example.com";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

A: resolved the error ("Oops! Something went wrong and we couldn't send your message.") by setting read/write permission on /volume1/web/
Synology support response: "After checking with our developer, normally, using the PHP mail function won't need the write permission, and not sure why your website needs it.
Furthermore, please be aware that giving R/W permission could allow someone to write or even overwrite files in /web folder, or the subfolders."


text:
Q: Change ImagenView´s image of custom control in JavaFX I am try to change the image of this component from another project. I have no compilation´s errors but it leaves it without image.
Failed properties:
 public Image getCompImageView() {
    return compImageViewProperty().get();
}

public void setCompImageView(Image imagen) {
    compImageViewProperty().set(imagen);
}

// Indica como tratar este componente.
public ObjectProperty<Image> compImageViewProperty() {
    return compImageView.imageProperty();
}

Controller(where do i try it):
@FXML  // Button
public void mostrarDatosUsuario() {

    componente.setTextoNombreUsuario("FRS.C");

    Image imagen = new Image(getClass().getResourceAsStream("usuario.png"));
    marco.setImage(imagen);
    componente.setCompImageView(imagen);
}


text:
Q: How to fix Maven PermGen out of memory error on Travis-ci? I'm getting PermGen out of memory error on every build at travis-ci. This is my configuration file:
language: java
env:
  global:
    - MAVEN_OPTS="-XX:MaxPermSize=512m -Xmx4g"
script: mvn clean install

Looks like MAVEN_OPTS is not working, since the same values on another server make the build successful.
Here is one of the builds: https://travis-ci.org/tpc2/requs/builds/23383360

A: Your build link is no longer valid, so I'm going to make a guess. Are you getting the PermGen during surefire tests? That plugin uses a separately configured arg line. Our builds are configured like this:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.14.1</version>
    <configuration>
        <argLine>${argLine} -Xmx512m -XX:MaxPermSize=256m</argLine>
    </configuration>
</plugin>

A: You can set JVM memory settings in MAVEN_OPTS by adding this to .travis.yml:
before_install: echo "MAVEN_OPTS='-Xmx2048m -XX:MaxPermSize=512m'" > ~/.mavenrc


text:
Q: Flutter : Dropdown reusability I need to reuse a dropdown widget, So I created a method. I am calling like this :
buildDropDown("Blood Group", bloodGroups, _groupSelected),
The method definition:
DropdownButtonFormField2<String> buildDropDown(
    String label,
    List<String> items,
    String? selectedElement,
  ) {
    return DropdownButtonFormField2(
      items: items.map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      value: selectedElement,
      onChanged: (value) {
        if (value != null) {
          setState(() {
            selectedElement = value.toString();
          });
        }
        log(selectedElement); // correct value
        log(_groupSelected); // null; though I am giving _groupSelected as selectedElement
      },

      hint: Text(label),
    );
  }

So I assumed it is due to pass-by-value, and decided to give a function as argument to change the variable. But I don't know how, because :
() => selectedElement = value.toString();  // "value" only available in the onChange:
I tried creating a widget but it is not working as desired
code:
class DropDownWidget extends StatefulWidget {
  DropDownWidget(
      {Key? key,
      required this.selectedElement,
      required this.label,
      required this.elements})
      : super(key: key);

  String? selectedElement;
  String label;
  List<String> elements;

  @override
  State<DropDownWidget> createState() => _DropDownWidgetState();
}

class _DropDownWidgetState extends State<DropDownWidget> {
  @override
  Widget build(BuildContext context) {
    return DropdownButtonFormField2(
      items: widget.elements.map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      value: widget.selectedElement,
      onChanged: (value) {
        if (value != null) {
          setState(() => widget.selectedElement = value.toString());
        }
      },
      hint: Text(widget.label),
    );
  }
}

How can I reuse the DropDown?

A: Try pass the function to it:
DropdownButtonFormField2<String> buildDropDown(String label,
      List<String> items, String? selectedElement, Function(String) onChanged) {
    return DropdownButtonFormField2(
      items: items.map((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      value: selectedElement,
      onChanged: onChanged,
      hint: Text(label),
    );
  }

then us it like this :
buildDropDown(
   "Blood Group",
   bloodGroups,
   (value) {
        if (value != null) {
          setState(() {
            _groupSelected = value.toString();
          });
        },
   }
 )


text:
Q: Four-terminal resistor pinout? Anyone can tell me (or preferably, point me to a source that explicitly shows) the pinout of the 4-pin current-sense resistors?
I'm seeing the datasheets for three different models (including Rideon's FHR 4-2321, the Powertron FHR 4-2321,and the PBV-R005-F1-0.5) and I simply cannot believe that neither one of them shows the actual pinout !!!  (the Powertron datasheet does say "Standard Contact S", but a Google search for that shows nothing concrete)
This page gives a very good explanation of the intended use.  Except that they talk about terminal 1, 2, 3, and 4.  They do not explicitly relate T1,T2,T3,T4 to pin numbers (and their drawing doesn't look like Terminal N maps to pin N --- in any case, if we read the pins 1,2,3,4 from left to right)

A: The larger pin would be more suitable for carrying current, so that would be the best indicator. In the event that the pins are the same size it probably wouldn't matter, they go to the same place. Usually the two inner pins are the kelvin connections.

A: If you look at lab current shunts like this one

you see that the current and sense terminals are on the same termination block of the resistor, the 4 point feature being that the connection resistance of the current path screw doesn't affect the voltage measured across the sense terminals. I'd suspect that these shunts are similar in construction, in that the two leads at each side are part of a single leadframe that the resistor element is bonded to, and the fatter of the two pins is the designated current terminal.
Here is an Ohmite data sheet that shows explicitly which pin is which.


text:
Q: Record and view video at the same time DirectShow I have used the sample code of DirectShow in order to record a video. however, I want to display the video during recording as well. But I can't do it at the same time, this error always shows:
' Const VIDEODEVICE As Integer = 0
' zero based index of video capture device to use
Cursor.Current = Cursors.WaitCursor

If cam Is Nothing Then
    cam = New AsfFilter.Capture(VIDEODEVICE, textBox1.Text)
    previewCamera(PictureBox1) <----- this is my code regarding on previewing the video recording.
    cam.Start()

    button1.Text = "Stop"
    textBox1.[ReadOnly] = True
Else
    button1.Text = "Start"
    textBox1.[ReadOnly] = False

    ' Pause the recording
    cam.Pause()

    ' Close it down
    cam.Dispose()
    cam = Nothing
End If

Cursor.Current = Cursors.[Default]

Error:

Insufficient system resources exist to complete the requested service. (Exception from HRESULT: 0x800705AA)

What am I doing wrong? Did somebody know of this?

A: 0x800705AA: ERROR_NO_SYSTEM_RESOURCES "Insufficient system resources exist to complete the requested service."
Here is the thing you need to know: video capture devices are exclusive access resources. You use it once, you cannot use it simultaneously again on another filter graph (that is, one graph for recording, and another one for monitoring). You have to have single filter graph to host video capture. From there, you can either use Smart Tee Filter, or Infinite Pin Tee Filter to duplicate the video feed on recording and monitoring legs. Or, alternatively, use multigraph solution with still video capture taking place on single graph.


text:
Q: In Jdbi3, how can I use bindBean() for same field? I have Java code:
String updateSql = "UPDATE table_name SET field_two = :field_two"
                + " WHERE field_one = :field_one AND field_two <> :field_two";
handle.createUpdate(updateSql)
    .bindBean(myBean)
    .execute();

@Data
public class MyBean() {
   private String fieldOne;
   private String fieldTwo;
}

When Jdbi tries to bind the field_two the second time, it throws UnableToCreateStatementException: Missing named parameter field_two in binding.
How can I bind the field_two appeared multiple times in the query using bindBean()?

A: It turns out that the binding needs to have the same name with the field name:
String updateSql = "UPDATE table_name SET field_two = :fieldTwo"
                + " WHERE field_one = :fieldOne AND field_two <> :fieldTwo";


text:
Q: Importing a RTF file in a UIWebView (content editable) I declared my App (a rich text editor) to be able to open any RTF file (coming, for example, from an email attachment). The application delegate sends a "loadContent: (NSURL *) url" message to the UiwebView controller when the user select the attachment. In the receiver, I get the url and load the RTF file in the UIWebView using
- (void) loadContent: (NSURL *) passedURL
{
    if (passedURL) {
        [self.myWebView loadRequest:[NSURLRequest requestWithURL:passedURL]];
    } else {
        NSBundle *bundle = [NSBundle mainBundle];
        NSURL *indexFileURL = [bundle URLForResource:@"index" withExtension:@"html"];
        [self.myWebView loadRequest:[NSURLRequest requestWithURL:indexFileURL]];

    }
}

Doing that, everything goes all right, and "myWebView" displays the content of the RTF file. The problem is that this view should be content editable, and the code should contain some javascript that I have in my "index.html" bundled file. I load when starting application. So I added some code to extract the HTML code created from the RTF file to be able later to recreate a complete code, inserting the extracted code in a  tag like that:

 imported html from rtf should be there

I modified the loadContent method to get that.
- (void) loadContent: (NSURL *) passedURL
{
    if (passedURL) {
        [self.myWebView loadRequest:[NSURLRequest requestWithURL:passedURL]];
        NSString *dum=[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML;"];
        NSLog(@"%@",dum);
    } else {
        NSBundle *bundle = [NSBundle mainBundle];
        NSURL *indexFileURL = [bundle URLForResource:@"index" withExtension:@"html"];
        [self.myWebView loadRequest:[NSURLRequest requestWithURL:indexFileURL]];

    }
}

Looking to the result of the NSLog, I get only the following html

Hello folks

Which was the HTML content of myWebView BEFORE I loaded the rtf file...
Do you have any idea of what is going on? Why does dum displays the former code, as the displayed myWebView displays the new one? Is it because the loadRequest is executed in a separated thread and that when executing the next instruction, myWebView still contains the former code?
Thanks
[EDITED] I also tried to NSLog the content of the webView in webViewDidFinishLoad: delegate method, but get the same result: the content of this webView before I opened the RTF attachment file. Is It possible to make a load request in a synchronous way?

A: This is because loadRequest is asynchronous. You need to wait for the load to finish before trying that NSLog. Take a look at the UIWebViewDelegate docs. Try that NSLog inside/after webViewDidFinishLoad: and you should get better results.


text:
Q: Clicklistner in webview The question can be a little vague, I have created a webview and showing the webpage of the URL which I get from some server. Now When i navigate to different pages , On one page there is only a button which will send me a different URL , I need that when user is on that page and click on that button the webview should hide and user continue other operation. I have read that addJavascriptInterface is needed to do this , can anyone tell me if this is possible and how to achieve this , any good tutorial will work.
I also tried this but of no use
 wv.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            HitTestResult result = wv.getHitTestResult();
            if (result.getType() == HitTestResult.UNKNOWN_TYPE) {
                Message msg = mHandler.obtainMessage();
                wv.requestFocusNodeHref(msg);
            }
            return false;
        }
    });

A:     topupWV.setWebViewClient(new WebViewClient());
        topupWV.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {

                    if (url.startsWith("XXXXX")) {

                        try {
                            URL urls = new URL(url);
                            query = urls.getQuery();

                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }

                        return true;
                }

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);

                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                }

            });

}

A: you can do something like this for detecting click within a webview
webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (isNetworkConnected()) {
                    //DO YOU OPERATION HERE
                }
                return true;
            }
        });


text:
Q: How to 'leave pair out' where each test pair consists of [0 1] I am building a machine learning classifier and want to use 'leave pair out' cross-validation, with non-overlapping pairs, where each pair contains one instance from the negative class and one from the positive, i.e. the ground truth labels or y values in each test set fold would be  [0 1].
I can't work out how to achieve this in Scikit learn. I have 50 instances (with 25 in each class) so I can do:
split = KFold(n_splits=50 // 2, shuffle=True, random_state=42)
to get non-overlapping pairs but this doesn't give me test sets of [0 1]. I have looked at the documentation for LeavePGroupsOut but this doesn't seem to be what I want.
Can anyone point me in the right direction? Thank you!

A: I believe you may want StratifiedKFold. This class creates folds while maintaining the label balance; combined with your current technique of using 25 folds, that should do the trick.


text:
Q: Getting error while using split method for reading multiple integers in a single line I am getting an error while using Split while reading an integer from the user
 int[] a = new int[s];
        for (i = 0; i < s; i++)
        {
            a[i] = Int32.Parse(Console.ReadLine().Split(' '));
        }

Can you please help me how to use Split.

A: Since split returns an array, and each time you need the i'ed one, you should change it like this:
 int[] a = new int[s];
 string[] input = Console.ReadLine().Split(' ');

 for (i = 0; i < s; i++)
 {
    a[i] = Int32.Parse(input[i]);
 }

You need to read the input only once btw.
Like @loneshark99 said it would be even better to use TryParse(). Since that returns a boolean, you can check if the input are indeed integers. If you just use Parse and they are not integers, it would throw an exception.
Code with TryParse():
 int[] a = new int[s];
 string[] input = Console.ReadLine().Split(' ');

 for (i = 0; i < s; i++)
 {
    if (Int32.TryParse(input[i], out a[i]))
    {
        //successfully parsed
    }
 }

The if-statement is not necessary but it's just to point out how you could use the TryParse.

A: LINQ can really help you here:
int[] a = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

A: We can take the input as string first
   string[] array_temp = Console.ReadLine().Split(' ');

and then convert the array into Int
   int[] array = Array.ConvertAll(array_temp,Int32.Parse);


text:
Q: AnnotationException: @OneToOne or @ManyToOne on MySchema$Parent.propertyX references an unknown entity: MySchema$Child I am new to R3 Corda. I have been stuck into this problem. Its been hours I am trying to figure out this problem.  I am getting Hibernate AnnotationException on running the nodes. Here is my schema declaration file NewIndicationSchema.java.
package com.myproject.schema;

import com.google.common.collect.ImmutableList;
import net.corda.core.schemas.MappedSchema;
import net.corda.core.schemas.PersistentState;
import org.hibernate.annotations.Cascade;

import javax.persistence.*;
import org.hibernate.annotations.CascadeType;
import java.util.Date;

/**
 * The family of schemas for NewIndication.
 */
public class NewIndicationSchema extends MappedSchema {
    public NewIndicationSchema() {
        super(NewIndicationSchema.class, 1, ImmutableList.of(Indication.class));
    }

    @Entity
    @Table(name = "new_indications", uniqueConstraints = {@UniqueConstraint(columnNames = "indicationNo")})
    public static class Indication extends PersistentState {
        @Column(name = "_id", unique = true, nullable = false) private final String _id;
        @Column(name = "indicationNo") private final String indicationNo;
        @Column(name = "status") private final String status;
        @Column(name = "effDate") private final Date effDate;
        @Column(name = "programID") private final String programID;

        @OneToOne(fetch = FetchType.LAZY, targetEntity = Insured.class)
        /*@JoinColumns(@JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))*/
        @Cascade(value = CascadeType.PERSIST)
        private final Insured insured;

        public Indication(Indication indication){
            this._id = indication.get_id();
            this.indicationNo = indication.getIndicationNo();
            this.status = indication.getStatus();
            this.insured = indication.getInsured();
            this.effDate = indication.getEffDate();
            this.programID = indication.getProgramID();
        }

        public String get_id() {
            return _id;
        }

        public String getIndicationNo(){
            return this.indicationNo;
        }

        public String getStatus(){
            return this.status;
        }

        public Date getEffDate(){
            return this.effDate;
        }

        public Insured getInsured(){
            return this.insured;
        }

        public String getProgramID() {
            return programID;
        }
    }

    @Entity
    @Table(name = "insureds")
    class Insured {

        @OneToOne(mappedBy = "new_indications")
        private final Indication indication;
        @Column(name = "name") private final String name;
        @Column(name = "dba") private final String dba;
        @Column(name = "city") private final String city;
        @Column(name = "address1") private final String address1;
        @Column(name = "address2") private final String address2;
        @Column(name = "state") private final String state;
        @Column(name = "zip") private final String zip;

        public Insured(Indication indication, String name, String address1, String address2, String city, String state, String zip, String dba) {
            this.indication = indication;
            this.name = name;
            this.dba = dba;
            this.address1 = address1;
            this.address2 = address2;
            this.city = city;
            this.state = state;
            this.zip = zip;
        }
        // Getters
        public Indication getIndication() {
            return indication;
        }
        public String getName(){
            return this.name;
        }
        public String getDba(){
            return this.dba;
        }
        public String getAddress1(){
            return this.address1;
        }
        public String getAddress2(){
            return this.address2;
        }
        public String getCity(){
            return this.city;
        }
        public String getState(){
            return this.state;
        }
        public String getZip(){
            return this.zip;
        }
    }
}

I am able to build with no exceptions but when I try to run the nodes I get this bellow errors logged onto the node's command prompt. I've been trying all the solutions over the internet but none of them were related to Corda. All of them are related to Hibernate only. I feel like I am missing any special annotation from Corda or the way I am thinking of the schema is wrong. Please help me.
    E 02:01:26+0530 [main] internal.Node.run - Exception during node startup {}
     org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.myproject.schema.NewIndicationSchema$Indication.insured references an unknown entity: com.myproject.schema.NewIndicationSchema$Insured
            at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:97) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
            at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processEndOfQueue(InFlightMetadataCollectorImpl.java:1752) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
            at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1696) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
            at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1583) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
            at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
            at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
            at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
            at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
            at net.corda.nodeapi.internal.persistence.HibernateConfiguration.buildSessionFactory(HibernateConfiguration.kt:105) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.HibernateConfiguration.makeSessionFactoryForSchemas(HibernateConfiguration.kt:63) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.HibernateConfiguration.access$makeSessionFactoryForSchemas(HibernateConfiguration.kt:26) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.HibernateConfiguration$sessionFactoryForSchemas$1.apply(HibernateConfiguration.kt:44) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.HibernateConfiguration$sessionFactoryForSchemas$1.apply(HibernateConfiguration.kt:26) ~[corda-node-api-3.2-corda.jar:?]
            at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(Unknown Source) ~[?:1.8.0_181]
            at net.corda.nodeapi.internal.persistence.HibernateConfiguration.sessionFactoryForSchemas(HibernateConfiguration.kt:44) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.HibernateConfiguration.<init>(HibernateConfiguration.kt:40) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence$hibernateConfig$2$1.invoke(CordaPersistence.kt:64) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence$hibernateConfig$2$1.invoke(CordaPersistence.kt:51) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:136) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:124) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:131) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence$hibernateConfig$2.invoke(CordaPersistence.kt:63) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence$hibernateConfig$2.invoke(CordaPersistence.kt:51) ~[corda-node-api-3.2-corda.jar:?]
            at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:130) ~[kotlin-stdlib-1.1.60.jar:1.1.60-release-55 (1.1.60)]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.getHibernateConfig(CordaPersistence.kt) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.getEntityManagerFactory(CordaPersistence.kt:67) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.DatabaseTransaction$sessionDelegate$1.invoke(DatabaseTransaction.kt:31) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.DatabaseTransaction$sessionDelegate$1.invoke(DatabaseTransaction.kt:16) ~[corda-node-api-3.2-corda.jar:?]
            at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:130) ~[kotlin-stdlib-1.1.60.jar:1.1.60-release-55 (1.1.60)]
            at net.corda.nodeapi.internal.persistence.DatabaseTransaction.getSession(DatabaseTransaction.kt) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.node.services.network.PersistentNetworkMapCache$start$$inlined$synchronized$lambda$1.invoke(PersistentNetworkMapCache.kt:99) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.services.network.PersistentNetworkMapCache$start$$inlined$synchronized$lambda$1.invoke(PersistentNetworkMapCache.kt:75) ~[corda-node-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:136) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:124) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:131) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.node.services.network.PersistentNetworkMapCache.start(PersistentNetworkMapCache.kt:99) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.AbstractNode$start$4.invoke(AbstractNode.kt:207) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.AbstractNode$start$4.invoke(AbstractNode.kt:105) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.AbstractNode$initialiseDatabasePersistence$2.invoke(AbstractNode.kt:685) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.AbstractNode$initialiseDatabasePersistence$2.invoke(AbstractNode.kt:105) ~[corda-node-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.inTopLevelTransaction(CordaPersistence.kt:152) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:138) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:124) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:131) ~[corda-node-api-3.2-corda.jar:?]
            at net.corda.node.internal.AbstractNode.initialiseDatabasePersistence(AbstractNode.kt:684) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.Node.initialiseDatabasePersistence(Node.kt:345) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.AbstractNode.start(AbstractNode.kt:206) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.Node.start(Node.kt:359) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.NodeStartup.startNode(NodeStartup.kt:145) ~[corda-node-3.2-corda.jar:?]
            at net.corda.node.internal.NodeStartup.run(NodeStartup.kt:115) [corda-node-3.2-corda.jar:?]
            at net.corda.node.Corda.main(Corda.kt:13) [corda-node-3.2-corda.jar:?]

A: You need to include all the Schema entities you are referencing in the constructor:
super(NewIndicationSchema.class, 1, ImmutableList.of(Indication.class, Insure.class));


text:
Q: HTML5 Canvas - Drawing a line inside a circle at specific angle Javascript
var canvas = document.getElementById("mycanvas");
draw(canvas);

function draw(canvas){
    var context = canvas.getContext('2d'), centerX = Math.floor(canvas.width / 2), centerY = Math.floor(canvas.height / 2),radius = Math.floor(canvas.width / 2);
    context.lineWidth = 1;
    context.strokeStyle = 'black';
    var begin = 0; interval = 90;
    var arcSize= degreesToRadians(interval);
    for(var startingAngle=begin; startingAngle < 360;){
        context.beginPath();
        context.moveTo(centerX, centerY);
        context.arc(centerX, centerY, radius, degreesToRadians(startingAngle), startingAngle + arcSize, false);
        context.closePath();
        context.stroke();
        startingAngle = startingAngle + interval;
    }
    lineAtAngle(context,centerX,centerY,radius,30);
}

function degreesToRadians(degrees) {
    return (degrees * Math.PI)/180;
}

function lineAtAngle(context,x1, y1, length, angle) {
    context.beginPath();
    context.moveTo(x1, y1);
    context.lineTo(x1 + length * degreesToRadians(angle), y1 + length * degreesToRadians(angle));
    context.strokeStyle = 'red';
    context.closePath();
    context.stroke();
}

HTML
<canvas id="mycanvas" width="400" height="400"></canvas>

JSFiddle
What I am trying to achieve
Pass the value of angle at which the red line needs to be drawn and it should be drawn at that angle.

A: I have managed to achieve it with following code. A bit hacky but it works. Not sure why I need to multiple the angle by -1.
var canvas = document.getElementById("mycanvas");
draw(canvas, 167);

function draw(canvas, angle){
    var context = canvas.getContext('2d'), centerX = Math.floor(canvas.width / 2), centerY = Math.floor(canvas.height / 2),radius = Math.floor(canvas.width / 2);
    context.lineWidth = 1;
    context.strokeStyle = 'red';
    var begin = 0; interval = 90;
    var arcSize= degreesToRadians(interval);
    context.beginPath();
    context.moveTo(centerX,centerY);
    context.arc(centerX,centerY,radius, degreesToRadians(0), degreesToRadians((-1) * angle),false);
    context.closePath();
    context.stroke();
    context.strokeStyle = 'black';
    context.lineWidth = 2;
    for(var startingAngle=begin; startingAngle < 360;){
        context.beginPath();
        context.moveTo(centerX, centerY);
        context.arc(centerX, centerY, radius, degreesToRadians(startingAngle), startingAngle + arcSize, false);
        context.closePath();
        context.stroke();
        startingAngle = startingAngle + interval;
    }
}

function degreesToRadians(degrees) {
    return (degrees * Math.PI)/180;
}

JSFiddle


text:
Q: access images from assets in css file My bootstrap layout was doing the following:
body {
...
 background-image:url('../img/bg.png');
}

now this worked fine. However, when integrating with rails, the image isn't showing up, the path is still correct:
assets > stylesheets > docs.css (has the line mentioned above)
assets > img > bg.png

however, its not working, and I can't figure out why. Any help would be appreciated.
Thanks

A: Try
body {
...
 background-image:url('bg.png');
}


text:
Q: Application behaves differently on different machines I am learning about streams and copied the following application from the text book. When my friend compiles and runs on his Windows machine, it works fine. When I run the application on my Ubuntu 18.04 machine, the input works fine, but the values don't seem to have any effect on the application, i.e. entering 0 does not cause the program to exit. My output is below the code.
What would cause different behavior when compiling on different machines, and why is this not working on my machine?

int main(int argc, char* argv[])
{
    FILE        *fpt;
    char        byte;
    long int    where,move;

    if(argc != 2)
    {
        printf("Usage: fileseek filename\n");
        return(0);
    }

    fpt = fopen(argv[1], "r");

    if(fpt == NULL)
    {
        printf("Unable to open file %s for reading\n", argv[1]);
        return(0);
    }

    while(1)
    {
        where = ftell(fpt);

        fread(&byte,1,1,fpt);
        fseek(fpt,-1,SEEK_CUR);

        printf("Byte %d: %d (%c)\n", where, byte, byte);
        printf("Enter #bytes (+ or -) to move, or 0 to quit: ");

        scanf("%d", &move);

        printf("move: %d\n", move);

        if(move == 0)
            break;

        fseek(fpt,move,SEEK_CUR);
    }
    fclose(fpt);
}

Output
jonathon@dev1:~/hoover/ch5/build$ ./fileseek  text.txt
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 0
move: 0
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 1
move: 1
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 2
move: 2
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 3
move: 3
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 4
move: 4
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 5
move: 5
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: ^C

A: The textbook is wrong if it that's exactly what it says: %d is a conversion specifier for an int, but move is a long int. The correct call would be:
scanf("%ld", &move)

, with similar corrections to several printf calls.
It can work by coincidence, especially when long and int happen to be the same size (as they are in 64-bit Windows, but not in 64-bit Linux).  With the mismatches, however, no particular behaviour is defined for the entire program: the compiler is allowed by the language standard to assume that the kind of illegal actions they represent never happen, and has no obligation whatever as to what a program that performs such an action may do.


text:
Q: How can I match the length of one variable to another in python? I am currently developing this python code and I am trying to match the length of the user's surname to their name length.
If the user's surname is greater than their message, then the code will successfully subtract the excess characters in the user's name to make both variables equal.
However if the user's name is greater than their surname, the code should loop through the user's surname and add the required amount of characters to make both variables equal.

A: I use this function :
def pad(key, wanted_len):
    lk = len(key)
    if lk > wanted_len:
        return key[:wanted_len]
    else:
        bigerkey = key * ((wanted_len / lk) + 1)
        return bigerkey[:wanted_len]

The first part of the if is pretty straightforward: if the key is larger than you expect, just truncat it. Otherwize, use the operator * on key to repeat n times, where n is the expected siwe divised by the size of the key.
for example:
>>> print 'hello ' * 5
hello hello hello hello hello

A nice suggestion from horns simplifies the previous code:
def pad(key, wanted_len):
   return (key * ((wanted_len // len(key)) + 1))[:wanted_len]

Another possible (more pythonic) is to use itertools.cycle:
def pad(key, len):
    it = itertools.cycle(key)
    return ''.join([it.next() for _ in xrange(len)])

The iterator on the key will pop you out a letter in the order of the iterable provided (key here) at each next(), and cycle in the end of the itirable.

A: from itertools import cycle
def combine(text, keyword):
    return ''.join(key for key, char in zip(cycle(keyword), text))

cylce makes an infinite generator over your keyword. for a keyword like 'abc' it will yield a, b, c, a, b, c, a, .... zip will stop after iterating over your text.
Stepwise explanation of the function:
zip (more information: https://docs.python.org/2/library/functions.html#zip)
for a, b in zip( [1, 2, 3], ['a', 'b']):
    print (a, b)
#1 a
#2 b
# stops after 2 steps, because ['a', 'b'] has only two elements

cycle makes an infinite generator:
keyword = '12'
# cycle(keyword) -> 1 2 1 2 1 2 .... (infinite times)
text = 'abcde'
for key, char in zip(cycle(keyword), text):
    print (key, char)
# 1 a
# 2 b
# 1 c
# 2 d
# 1 e
#stops (cause len(text) == 5)
keys = [key for key, char in zip(cycle(keyword), text)]
#keys == [ '1', '2', '1', '2', '1']
newkeyword = ''.join(keys)
#join joins a iterable of strings with '' as delimiter between them
#newkeyword == '12121'


text:
Q: Vite and dealing with require vs import (for google api) First time using Vite with google apis and right at the start ran into trouble trying to import the translation client. It uses 'require' to import it  const {TranslationServiceClient} = require('@google-cloud/translate') instead of 'import' syntax. I've tried workarounds including the vite require plugin but nothing has worked (reworking it into an import statement causes different errors with 'process not defined' which just stumped me even more) and it seems strange that no one else seems to mention any problem with vite and google apis. Has anyone run into this issue?

A: Did you try?
import TranslationServiceClient from "@google-cloud/translate";


text:
Q: cant figure how to sum nested id tables I have a table like this
LEVEL_01   LEVEL_02    LEVEL_03
---        ---         ---
10010      10030       30010
10010      10040       30030
10010      10040       30040
10020      20010       20080
10020      10040       20080
10020      10040       20090
10021      20020       40000

and a table with amounts of the last level
id         amount
---     -------------
30010      100.00
30030      190.00
30040      800.00
30040      700.00
40000      250.00
20080      320.00
20090      500.00

What I need is to show sum data from the three levels, grouping / nesting levels like:
10010->10030->30010
10010->10040->30030
10010->10030->30040
-------------------
10010=sum(30010)+sum(30030)+sum(30040)=(100.00)+(190.00)+(1500.00) = 1790.00
10030=sum(30010)+sum(30040)=(100.00)+(1500.00) = 1600.00
30040=sum(30040) = 1500.00

(one record for LEVEL_10 thru LEVEL_03 and their relative sum.

Cant make it work. Any help will be appreciated

A: You can just do the sum with a join and then union the results for each level, like:
SELECT LEVEL_01, sum(amount)
FROM table1 INNER JOIN table2 ON table1.level_03 = table2.id
GROUP BY LEVEL_01
UNION ALL
SELECT LEVEL_02, sum(amount)
FROM table1 INNER JOIN table2 ON table1.level_03 = table2.id
GROUP BY LEVEL_02
UNION ALL
SELECT LEVEL_03, sum(amount)
FROM table1 INNER JOIN table2 ON table1.level_03 = table2.id
GROUP BY LEVEL_03;


text:
Q: Unable to login via FTP unless shell is enabled I'm trying to set up FTP access on a Debian box running Apache. Creating an FTP user via useradd works over port 22... but only if I don't restrict shell access via -s /dev/null.
I've got vsftpd installed, and have theoretically opened up port 21 with iptables. But attempting to connect over this port causes the FTP client to completely hang and never connect.
Here're the iptables rules I applied:
iptables -A INPUT -p tcp -s 0/0 --sport 1024:65535 -d 202.54.1.20 --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s 202.54.1.20 --sport 21 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp -s 0/0 --sport 1024:65535 -d 202.54.1.20 --dport 1024:65535 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -p tcp -s 202.54.1.20 --sport 1024:65535 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s 202.54.1.20 --sport 20 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp -s 0/0 --sport 1024:65535 -d 202.54.1.20 --dport 20 -m state --state ESTABLISHED -j ACCEPT

A: Try /bin/false as the shell instead of /dev/null. FTP is likely hanging because it's not able to execute /dev/null.

A: As already suggest, use /bin/false instead of /dev/null.
Check if /bin/false is inserted in /etc/shells.
Or you could use nologin(8).


text:
Q: How to migrate a database from a local to a remote server? I have a postgres db that I have created and need to deploy remotely. From reading online I have understood that to do that I need to modify the following files :

*

*pg_hba.conf

*postgresql.conf
From what I read I need to modify them and somehow add them to my database?
My question is:

*

*How do I modify the 2 files to deploy a database online? I read the documentation but its too complicated for my understanding.(ie what is needed and why?)

*How do I add them to my database online? My idea was to create a database dump of the local DB, then push the dump on a new database on the remote computer, but how do these 2 files fit in there? Where should there be placed? I cannot find details on this.
note. I have never done distributed programming before, my question might be naive but I really have no idea how to proceed.
I am using osX operating system,but will be using linux on the remote computer.

A: The two configuration files apply to the server, so both your local and remote server already have those files and their contents is specific to the installation.
Assuming your remote server is already up and running, all you need to do is dump the database you want to deploy to a file and then load the dump file in your remote server. You do not have to do anything with the configuration files.
You can use pg_dump to dump the local database to file, doing something like this:
pg_dump -U postgres -Fc my_db > my_db.db

But check all the options of the pg_dump program.
Loading the database on your remote server is just as easy with pg_restore:
pg_restore -h <ip remote server> -p <port remote server> -U postgres -C my_db.db

On the remote server you need to specify a user who can create databases, if you do not have access to the postgres role.
If you are on some flavour of *nix you can even pipe pg_dump output into pg_restore input and do it all in one go:
pg_dump -U postgres -Fc my_db | pg_restore -h <ip> -p <port> -U postgres -C

Note that pg_dump will ask for a password on the local server (if at all) and pg_restore will for a password on the remote server (if at all).
Both programs have a lot of options. Be sure to read the documentation fully and use options to match your situation before coming back to tell me that it doesn't work.