text:
Q: Edit HTML Response before sending I have a webservice that is going to receive a request, perform an action in java, and then return a response as standard.
The client expecting the response however, is expecting the HTTP response to have two characters appended to the end of the message (any, it does not matter, currently just \n\n, and for reasons unknown to me - it's legacy code), outside of the headers and body.
Presently it is done by sending the HTTP message first to a proxy, which appends the characters and forwards the message, but does anyone know of a way that this can be done in java without the need for a proxy?
I.e. - Can I access the full HTML response to edit it before it is sent?
Edit: The client is not a browser, but an application sending SOAP messages.

A: Assuming that this is being ran as a webserver following the servlet spec you could use a filter.
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter(asyncSupported = true, filterName = "LegacyAppender", urlPatterns = { "/paths/tofile" })
public class AppendFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(req, resp);
        HttpServletResponse hsr = (HttpServletResponse) resp;
        hsr.getWriter().print("\r\n");
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }
}

A: We ended up using apache-cxf interceptors, as we only needed the full SOAP message in the end. By adding an outgoing interceptor that converted the SoapMessage content to a string, added the two characters and set the content again, our issue was fixed.
Thanks anyway!


text:
Q: Skip lines containing only commas in csv files How to read csv files so that lines containing only commas are skipped?
Skip all leading empty lines in read.csv
covers couple ideas for the case that these lines are in the beginning of the file, but what about a more generic solution?

A: I am not sure about the performance but you can do this with the help of readLines(), grepl() and writeLines() function:
Assuming input file is A.csv and the output CSV file (though not necessary)which will not contain commas be B.csv.
test <- readLines('A.csv')

test2 <- test[!grepl(",",test)]

Either you can use test2 variable or save that to B.csv:
writeLines(test2,'B.csv')

redpajama_set_name: RedPajamaStackExchange


text:
Q: replace unique, noninteger varchar with unique integer in postgres I have a postgres table 'labs' with two columns (col1 varchar, col2 varchar).
col1   |  col2
1.2.3  |   a
1.2.3  |   b
3.4.4  |   c
3.4.4  |   d
2.6.9  |   e
2.6.9  |   f

I would like to replace col1 with an integer like this
col1   |  col2
1  |   a
1  |   b
2  |   c
2  |   d
3  |   e
3  |   f

Does anyone know an efficient statement to do this?

A: You can do this in a select query using:
select dense_rank() over (order by col1) as col1, col2

This doesn't produce exactly the results you want (it would be 1, 3, 2).  SQL tables represent unordered sets.  Your data doesn't have enough information to assign the second value a value of "2" rather than "3".
You can also incorporate this into an update, but that wouldn't be recommended because the current value is a string and the result you want is an integer.


text:
Q: Two (or more) looks, with one set of content I'd like to set up a pair of sites (red and blue) with different looks (backgrounds, header images), but the same content (pages, text, embedded media, etc.) And I'm trying to minimise the effort keeping them synced once set up.
e.g., the two sites might have a root URL like: http://example.com/red and http://example.com/blue. The URLs http://example.com/red/about and http://example.com/blue/about would both show the same about page, ideally edited in only one instance and auto-magically updated in the other.
Ideally I'd like to be able to have users flip from one to the other like a multilingual site.
I've thought about mirroring red to blue and then customise blue; but I expect to have to updated red in the future and I don't want to have to redo the mirror/customisation each time.
Have I missed a convenient way/plugin for accomplishing this kind of situation?
Is there a better way? Or am I going to be maintaining content on two sites with different looks.

A: I've done something pretty simmilar once where I had 2 websites that shared most of their content and had differing color schemes. Here's how I would approach this challenge
Use Multisite and child themes in the following way:

*

*Website 1: This holds the content and acts as the main theme (e.g. Red). This is just a regular WordPress site — no funky stuff going on here.

*Website 2: This installation switches to blog 1 (<?php switch_to_blog( $website_1_id ); ?>) whenever it queries data and then uses a child theme to apply the blue styling.
Multisite will give you the ability to have different URL's for the two sites and still query for content between the sites.
You can even use domain mapping to have completely different url's like my-red-website.com and my-green-website.com
Child themes will make it much easier to maintain the two themes in the future, as all of your functionality lives in the main theme (website 1). Your child theme (website 2) inherits everything from the main theme and builds on top of that with custom CSS and PHP. Whenever you add new functionality to website 1 it automatically cascades down to website 2 as well.
I'm not sure that there aren't any gotcha's with this approach, but if I was in your shoes this is the path I'd try first.


text:
Q: How to calculate voltage drop across a coaxial transmission line? I am an engineering student and I want to ask a question for my assignment.
How can I calculate voltage amplitude drop across a coaxial transmission line without input function? (How many percent of amplitude is dropped across certain distance?)
In my understanding, the voltage at certain point can be predicted as:

To predict amplitude drop across distance, we just need to calculate this term:

This term is the percentage of amplitude at certain point.
But isn't k and gamma calculated from input function?


text:
Q: Popup window in chrome extension? I am working with chrome extension development.
Here I am call URL by xml http request:
var xhr = new XMLHttpRequest();
xhr.open("GET", "URL", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
   var resp = JSON.parse(xhr.responseText);
    alert(resp);
    alert(xhr.responseText);
  // innerText does not let the attacker inject HTML elements.
 //document.getElementById("resp").innerText = xhr.responseText;
}
}
xhr.send();

When I posting same script popup window will open when send request But in case of chrome popup window not working.
When I hit same URL in browser then also a popup window open.
Please suggest me why this not working in case of chrome development.

A: Javascript alerts are not working in extension popups, you should avoid them. Use console.log instead.

A: put a check for xhr before xhr.open, if undefined then initialize it again. install some debugging tool like fiddler or firebug for chrome. and debug xhr in chrome.  xmlhttprequest has problems sometimes with browsers

A: Javascript alert() is working in chrome extension popup but not perfect this time. The position of the alert window is not necessary in the middle of the screen but close to the top left corner. Sometimes it turns that the alert window doesn't (or hardly) appears, it is out from the visible screen. Annoying bug...my chrome always froze when I launched two alerts. The reason was the second alert window didn't appear, but when I hit the enter it run ahead.
console.log('test') --> keep mind you have to click on inspect popup (right click on the popup icon) instead inspect element (right click on the webpage).


text:
Q: Exporting QGIS Raster/Vector layers into one PDF? I have seen a similiar post to this a while back (Is it possible to export geospatial PDF from QGIS via GDAL/OGR?), and thought I would try asking it again to see if there has been any improvement or new knowledge on this.
Is it possible to export one PDF with multiple layers like the picture shows?

The above shows a Raster image (WMS) and 4 different Vector layers, is it possible to get all these into one PDF as different layers? As shown below, where you can click/unclick each layer?


text:
Q: Questions on learning assembly for a CTF challenge I've just started to dip into Assembly for CTF reversing challenges, and am having a great time. The current challenge I'm working on has me stumped, however - hoping someone can help with a few basic Assembly questions - or point me to good resources.
I ran the binary provided for the challenge through Binary Ninja and identified the key function - tracing the logic within that function is giving me problems.
The function starts in a fairly straightforward way - I've added my own comments to the best of my understanding:
08048661  push    ebp {__saved_ebp}  ;Push old base pointer onto stack
08048662  mov     ebp, esp {__saved_ebp} ;Function preamble (?)
08048664  sub     esp, 0x18
08048667  sub     esp, 0xc
0804866a  push    dword [ebp+0x8 {arg1}] {var_2c} ;var_2c is user input (arg1)
0804866d  call    strlen ;Get the string length of user input
08048672  add     esp, 0x10 ;??
08048675  mov     dword [ebp-0x10 {var_14}], eax  ;Assign EAX to var_14
08048678  cmp     dword [ebp-0x10 {var_14}], 0x13
;Compares string length to 0x13 (decimal 19) - if it's longer continue
0804867c  ja      0x8048688

This first block seems to get the string length of the user input - and if the string length is greater than 19 it continues to the next block.
This next block is where I think my understanding is incorrect:
08048688  mov     eax, dword [ebp+0x8 {arg1}]
;Set EAX to the memory location of the user input (arg1)
0804868b  movzx   eax, byte [eax]
;Replace EAX with the first byte of EAX (arg1)
0804868e  cmp     al, 0x61
;Compare the first byte of EAX with 0x61 (decimal 97 / binary 01100001)
;if equal, continue to next block
08048690  je      0x8048699

This would imply that the first byte of the correct response would have to be 01100001 - but that seems to be contradicted by the next block:
08048699  mov     eax, dword [ebp+0x8 {arg1}]
;Set EAX to the memory location of the user input (arg1)
0804869c  add     eax, 0x1
;Add 0x1 to EAX (decimal 1 / binary 00000001)
0804869f  movzx   eax, byte [eax]
;Replace EAX with only the first byte of EAX (arg1+1)
080486a2  cmp     al, 0x71
;Compare the first byte of EAX with 0x71 (decimal 113 / binary 01110001)
;if equal, continue to next block
080486a4  je      0x80486ad

This is where I'm currently stuck - if the first byte of the input needs to be decimal 97 / binary 01100001 to pass the second block, then how could adding 1 to it possibly result in the decimal 113 / binary 01110001 required to pass the third block of code?
I'm not sure where my understanding of the code is incorrect - very much appreciate any tips or pointers. Apologize if this covers basic knowledge - I'm working through these on my own.
Thank you!

A: Well it's not adding one that should result in 113. If you look closer you should notice that adding 1 to eax is done before reading the character value again to eax. Only this new loaded value is compared with 0x71. So this first operation just serves as an index incrementation.
A bit more explanation:
08048699  mov     eax, dword [ebp+0x8 {arg1}]

This loads the address of the input buffer to eax.
0804869c  add     eax, 0x1

After this eax points to the second character in the input buffer.
0804869f  movzx   eax, byte [eax]

This line loads the character that eax points to (input buffer), to eax (extending with zeros to 32bits).
And only after the last line you have your comparison with 0x71. So the second character should be 'q'.

If add eax, 0x1 points eax to the second character in the input buffer, does that mean that movzx eax, byte [eax] without add eax, 0x1 points to the first character in the buffer?

Yes, and you had that code/pattern in the first block under addresses: 08048688 & 0804868b. There's no add eax,1 and the rest is the same.

does dword [ebp+0x8 {arg1}] always signify the input buffer, or only in this case?

Only in this case - this [ebp+0x8] basically points to the argument on the stack - in this case it's input buffer but it doesn't have to be like that.
BTW, I think you would be better with such questions on Reverse Engineering.


text:
Q: how to track down my custom module issue?it throw out error how do I track where the problem of my custom module.
I got below error.
Fatal error: Uncaught Error: Call to undefined method ABC\NewsletterCrm\Controller\Subscriber\Confirm\Interceptor::loadByCustomerId() in /app/vendor/magento/module-customer/Block/Account/Dashboard/Info.php:105 Stack trace:
#0 /app/vendor/magento/module-customer/Block/Account/Dashboard/Info.php(120): Magento\Customer\Block\Account\Dashboard\Info->getSubscriptionObject()
#1 /app/vendor/magento/module-customer/view/frontend/templates/account/dashboard/info.phtml(39): Magento\Customer\Block\Account\Dashboard\Info->getIsSubscribed()
#2 /app/vendor/magento/framework/View/TemplateEngine/Php.php(59): include('/app/vendor/mag...')
#3 /app/vendor/magento/framework/View/Element/Template.php(271): Magento\Framework\View\TemplateEngine\Php->render(Object(Magento\Customer\Block\Account\Dashboard\Info), '/app/vendor/mag...', Array)
#4 /app/vendor/magento/framework/View/Element/Template.php(301): Magento\Framework\View\Element\Template->fetchView('/app/vendor/mag...')
#5 /app/vendor/magento/module-customer/Block/Account/Dashboard in /app/vendor/magento/module-customer/Block/Account/Dashboard/Info.php on line 105

I wrote a override module at app\code\ABC\NewsletterCrm\Controller\Subscriber\Confirm.php
using Object Manager to getCustomerID, please help
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$subscribeCollection = $objectManager->create('Magento\Newsletter\Model\Subscriber');
$collection = $subscribeCollection->getCollection()
                                  ->addFieldToFilter('subscriber_id', $id);

foreach ($collection as $subscribe){

    $customerid = $subscribe->getCustomerId();

}


text:
Q: Regular expression: match youtube links, but not youtube embed code Could you help me, please. I need regular expression that match string like this:
http://www.youtube.com/watch?v=eE4qPqMYsp8

but not this:
<object width="500" height="700"><param name="movie" value="http://www.youtube.com/v/eE4qPqMYsp8&hl=ru&fs=1&rel=0" /><param name="wmode" value="transparent" /><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><embed src="http://www.youtube.com/v/eE4qPqMYsp8&hl=ru&fs=1&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="500" height="700">

I have this code:
%(?:(http://){0,1}(www.){0,1}youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|(http://){0,1}(www.){0,1}youtu\.be/)([^"&?/ ]{11})%

I don't know  how to exclude some parameters.

A: How about an expression like this:
(?:https?://)?(?:www\.)?youtube\.com/watch.+?\bv=[a-zA-Z0-9]+

You can certainly add in more options (e.g. (?:-nocookie)), but it might be specific enough like this already.


text:
Q: SQL query for Selecting from Multiple Tables in single database I am having 3 tables (c19 , c19b2, g26) in a database
I want to write a SQL Query to search and display all fields of the matched record.
I am using following query:
$query = "SELECT * FROM c19,c19b2,g26 WHERE armyno LIKE '%$searchTerm%'";

But it only works for table c19,
Data from the other 2 tables is not fetched.Each table has a field armyno
Please help me with this
Thank you.

A: Alright, you are not looking for a JOIN, but a UNION.
SELECT * FROM c19 WHERE armyno LIKE '%$searchTerm%'
UNION
SELECT * FROM c19b2 WHERE armyno LIKE '%$searchTerm%'
UNION
SELECT * FROM g26 WHERE armyno LIKE '%$searchTerm%'

That will let you query all three tables at the same time.

A: Which DB are you using?  This would have worked in SQL Server.  However, notice you are doing a cross join of every record to every record... usually you only want to match some records by restriction of a matching key, for example:
select
  *
from a
left join b on b.somekey = a.somekey
left join c on c.someotherkey = b.someotherkey

In SQL server you can just say *, but I'm taking it that in your DB engine that didn't work, so try specifying which table.  This may in some environments require aliasing as well:
select
  a.*,
  b.*,
  c.*
from tableA as a
left join tableB as b on b.somekey = a.somekey
left join tableC as c on c.someotherkey = b.someotherkey

Generally, you should see the columns from the first table, followed by the columns from the second table, followed by columns from the third table for a given row.  If you wanted to get all columns from all tables, but separately, then that would be 3 separate selects.
Lastly, if all 3 tables have "armyno" then I'd expect it to throw an ambiguous field error. In such case you'd want to specify which table's "armyno" field to filter on.


text:
Q: How to list all nearest scheduled jobs in bacula bconsole Is there a way to see all scheduled jobs in bconsol?. You can see the first 30 jobs by executing status dir command in bconsole but how to list all (all nearest). I don't want to see scheduled jobs for all month only all the nearest scheduled jobs.

A: From the current bacula console manual:

If you do a status dir, it will by default list the first occurrence
  of all jobs that are scheduled today and tomorrow. If you wish to see
  the jobs that are scheduled in the next three days (e.g. on Friday you
  want to see the first occurrence of what tapes are scheduled to be
  used on Friday, the weekend, and Monday), you can add the days=3
  option. Note, a days=0 shows the first occurrence of jobs scheduled
  today only. If you have multiple run statements, the first occurrence
  of each run statement for the job will be displayed for the period
  specified.


text:
Q: Websocket closing issue I am working on web application for client side which is user websocket connection to send/receive data.
Here is my problem.
If some parameter change on client side, I want to close my web socket connection and initiate new connection with new paramaeters.
I tried to close web socket connection bu using close(). But when I checked my browser console, websocket status is always 2.
Please help me to resolve this.

A: I am not completely sure of what problem you have, but if you set a handler for onclose, it will be triggered when you call close.
var ws = new WebSocket('wss://wss://echo.websocket.org');
ws.onclose=function(){
    alert('The websocket just closed, readyState: ' + ws.readyState);
}

Demo: http://jsfiddle.net/6kh20bdy/
ReadyState 3 means closed: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Constants


text:
Q: Как организовать проверку двух японских свечей Пожалуйста помогите разобраться в PineScript.
Суть задачи такова:
Имеются фракталы на графике как с помощью PineScript сделать проверку на то что если две свечи "подряд" идущие имеют максимум и минимум как на фотографии то поставить на 3ую свечу табличку "HQS"(Для понимание приложил скриншот)
Как рисуются фракталы понятно а вот как сделать данную проверку не совсем понятно.Заранее спасибо


text:
Q: Spinner не устанавливать значение пока не нажму(android) У меня есть spinner:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int childposition, long id) {
        textView.setText(spinner.getSelectedItem().toString());
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        textView.setText("");
    }
    });

У меня есть textView При запуске программы, по стандарту туда устанавливается первое значение списка, т.е:
list.add("one");
list.add("two");

Когда я запущу свой пример то у меня в textView будет one.
Вопрос: как сделать так что б при запуске программы у меня был textView.setText("")  и только тогда когда я нажму на спиннер и выберу item то устанавливалось textView.setText(spinner.getSelectedItem().toString()); ?

A: Есть более изящней способ вместо того что бы тянуть в проект левые исходники :-)
Все что нужно это назначить OnItemSelectedListener в методе post()
Выглядит это так:
        spinner.setAdapter(adapter);
        spinner.post(new Runnable() {
            @Override
            public void run() {
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        textView.setText(spinner.getSelectedItem().toString());
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        textView.setText("");
                    }
                });
            }
        });

A: То что вы описали - нормальное поведение дефолтного Spinner. Это многим не нравится, поэтому появилось альтернативное решение https://github.com/justjohn/transitwidget/blob/master/src/com/transitwidget/NoDefaultSpinner.java. Добавьте этот класс в свой проект и используйте вместо стандартного Spinner - NoDefaultSpinner. У вас не будет выбираться первое значение по умолчанию, а в самом Spinner будет устанавливаться текст из атрибута prompt.


text:
Q: arrays, constructors and instances I explain my problem: I'm trying to solve an arrays proble, I got a programme done in OOP in which it has a class called lights. What I want is to do an array with pin numbers inside and set them up as output. I did pin by pin and it was easy to do but now I would like to do it with a for loop and an array
I don't know how to build a constructors and handle of this with an array whit pin numbers in it.
    //----------------------------------------------------------------------------------
class lights{

  int pins[5]; //array for 5 elements
  int i;

  public:
  lights(int ledPins[]){

    for(i=0; i<5; i++){     //pins are set up as output
      pinMode(pins[i],OUTPUT);
    }

  }//end constructor

  void attempt(){                        //metodo para pobrar si se enciende los leds

    for(i=0; i<5; i++){
      digitalWrite(pins[i],HIGH);
      Serial.println(pins[i]);
    }
  }//end attempt
};//end class
//---------------------------------------------------------------------------------------------------------------------

int MyPins[] = {5,6,7,8,9};        //I declare what it is inside

lights lit(MyPins);                 //I create an objet with my array as parameters

void setup(){
  Serial.begin(9600);
}

void loop(){

  lit.attempt();

}

A: You don't need to put everything into a class.  I think using a class for the lights is overkill.
In my experience, a functions are used to process the light pins and they all would take a pin enum.
Unless you have a huge amount of pins to set up, a loop may not be worthwhile.  Unrolling the loop may increase the programs efficiency:
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);

Initialization usually only occurs once, so optimization is usually not warranted.
If need to use classes, I suggest one class that models a single light.
Every light has an associated pin.
You can have a container of lights (such as array):
class Light
{
  public:
    Light(unsigned int pin)
      : m_pin(pin),
        m_is_on(false)
    { ; }

    void initialize(); // Sets up the appropriate pin
    void on(); // Turns on the light
    void off(); // Turns off the light
    void blink(unsigned int rate, unsigned int duration);

  private:
     unsigned int m_pin;
     bool         m_is_on;
};

Light display[] = {Light(5), Light(6), Light(7), Light(8), Light(9)};
const unsigned int light_quantity =
    sizeof(display) / sizeof(display[0]);

An advantage to this model is that your program can be in terms of lights and not worry about pins.

A: Your code is not working because you are just writing code but didnt make an algorithm to design the application first...
Take a minute to see what you wrote as a software...
you are passing to the constructor an array, but where are you using that information??  nowhere...
 lights(int ledPins[]){

    for(i=0; i<5; i++){     //pins are set up as output
      pinMode(pins[i],OUTPUT);
    }

  }//end constructor

and you are setting as output in the arduino the pins {0 to 4} and not {5 to 9} as you think, after that the loop method is just setting to HIGH level pins that probably dont even have LEds :)
(you should there by the way use a sleep and play turning the leds on an off so you can see how they blink )

A: I resolved the problem: just two lines were missing. I correct the real constructor
public:
  lights(int ledPins[]){
    for(i=0; i<5; i++){
      pines[i] = ledPines[i];
    for(i=0; i<5; i++){     //pins are set up as output
      pinMode(pins[i],OUTPUT);
    }

  }//end constructor


text:
Q: SwiftUI MapKit [Memory] Resetting zone allocator with 24 allocations still alive I'm developing an Ipad app that contains a MapKit Map using SwiftUI and I get the following error message in the XCode console everytime when the view with the map disappears:
[Memory] Resetting zone allocator with 24 allocations still alive.
Thankful for any help on how to solve it. :)
Related threads
First, before posting some code, let me say that there are a few threads related to this error. I've looked at this SO thread, Resetting zone allocator with allocations still alive, but it relates to UIKit and not to SwiftUI and either way I get the error message without adding annotations or zooming.
Another related thread here on SO is SwiftUI - EnvironmentObject - Strange Memory Usage but there the OP uses MKMapView instead of SwifUI's Map. Preferably, I'd like to use Map, but if nothing else MKMapView might be a way forward.
There is also some threads on the Apple developer forum, such as this one, but I've found no complete matches (in the linked thread, the OP only gets the error once, while it reoccurs for me every time the view with the map disappears).
Minimal reproducible example
The error occurs each time the view button that removes the Map is pressed.
View creating the error
import MapKit
import SwiftUI

struct ContentView: View {
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 10))
    @State private var showMap = true

    var body: some View {
        if showMap {
            VStack {
                Map(coordinateRegion: $region)

                Button("Hide map") {
                    showMap = false
                }
                .font(.title)
            }
        } else {
            Button("Show map") {
                showMap = true
            }
            .font(.title)
        }
    }
}

Set-up view
import SwiftUI

@main
struct SwiftUIByExampleApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}


text:
Q: how to implement GridGain GridSegmentationResolver I am trying to add GridSegmentationResolver to the GridConfig. But it seems it is not being invoked. Look around in the source code and I found that the open source GridSegmentationProcessor is a mock implementation which always return true.
So the question is how to add our own Segmentation handling in the open source version of GridGain? Or it requires enterprise version?

A: Network segmentation handling is part of GridGain enterprise edition only. It is not possible to add segmentation handling in open source edition.


text:
Q: Zebra ZD410 print from https I'm trying to get my Zebra ZD410 to print labels from a website. That website is not mine. It runs on https. My printer does work, is connected to my computer, I can send ZPL instructions. The printer is actually connected to my Wi-Fi and has a static IP address of "192.168.2.80".
When browsing to "http://192.168.2.80" the print server page shows up.
The website in question supports, for now, only the Zebra 410 (and most probably other version, just not tested). Their instructions are to click on a link to accept the SSL certificate. Upon clicking on that link, a new page is opened and tries to load https://192.168.2.80, which is refused with "ERR_CONNECTION_REFUSED"
I have tried and successfully sent "!U1 setvar "ip.https.enable" "on" and restarted the printer, it doesn't change anything.

A: *

*By default, the printer comes with http enabled

*Always add a carriage return at the end of your commands in the communication tool

*One can enable https by sending ! U1 setvar "ip.https.enable" "on"

*The printer comes with no self-signed default certificate for SSL, that's a shame

*Anybody can generate self-signed certificates, by opening a terminal and make sure you have openssl installed then type :

*

*openssl genrsa 2048 > HTTPS_KEY.NRD

*openssl req -new -x509 -nodes -sha256 -days 365 -key HTTPS_KEY.NRD > HTTPS_CERT.NRD

*

*The certificate file must be named HTTPS_CERT.NRD

*The private key file must be named HTTPS_KEY.NRD

*Get both files EXACT byte sizes

*Files must be manually uploaded in binary mode on the printer on E: (any other method will fail on ZD410, be it driver upload, serial upload, ftp upload, or setup utility upload, because the default destination is not E: but R: and is not RW)

*

*Open Zebra setup utility

*Open communication tools

*Enter following commands

~DYE:HTTPS_CERT.nrd,B,NRD,REPLACE WITH FILE BYTE SIZE,,-----BEGIN CERTIFICATE-----
REPLACE WITH YOUR CERTIFICATE CONTENT
-----END CERTIFICATE-----
~DYE:HTTPS_KEY.nrd,B,NRD,REPLACE WITH FILE BYTE SIZE,,-----BEGIN PRIVATE KEY-----
REPLACE WITH YOUR KEY CNTENT
-----END PRIVATE KEY-----
^XA
^JUS
^XZ
! U1 setvar "ip.https.enable" "on"
! U1 do "device.reset" ""

Upon restart, one can check if the https webserver was enabled with a command:

*

*! U1 getvar "file.cert"

*

*The printer will answer with all the loaded certificates.

*Check the line with HTTPS service. It should have a file and a validity

You can then navigate, on your browser to your printer's ip using https and also send https API triggers.
If you wish to then turn off http, you can disable it by sending this command:
! U1 setvar "ip.http.enable" "off"


text:
Q: HTML Email TD's stacking I'm trying to create an HTML Email with a table, and from what I've been reading, my TD, TR, and TABLEs need to be display:block in order to work, be responsive etc. However, when I put the cells in the document they stack instead of appearing linearly.
Sorry, it's so long. I've been playing with different solutions to try to get this "responsive" thing to work for this email, but i'm a bit stumped.

  /* Basics */
body {
    Margin: 0 !important;
    padding: 0;
    background-color: #ffffff;
}
table {
    border-spacing: 0;
}
td {
    padding: 0;
}
img {
    border: 0;
}
div[style*="margin: 16px 0"] {
    Margin:0 !important;
}
.wrapper {
    width: 100%;
    table-layout: fixed;
    -webkit-text-size-adjust: 100%;
    -ms-text-size-adjust: 100%;
}
.webkit {
    max-width: 600px;
    Margin: 0 auto;
}

table[class="magic"],
table[class="magic"] tbody,
table[class="magic"] tr,
table[class="magic"] td {
    display: block !important;
    width: 100%;
}

/* Y! and Outlook bg image fix */
tr[class=GradeHead] {
width: 100% !important;
height: 198px;
background-image:url('https://gallery.mailchimp.com/88f8ea77021bbc9d2f53d5229/images/5827ac1b-050b-4752-9f9f-728e05e3170b.png');
background-repeat: no-repeat !important;
background-position: 0px 6px !important;
background-size:cover;
}

tr .g-row{
width: 100% !important;
height: auto;
background-repeat: no-repeat !important;
background-size:cover;
background-position: -2px center !important;
display:table-row;
}

tr .g-row-2{
background-image:url('https://gallery.mailchimp.com/88f8ea77021bbc9d2f53d5229/images/535bc2e7-194c-4484-b47e-d8ecd81659a1.png');
}

tr .g-row-3{
background-image:url('https://gallery.mailchimp.com/88f8ea77021bbc9d2f53d5229/images/573b935e-64d4-43d4-b29c-aa3cc0661dbf.png');
}

tr .g-row-4{
background-image:url('https://gallery.mailchimp.com/88f8ea77021bbc9d2f53d5229/images/535bc2e7-194c-4484-b47e-d8ecd81659a1.png');
}

td[class=option] {
width: 300px !important;
height: auto !important;
display: table-cell;
}

td[class=cover] {
background-repeat: no-repeat !important;
background-position: center !important;
width: 100% !important;
height: auto;
}

td .boys {
background-image: url('img/row-1-bubbles.png') !important;
}

td .ship {
background-image: url('img/row-2-ship.png') !important;
}

td .resort {
background-image: url('img/row-3-resort.png') !important;
}
/* iphone X Media call */
  @media only screen
    and (device-width : 375px)
    and (device-height : 812px)
    and (-webkit-device-pixel-ratio : 3)
    and (device-pixel-ratio : 3) { }

/* iphone 7,8 Media call */
 @media only screen
    and (device-width : 375px)
    and (device-height : 667px)
    and (-webkit-device-pixel-ratio : 2)
    and (device-pixel-ratio : 2) { }

/* iphone 6 Plus, 6S Plus, 7 Plus, 8 Plus Media call */
 @media only screen
    and (device-width : 414px)
    and (device-height : 736px)
    and (-webkit-device-pixel-ratio : 3)
 and (device-pixel-ratio : 3) { }

  body{
   background-color:#fff;
  }
  *{
   font-family:Futura,Helvetica,Arial,sans-serif;
  }
  p{
   color:#929292;
   font-size:18px;
  }
  .plus{
   font-size:2em;
   padding:20px 10px;
   border-radius:30px;
  }
  a{
   text-decoration:none;
   color:inherit;
  }
  #footer a{
   text-decoration:underline;
  }
  #footer p{
   color:#c5b9ac;
   font-size:12px;
  }
  .btn-pink{
   color:#fff;
   background-color:#fa0375;
   display:block;
   padding:15px 5px;
   border-radius:30px;
   font-size:22px;
   text-align:center;
  }
  .btn-white{
   color:#fff;
   border:2px solid #fff;
   font-size:18px;
   display:block;
   margin:10px 25px;
   padding:10px 15px;
   text-align:center;
   text-transform:uppercase;
   border-radius:30px;
  }
  .btn-purp{
   color:#fff;
   background-color:#69034c;
   display:block;
   padding:15px 5px;
   border-radius:30px;
   font-size:20px;
   text-align:center;
   margin:25px 70px;
  }
  h3{
   color:#fff;
   font-size:21px;
   font-weight:normal;
  }
  table,tr,td{
   border:none;
   border-collapse:collapse;
   padding:0;
   border-color:rgba(0,0,0,0);
   border-style:none;
   overflow:hidden;
  }
  td h3,td p{
   margin:10px;
  }

You're always up to speed

HEADLINE

COPY

   Explore

HEADLINE

COPY

   Explore

HEADLINE

COPY

   Explore

Connect with us: @myvacaya

 Qs? WE'VE GOT As
 LET'S DO THIS


text:
Q: Why should I use normalised units in numerical integration? I was simulating the solar system (Sun, Earth and Moon). When I first started working on the project, I used the base units: meters for distance, seconds for time, and metres per second for velocity. Because I was dealing with the solar system, the numbers were pretty big, for example the distance between the Earth and Sun is 150·10⁹ m.
When I numerically integrated the system with scipy.solve_ivp, the results were completely wrong. Here is an example of Earth and Moon trajectories.
But then I got a suggestion from a friend that I should use standardised units: astronomical unit (AU) for distance and years for time. And the simulation started working flawlessly!
My question is: Why is this a generally valid advice for problems such as mine? (Mind that this is not about my specific problem which was already solved, but rather why the solution worked.)

A: Most, if not all integration modules work best out of the box if:

*

*your dynamical variables have the same order of magnitude;

*that order of magnitude is 1;

*the smallest time scale of your dynamics also has the order of magnitude 1.

This typically fails for astronomical simulations where the orders of magnitude vary and values as well as time scales are often large in typical units.
The reason for the above behaviour of integrators is that they use step-size adaption, i.e., the integration step is adjusted to keep the estimated error at a defined level.
The step-size adaption in turn is governed by a lot of parameters like absolute tolerance, relative tolerance, minimum time step, etc.
You can usually tweak these parameters, but if you don't, there need to be some default values and these default values are chosen with the above setup in mind.
Digression
You might ask yourself: Can these parameters not be chosen more dynamically? As a developer and maintainer of an integration module, I would roughly expect that introducing such automatisms has the following consequences:

*

*About twenty in a thousand users will not run into problems like yours.

*About fifty a thousand users (including the above) miss an opportunity to learn rudimentary knowledge about how integrators work and reading documentations.

*About one in thousand users will run into a horrible problem with the automatisms that is much more difficult to solve than the above.

*I need to introduce new parameters governing the automatisms that are even harder to grasp for the average user.

*I spend a lot of time in devising and implementing the automatisms.


text:
Q: Making Timeline in qliksense I would like to display a timeline in qlik sense using the  Bar Chart Object enter image description hereas follows:
The x-axis represented the months of the year.
The Y-axis represented the years.
The length of the graph will be a date range in the appropriate year and month.
It will look like this:
exaple
How can I do this?
Thanks!

A: I suggest you use a Pivot Table chart object with a background colour expression set to yellow.
In this example, I calculated the day number of the start date and the duration of the period to be shown in yellow.
The Bar Chart shows the sum of 'DayNumberStartDate' and 'Duration'
Bar Chart


text:
Q: How to find total combinations of following numbers? I have the following Arrays:
[1,2,3]
[I,II]
[A,B,C]

I want to know how many combinations are possible. In example:
[1,I], [1,A], [2,I], [2,A], [3,I], [3,A], ...

There is something called the Cartesian product in Mathematics but I don't know how to implement it.

A: You can calculate the number of possible combinations of elements in your arrays using multiplicatation.
If you have 2 arrays array1 and array2 the number of possible combinations would be array1.length * array2.length.
var array1 = ['1','2', '3'];
var array2 = ['I', 'II'];

var posibleCombinations = (array1.length * array2.length);

The result of the above example is 6.
With three arrays you would calculate the possible combinations between each array and then add the sum of each.
var array1 = ['1','2', '3'];
var array2 = ['I', 'II'];
var array3 = ['A','B','C'];

var posibleCombinations = (array1.length * array2.length) + (array1.length * array3.length) + (array2.length * array3.length);

The result of the above example is 21.

A: var array1 = [1,2,3],
    array2 = ['I','II'],
    array3 = ['A','B','C'];

var count = array1.length + array2.length + array3.length;
    count = count * (count -1);
console.log(count); // 56

The formula is:
n = total * (total -1) // -1 assuming that the first can't be equal to the second


text:
Q: How to use THIS in express? In my express app, I'm trying to create a helper function that sends a response so that I don't have to keep typing it.  However, I'm having problems getting this to work.  I keep getting this as undefined.

function sendMessage(code, message)
{
  return this.res.status(code).json({message});
}

app.('/foo', (req, res) => {
  return sendMessage(200, 'bar');
});

app.('/buzz', (req, res) => {
  return sendMessage(200, 'bang');
});

A: this won't solve your problem.
res is not a property of any object, it is a variable.
You need to pass it to your function:
function sendMessage(res, code, message)
{
  return res.status(code).json({message});
}

app.('/foo', (req, res) => {
  return sendMessage(res, 200, 'bar');
});

A: try this
function sendMessage(res, {status,data})
{
  return res.status(status).json(data)
}

app.('/foo', (req, res) => {
  return sendMessage(res,{ status : 200, data :  'bar'});
});

A: Express doesn't use dynamic this, in order to access needed middleware parameters they should be passed to a function, as other answers show.
If the intention is to provide a middleware with custom response, higher-order function can be used with optional code argument:
const createSendMessageMiddleware = (message, code = 200) => (req, res) => {
  res.status(code).json({message});
}

app.get('/foo', createSendMessageMiddleware('bar'));

app.get('/buzz', createSendMessageMiddleware('bang'));

A:  function sendMessage(code, message,res) {
      return res.send({code:code,message:message});
    }

    app.('/foo', (req, res) => {

    return sendMessage(200, 'bar',res);
    });

    app.('/buzz', (req, res) => {

    return sendMessage(200, 'bang',res);
    });


text:
Q: dymanically increasing number of textboxs in webforms I have a database with 2 records Id and Description.
What I want to do is try to bind this to a table  so for example
<tr>
   <drop down select list with ids available> <textbox>
</tr> <add button>

So the user can select an id from the drop down list, enter a description then click an add button next to this  which will duplicate that  block dynamically so they can enter as many as they like. What is the best way to go about this in webforms? Detailsview? I'm not sure how to make it dynamically add html blocks though? Any help would be appreciated.

A: pseudocode :
foreach description
    create new tablerow
    create a table cell in the row with the description as a label
    create a table cell in the row with the id dropdown as a combobox
    add the tablerow to the table.rows collection

the tricky part is accessing the data in your dynamically created table, but it shouldn't be hard to do as long as you set an identifier on each control that can be tied back to your data.

A: I'd stay away from any of the built in controls (i.e. DetailsView, FormView) for anything other than simple CRUD forms, as it's not much more effort to manually create your own data-entry forms.
Dynamically adding controls to an ASP.NET Webform (and have them work across postbacks) is quite a tricky one to get right, but in short you'll need to do something like:

*

*Add a table server control which will store your dynamic rows.

*Create a property (stored in ViewState or ControlState) to store a count of rows available.

*Handle the appropriate 'add' button click event, to increment the count property and add a new table row, and child controls.

*Inside an OnInit event, create the number of table rows stored in the count property.

Dynamically created controls aren't persisted across postbacks, so you'll need to create them on every postback during the pages OnInit method. As long as the controls are recreated in the right order and with the same ID's, then they will be repopulated successfully on postback.
Because you're dynamically adding controls, you may need to set the pages EnableEventValidation property to false.


text:
Q: Which great mathematicians had great political commitments? Some mathematicians claim that their field has nothing to do with political concerns; others are deeply involved in political life.
Are there many great mathematicians with great political commitments?
I am particularly interested in the possible interplay between their research work and their political involvement.
For instance, did their political views influence their research topics or collaborations? Did some issues met in their mathematical life (like funding opportunities, e.g.) have an impact on their political commitment? ... This would mean more than just doing maths and politics independently.

A: Some great French mathematicians were involved during the French Revolution:

*

*Joseph Fourier was part of a local Revolutionary Committee.

*Gaspard Monge was Minister during the 1st Republic.

*Politics was a central part of Condorcet's work as a philosopher. He used mathematics to study voting systems. He was very active during the French Revolution and participated in the Constitution Committee.

Others participated in Napoleon's empire:

*

*As said in another answer, Fourier and Monge participated in the campaign in Egypt. They also held political positions: Fourier was prefect of the department of Isere, while Monge was part of the Conservative Senate.

*Augustin-Louis Cauchy was known to be a staunch royalist. This had a huge impact on his career (and the careers of other mathematicians). More generally, the history of the Academy of Sciences is full of political meddling.

The Eiffel Tower is engraved with the names of 72 scientists, engineers and mathematicians. Most of them have been involved in the political turmoils of the 18th and 19th centuries.

A: Daniel Biss received his PhD in mathematics at MIT in 2002, then was an Assistant Professor at the University of Chicago until 2008. He won the 1999 Morgan Prize for outstanding research as an undergraduate. However, in 2007, a serious flaw was discovered that destroyed the main results of papers he had published in the Annals of Mathematics and in Advances. He is now a State Senator in Illinois. I have no idea how much his mathematical background influences his decisions, but in this position, he has worked on legislation touching on mathematical topics, such as legislation to "allow for automatic voter registration," to "elect a number of statewide offices by ranked-choice ballot," and on healthcare, among other things.

A: How about a very recent political appointment? Eric Lander co-chaired Obama's "Council of Advisors on Science and Technology", and was very recently appointed to President Biden's director of the Office of Science and Technology Policy, as well as adviser on science; this is now a cabinet post, so ought to count as a political commitment.
Lander did his DPhil at Oxford, supervised by Peter Cameron, on algebraic coding theory. He is also a major figure in bioinformatics -- he is the first named author on the Nature paper which announced the completion of the Human Genome Project, a paper cited nearly 15000 times.

A: Tadatoshi Akiba, a former student of John Milnor, served as the mayor of Hiroshima from 1999 to 2001. He obtained his PhD from MIT in 1970 and has written papers in algebraic topology.

A: It seems to me that Alexander Grothendieck, 1966 Fields Medalist and founder of the Survivre group in 1970, is one of the best examples; he had and still has both a tremendous contribution to mathematics and an important political influence. He is considered by some as the greatest mathematician of the 20th century (see Wikipedia page, that cites this obituary), and by others as a precursor of ecology in politics.
Grothendieck gave conferences and participated debates regarding the role of research, notably at CERN in 1972 (in French). I heard he considered the idea of working in life sciences for political reasons, but estimated this was a dead-end. He finally discontinued his participation to the global research effort (although he may have continued his own work outside the system). I do not know if his political views had any further influence on his research topics or results themselves, though.
More material is available from the Grothendieck Circle.

A: Sir Isaac Newton is perhaps an example.
Aside from his work as Warden and Master of the Royal Mint, he also served as a Member of Parliament for Cambridge University and was involved in opposing Royal encroachment on the religious rights of the university; this was linked to Catholic - Anglican conflict in England at the time and Newton supported the Protestant William III and Mary II in his invasion of England and ouster of his uncle James II, a Catholic.
A good and detailed article by Robert Iliffe is published as part of the Newton Project, at oxford University; Newton: The Making of a Politician

A: I would like to say a few words about Marianne Ruth Freundlich Smith, who was one of the pioneers of the theory of stereotype spaces (Smith spaces are named after her). During WWII her family left Germany as they were Jewish, they moved to USA, and Marianne found a job in UC Berkeley. From what her children told me about her, it follows that she was interested in politics as an anti-war activist, and, in particular, because of that she had to quit working at Berkeley when they started imposing the Loyalty Oath. It is not clear how deeply this event influenced her life, but after that she left science and became a teacher at a colledge. Here is a quote from her son's letter to me:

I recall my mother and I attended a march in protest to the Viet Nam war in 1965, maybe 20,000 people, where she wore a nice black dress, a short fur coat and high heel shoes.  This was in contrast to the appearance of most of the marchers.  She said it was important to show that people who could dress well were part of the protestors.  I remember she remarked to me that day that her last public demonstration had been to encourage the US Government to take action against Franco and the Russians' attempts to overthrow the republican government in Spain and that she was now protesting the US government taking action to interfere in Viet Nam's internal struggles.

For my generation, people like Marianne are role models in current events in my country.

A: Chandler Davis.  He was Professor of Mathematics at University of Michigan.  He was a member of the Communist Party USA.  He refused to cooperate with the House Unamerican Activities Committee.  He was fired from the University of Michigan and sentenced to 6 months in jail.
A paper from this era has the following acknowledgement:

Research supported in part by the Federal Prison System. Opinions expressed in this paper are the author's and are not necessarily those of the Bureau of Prisons.

source

A: Joseph Fourier accompanied Napoleon Bonaparte on his Egyptian expedition in 1798, as scientific adviser, and was appointed secretary of the Institut d'Égypte.
source

A: I think Bertrand Russell should be mentioned here.
No doubt he was a great mathematician, but he was also very involved in politics (https://en.wikipedia.org/wiki/Bertrand_Russell#Political_causes).

A: Evariste Galois divided his time between his mathematical work and his political affiliations as a member of a Republican artillery unit. He was arrested twice for protesting against the king.

A: Laurent Schwartz was a passionate communist, later a social democrat, suspended from teaching for two years for signing the Manifesto of the 121 (French leftwing petition against the Algerian war).

A: The number theorist DH Lehmer (along with 30 other faculty) was fired from a tenured position at UC Berkeley for refusing to sign the loyalty oath during the McCarthy era.  When the State Supreme Court ruled the oath unconstitutional, he got his job back.

A: The OP might be interested in the paper

Dauben, Joseph W (1998), "Marx, Mao and mathematics: the politics of infinitesimals", Proceedings of the International Congress of Mathematicians, Vol. III (Berlin, 1998), Documenta Mathematica, III, pp. 799–809, ISSN 1431-0635, MR 1648209, archived from the original on 2019-01-30, retrieved 2011-09-25

You can also read the Mathematical manuscripts of Karl Marx, which, according to Wikipedia, justify "Engels' claim that Marx made 'independent discoveries' [in mathematics]." Certainly Marx had "great political commitments" and his writings in economics were clearly influenced by his study of mathematics, as discussed in the sources above.

A: Dov Tamari, born Bernhard Teitler, was a German Jewish mathematician who emigrated to British Mandate Palestine in 1933 at the age of 22 and became involved in Irgun, an underground paramilitary organization.  On July 14, 1939 Teitler was sentenced to imprisonment by the Jerusalem Military Court, after explosives were found in the room where he was staying.  In their biographical article from the Tamari Memorial Festschrift, Folkert Müller-Hoissen and Hans-Otto Walther quote the following excerpt from the Palestine Post (July 16, 1939) about the trial:

Professor A. Fraenkel, Rector of Hebrew University, gave evidence as to the good character of the accused, whom he described as an excellent student of mathematics. For the Defence, Mr. E.D. Goitein argued that the Prosecution had failed to prove its case against the accused, who was 'a scatterbrain, like all mathematicians,' and therefore might have done something foolish.

Apparently this argument did not succeed and Teitler was still sentenced to seven years in prison, although he was released early in summer 1942.  Later that year he officially changed his name to Tamari.
The very interesting article by Müller-Hoissen and Walther discusses many other aspects of Tamari's life and mathematics, including how his political views evolved after his early involvement in Irgun.

A: In the early/mid twentieth century, there were a number of "great mathematicians" working on theoretical physics directly and indirectly related to atomic weapons research. I think this area will have a number of examples with "great political commitments."
I want to briefly mention The ManhattanProject, but first I want to point out the (sort of) null hypothesis: the people involved in that work had "great political commitments," that what they were working on was for the national interest.
For this question, I wanted to add a mention for Oppenheimer. It is true he was an accomplished physicist, and even made important contributions to the field, but in a period of many important discoveries I'm not sure he would ever rise to qualifying as a truly "great mathematician." One area he did excel in was task management and coordinating people, which is how he landed as the head of Los Alamos Laboratory.
This is just a bit of background to mention Oppenheimer's "great political commitments." After the war,

Oppenheimer recommended putting control over atomic energy into the hands of an international agency. Appointed a key advisor to the newly created Atomic Energy Commission, a position that offered him an important voice in Washington and a top-secret security clearance, he spoke out for moderation as tensions between the Soviet Union and the United States began to escalate. He advised against the development of the hydrogen bomb, a device with unlimited destructive power, and took a stand against building nuclear powered aircraft and submarines. [emphasis mine]

(Without going into details, he was stripped of his authority and removed from this position)

"The Oppenheimer hearings had a tremendous impact on the nuclear arms race," says Mark Samels, executive producer of AMERICAN EXPERIENCE. "Once Robert Oppenheimer's voice of moderation was silenced, the U.S. began building an arsenal of tens of thousands of nuclear weapons, and the Soviet Union followed suit. The result was a standoff between the world's two largest superpowers that lasted for nearly fifty years."

(quoted from "The Trials of J. Robert Oppenheimer", released on PBS. reference: https://www.pbs.org/wgbh/americanexperience/films/oppenheimer/#part01 )

The above quote seems to imply that Oppenheimer was the sole thing standing between the USA and nuclear weapons development, which seems a bit exaggerated. Surely there were other forces and institutional inertia at play. But I like to think there is an alternative universe where his non-proliferation stance prevailed.

A: Ludwig Bieberbach was a devoted member of the Nazi party and adherent of its ideology.  Fittingly for this question he helped found (along with fellow German Mathematician Theodore Vahlen) the journal "Deutsche Mathematik".  This was an ideological project aimed at promoting various racial theories of "German mathematics".  Hardy wrote a letter to Nature summarizing his understanding of some of Bieberbach's racialized views of mathematics and mathematicians.

A: A group of mathematicians and lawyers filed an amicus brief for the Supreme Court of the United States, on the issue of gerrymandering. This work uses deep mathematics to answer questions inspired by politics. The related research group, at Tufts University, includes both mathematicians and people whose work could be characterized as "politics" (e.g., outreach to elected representatives to teach them about the group's work on gerrymandering). I suspect this is an area where you can find a lot of people crossing over between math and politics. I hope readers who know more will feel free to edit this answer.

A: Your question is about persons, while my response is about incidents, but:
The Antwerp school/conference on modular forms in 1972, sponsored by NATO, led to a number of statements in the various conference proceedings, about the funding source being incompatible with the "peaceful mission" of the mathematician, etc.
For instance,

This is a slightly edited version of a letter to Cassels.
Tate's absence from the conference was in protest against the large
scale support of basic scientific research by military organizations
rather than by agencies whose aims and spirit he thinks are more
compatible with those of scientific inquiry.

https://dx.doi.org/10.1007/BFb0097582
For that matter, various top-level European mathematicians in the last few decades have stated political reasons for not travelling to the United States (such as support for capital punishment, involvement in foreign wars, identity of leaders, etc). Undoubtedly this affects their research directions, though probably less so than it would a mid-range researcher, and moreover less so due to the Internet nowadays too.

A: Leibniz worked as a diplomat for the Elector of Mainz. He tried to persuade Louis XIV to desist from expanding into Germany and redirect his efforts towards conquering Egypt from the Turks. The plan did not go anywhere, at least not until Napoleon decided he wanted both Germany and Egypt.

A: Ted Kaczynski, aka "The Unabomber", was also deeply committed to a political cause. He was a staunch supporter of an anarcho-primitivist ideology and society. He was considered a mathematics prodigy and an expert in geometric function theory. In 1967, he became the youngest assistant professor of mathematics in the history of UC Berkeley at the age of 25.
From 1975 onwards, he dedicated his life to achieve his political goals by reading works on sociology and political philosophy (written by Jacques Ellul, among others), and by executing terrorist attacks on numerous people.
Whether the methods he employed to realise his political aims were justifiable is of course up to debate.

A: Sergio Fajardo is a mathematician who was also Mayor of Medellin after the death of Pablo Escobar, was Governor of Antioquia (the state that Medellin is in) from 2012–2016, ran for President of Colombia in 2018, and has announced plans to run again for President. In mathematics, he earned his PhD from UW-Madison and was a professor at the Universidad de los Andes and the Universidad Nacional of Colombia.
In politics, he completely revitalized the city of Medellin, building new parks and libraries, and rebranding the city. The Park of Lights is a great example. That park used to be (figuratively) the darkest place in the city. Escobar had complete control of it and any (non-corrupt) police officer who came nearby would be killed. The park contains two of the oldest buildings in the city, and they were full of squatters. Now, the park is full of life, with Colombian bamboo (Guada kindiana), tons of people, and these giant lightsaber-looking lights that run all night. It's never dark there. It's the safest place in the city. The buildings that used to house squatters now house the department of education. Fajardo also built beautiful libraries to serve the poorest neighborhoods of the city, to give children a chance at a life based around something other than drugs.  He was named "best Mayor of Medellin" in 2007. Regarding his time as governor, according to Wikipedia

During his administration, Antioquia experienced the best national performance in open government, transparency and investment of oil royalties (according to the National Planning Department and the Anti corruption Office of Colombia). He was named the best governor of the country in 2015 by the organization Colombia Líder.

There are interviews with him in the book Magdalena by Wade Davis. I think his mathematical way of thinking did influence how he governed.

A: Jean van Heijenoort (1912-1986) was a historian of mathematical logic and personal secretary to Leon Trotsky.

A: *

*Alex Lubotzky was a parliament member in the late 1990s in Israel.

*Menachem Magidor was, while being the president of the Hebrew university (a political position in itself), the head of the "presidential committee for examining an alternative governmental structure" (informally known as the Magidor committee) which considered the possibility of changing the Israeli executive branch to a presidential system. While not exactly a political career per se, I feel that it's only a stone's throw away from having a lot of political influence. The committee made several suggestions to switch to semi-local representation, rather than a presidential system, but none of the recommendations were implemented as of 2021.

A: Cédric Villani is a 2010 Field Medalist. In 2017 he was elected as a deputy in the French National Assembly, in LREM, Emmanuel Macron's party (which he left since then). In 2020 he ran for Mayor of Paris.
As far as I know, there is no link between the precise subject of his research and his political involvement.
However he has done some (a lot of?) interventions as a scientific expert for different commissions. In 2017 he has been President of the French Parliamentary Office for the Evaluation of Scientific and Technological Choices.

A: Faustin Touadera, the current president of the Central African Republic, is a mathematician. (I am sure that he is great in your sense).
https://en.wikipedia.org/wiki/Faustin-Archange_Touad%C3%A9ra
papers found in ZBL
Touadera, Faustin, Condition suffisante de résolubilité du problème de Cauchy matriciel $C^\infty$ non caractéristique à caractéristiques de multiplicité variable., Ann. Sci. Math. Qué. 20, No. 1, 67-91 (1996). ZBL0876.35071.
Dossa, Marcel; Touadera, Faustin, Solutions globales de systèmes hyperboliques non linéaires sur un cône caractéristique., C. R., Math., Acad. Sci. Paris 341, No. 7, 409-414 (2005). ZBL1077.35098.

A: I would like to add von Neumann. He was involved in the Manhatten Project and a part of the Atomic Energy Commission. In addition, he was heavily involved in politics as a consultant for various departments within the US government.

A: The polymath Francis Galton is considered as a pioneer of eugenics, a topic he studied using statistical tools. The so-called Galton-Watson process was introduced to study the extinction of aristocratics surnames.

A: *

*Stanisław Mazur was involved in the the Communist Party of Poland and Polish United Workers' Party. He was a member of the Polish parliament in 1946-1954.

*The work of Stanisław Ulam (n.b. a collaborator of Mazur) had some significant political implications. (I've just noted that this is also mentioned in another answer.)


text:
Q: php - how to find the month names and numbers between two dates? I need to find the month names and numbers between two dates

For the above two variables, how to find out the month numbers, ie) output will goes like this

aug2016,sep2016,oct2016,nov2016,dec2016,jan2017

A: <?php

$date1  = '2013-11-15';
$date2  = '2014-02-15';
$output = [];
$time   = strtotime($date1);
$last   = date('M-Y', strtotime($date2));

do {
$month = date('M-Y', $time);
$total = date('t', $time);

$output[] = $month;

$time = strtotime('+1 month', $time);
} while ($month != $last);

echo implode(",", $output);
?>

output
Nov-2013,Dec-2013,Jan-2014,Feb-2014

A: Try this one
<?php
 $var1 = "2016-08-15";
 $var2 = "2017-01-31";
 $result = '';
 while (date('m', strtotime($var1)) != date('m', strtotime($var2))) {
    $result .= date('MY',(strtotime('next month',strtotime($var1)))).",";
    $var1 = date('Y-m-d',(strtotime('next month',strtotime($var1))));
 }
 echo trim($result, ",");
?>

Output : Sep2016,Oct2016,Nov2016,Dec2016,Jan2017

A: Correct me if I'm wrong but, based on the output you provided, it seems what you really want to do is extract a month name from month number.
See this: http://www.php.net/manual/en/function.jdmonthname.php
$monthName = jdmonthname($month, 0);

I think you should be able to take it from there.


text:
Q: set the pageContent in node-slimerJS or for slimerJS globally I'm trying to set the network capture content  using node-slimerjs  bridge for node js. What I would do using plain slimerJS is the following:
page.captureContent = [/html/, /text/];

but I have to use the getter setter functions in the node-slimerjs library so using the these functions I'm using the following code:
page.set('captureContent',[/text/,/html/]);

but the setter function isn't setting the value correctly and I'm left with the empty body for the network responses with text/* and html/* types.
After setting the captureContent if I try to read the value with console.log I can see that only an empty object has been set to the capture content:
page.get('captureContent', function(err,val){
        console.log('captureContent::: ',val)
        });

from node console:

captureContent::: [ {}, {} ]

I also tried creating new regex objects and setting them using the setter function but got the same result.
var re = new RegExp("html");
var re2 = new RegExp("text");

In the SlimerJS documentation it is stated that by default this is limited to avoid memory problems. So it may be possible to unlimit this so...
How can I set the pageContent in slimerJS either globally or from node-slimerJS library so I can see the network body for responses with certain content types?


text:
Q: Pexpect equivalent for java? Is there a pexpect equivalent for java? I know that I could replicate the functionality by using commons exec or processbuilder and redirecting stdin/stdout and then parsing the streams etc etc But, my question is, is there a plug-and-play equivalent for that?
What I would like would be to run interactive command line programs like I do in python. A small example is:
def start_binary(input):
   shell_cmd = 'grep '+input+' file4.dat >> file3.dat'
   grep = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
   grep.expect(pexpect.EOF)
   shell_cmd = './myProg -c'
   myProg = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
   myProg.expect('Next DATA file')
   file_list = ['file1.dat', 'file2.dat', 'file3.dat']
   for this_file in file_list:
      myProg.sendline(this_file)
   myProg.sendline()
   return myProg

And then I use myProg in an interactive way (sending commands, getting/parsing results, etc). I can get the results between two calls through myProg.before, etc.
Is there a package that offers the same functionality in the same easy way in java?

A: A simple Google search for "java expect" found expect4j as the first item in the list and ExpectJ as the second item listed.


text:
Q: proving vector is bounded above by convex combination of vectors I am trying to prove the following statement.
given vectors $\textbf{a},\textbf{a}_1, \cdots, \textbf{a}_m \in \mathbb{R}^n$,
$\forall \textbf{x} \geq 0 $, we have $\textbf{a}'x \leq \textrm{max}_i \{ {\textbf{a}'_i \textbf{x}}\}$  if and only if there exist nonnegative coefficients $\lambda_i$ that sum to 1 and such that $\textbf{a} \leq \sum_{i=1}^m\lambda_i\textbf{a}_i$
here $\textbf{v} \leq \textbf{w}$ for $\textbf{v}, \textbf{w}\in \mathbb{R}^n$ means we have $v_i \leq w_i$, $i = 1, \cdots, n$
for one way, it was pretty straightforward,
$\textbf{a}'\textbf{x} \leq \sum_{i=1}^m\lambda_i\textbf{a}_i'\textbf{x} \leq \sum_{i=1}^m\lambda_i\textrm{max}_j\{\textbf{a}_j'\textbf{x}\} \leq \textrm{max}_j\{\textbf{a}_j'\textbf{x}\}\sum_{i=1}^m\lambda_i \leq \textrm{max}_j\{\textbf{a}_j'\textbf{x}\}$
showing the other way is much of a struggle for me and I dont really know where to start. I have thought of trying maybe forming a polyhedron thats convex hull of $\textbf{a}_1, \cdots, \textbf{a}_m$ but it brought me nowhere. I have also attempted maybe forming a cone but it seems $\textbf{a}$ can be lying outside the cone. Any hint or guidance is appreciated.

A: To show (a)$\implies$(b), we can show $\neg$(b)$\implies$$\neg$(a).
To begin, assume that for every $\lambda\geq0$ with $\lambda^\top \mathbf{1}=1$ that $a \not\leq \sum_{i=1}^m\lambda_i a_i$.
Then there is a coordinate $k\in\{1,2,\ldots,n\}$ of $a$ such that $a^{k}>\sum_{i=1}^m\lambda_i a_i^k$.
Next consider a special $x:=e_k=(0,\ldots,1,\ldots,0)$, the $k$th standard basis vector.
Taking a special $\lambda^*$ to be the vector of zeros with a one in the $i^*$th slot where $i^* := \mathrm{arg}\max_i \{a_i^\top x\}$, we have
$$a^\top x = a^k > \sum_{i=1}^m\lambda_i^* a_i^k = \sum_{i=1}^m\lambda_i^* a_i^\top x = \max_i\{a_i^\top x\}$$
and are done.


text:
Q: Interfacing html, javascript, php and mysql Below is an order form that I have been working on to learn how html, javascript, php and mysql interact with each other.
https://www.dropbox.com/s/7zpok07w1bygu60/Screen%20Shot%202012-08-12%20at%2010.28.41%20AM.png
The goal of this table is to have the user input a number in the quantity field and on the change, javascript will automatically update the total cost of that particular product.  The kicker is that I want the list to be populated from a mysql database table.
Here is the html, javascript and php code that I am using.
HTML

        Product

        Description

        Quantity

        Price

        Total Cost

<?php include("pop_prodlist.php"); ?>

    Totals

    TotalQuantity

    TotalCost

PHP
    while($row = mysql_fetch_array($result))
{
    echo "
";
    echo "" . $row['P_Name'] . "	";
    echo "" . $row['P_Description'] . "	";
    echo "
    <input type='text' size='3' name='" . $row['P_Name'] . "_Quantity'
      onChange='calcCost()'/>
    	";
    echo "" . $row['P_Cost'] . "	";
    echo "0.00	";
    echo "
";

}

Javascript calcCost() function
    function calcCost()
    {

      var theForm = document.forms['productform'];

    /*
    COMMENTED OUT FOR TIME BEING
    var pquan = theForm.elements[productname + '_Quantity'].value;
    var costperquan = '15.99';
    var ptotalcost = costperquan * pquan;
    */

     var divobj = document.getElementById('Basketball_Cost');
     divobj.innerHTML = "helloworld";

    }

The issue that I am currently having is that I cannot figure out how to place an unique argument into the javascript function calcCost from the php script echo depending on the product name decided from the mysql query.
Also, for the sake of educating myself, I am curious as to what a better solution would be/look like.  I doubt that this is the most elegant solution to the problem and I would like to see some better solutions.

A: Jay, it seems like you understand how PHP, MySQL and JavaScript work together - that is good.
Personally, I can really reccommend using jQuery (JavaScript Library). It is widely used all over the web, very common, powerful and easy to understand and use. Although there are people that say it is not good to use a library of a language, before you know the language, jQuery helped me to understand JavaScript better because of its easy to follow syntax.
So, to use jQuery, you just need to add the source scripts in your html file. Why do I recommend jQuery? It will also allow you to use ajax (loading content, also from the database, without having the page to refresh) very easily.
jQuery will also allow you to separate your click events from your HTML. Basically you assign an id or class attribute to the HTML elements and this is your reference in your js, so no onclick="" required.
As for your HTML: it is highly recommended to not use table-layouts. In a time of HTML5 and CSS3 there are excellent replacements for tables.
If you need more help let me know in the comment, I'm glad to help...


text:
Q: Why in the discussion of the definition of \newif are the following things true This is a couple of questions that stem from the answer to Problems understanding definition of \newif by @egreg.
In that @egreg says

Let's look at
\expandafter\expandafter\expandafter
\def\@if\iffoo{true}{\let\iffoo=\iftrue}%
  recalling the definition of \@if:
\def\@if#1#2{\csname\expandafter\if@\string#1#2\endcsname}
  The first \expandafter expands the third one, which in turn causes the expansion of \@if, which has two arguments; in this case they are
#1<-\iffoo
#2<-true

But from my understanding the way that \def works is that it is sensitive to the non-argument characters (i.e., characters other than #1,#2,…,#9) that follow the command's name, such that (to take from p202 of the TeXbook) if you have \def\cs #1. #2\par{…} then \cs will need arguments that are given in the format #1. #2 where you need a .␣ separating the two, such that
\cs You owe \$5.00. Pay it.\par

gives
#1 <- You owe \$5.00
#2 <- Pay it.

Where (to quote the TeXbook)

the period in \5.00 doesn't stop #1, because TeX keeps going until finding a period that is immediately followed by a space.

And in the above \def\@if#1#2 is not \def\@if#1{#2}, and I would imagine that the latter wouldn't work since it would interpret #2 as the definition of \@if#1 thinking that \@if only took a single argument #1.
My second difficulty was in understanding the following section

So we're left with
\expandafter\def\csname\expandafter\if@\string\iffoo true\endcsname
  Now the remaining \expandafter triggers the expansion of \csname that, I recall, does exhaustive expansion until finding the matching \endcsname. So, in order to know what control sequence name will be produced, we have to follow the expansion of all tokens after \csname.
  The first token is \expandafter, that causes the expansion of \string; since \escapechar is -1, we're left with
\if@ iffootrue\endcsname

But I do not understand why \string has that effect both in the situation where \escapechar=-1 or where \escapechar has not been reassigned.
Acc. to the TeXbook

\string<token> TeX first reads the <token> without expansion. If a control sequence token appears, its \string expansion consists of the control sequence name (including \escapechar as an escape character, if the control sequence isn't simply an active character).

So I'm left to surmise that if it replaced \ before iffoo in \iffoo then

*

*why does \string have that effect when \iffoo is a control sequence and so (acc. to my likely misunderstanding of the TeXbook) should just be turned into its name, which is \iffoo (or is it iffoo, in which case why did the \escapechar need to be changed). Or,

*If \ was replaced as it is a "control sequence token" as opposed to a "control sequence", per se, where did the -1 go?

And finally, in the next section @egreg says

Because of its definition, \if@ removes i and f and leaves footrue; so we have
\def\footrue{\let\iffoo=\iftrue}

I believe that \if@ is defined in the following:
{\uccode'1='i \uccode'2='f \uppercase{\gdef\if@12{}}} % 'if' required

And I understand that the first part sets the uppercase value of 1 to be i and 2 to be f, but i do not understand why this section is enclosed in a separate set of brackets nor why this definition acts to remove i and f since it would seem to either be undefined if \uppercase was applied initially since \GDEF is not a valid command or would be expecting 1 and 2 as fixed arguments (not i and f) that it would eliminate (in that it returns an empty string).
I apologize if this seems entirely esoteric, but I am really trying to understand why these definitions work as they do, and I genuinely don't know where I'm going awry. I had originally intended to ask this in the comments of the original answer, but @egreg helpfully pointed out that my questions were extensive enough that comments were an inappropriate place for that discussion.

A: Saying \newif\iffoo generates the following list of tokens:
\count@\escapechar \escapechar\m@ne
\expandafter\expandafter\expandafter\def\@if\iffoo{true}{\let\iffoo=\iftrue}
\expandafter\expandafter\expandafter\def\@if\iffoo{false}{\let\iffoo=\iffalse}
\@if\iffoo{false}
\escapechar\count@

In what follows, spaces (or newlines) are added just for separating tokens; there is none in the definitions, so none is generated.
I recall also the definition of the auxiliary macros \@if
\def\@if#1#2{\csname\expandafter\if@\string#1#2\endcsname}

and \if@
{\uccode'1='i \uccode'2='f \uppercase{\gdef\if@12{}}} % 'if' required

What does \if@ do?
TeX opens a group, where new \uccode values for 1 and 2 are set. Then it executes \uppercase. The operation transforms character tokens in their uppercase equivalents, without changing category codes. The resulting token list is put back in the input stream and it is
\gdef\if@ if{}

where i and f have category code 12 (like 1 and 2). The space is there just for clarity, there's no space token. So the macro \if@ wants to see after it that pair of character tokens or an error is issued and swallows them producing nothing. Next the } restores the \uccode values of i and f.
Step 1
The assignments \count@\escapechar and \escapechar\m@ne are performed. In particular, the escapechar is set to –1, which means that \string\cs will expand to cs (each character with category code 12), because –1 is not a valid character code.
Step 2
\expandafter\expandafter\expandafter\def\@if\iffoo{true}{\let\iffoo=\iftrue}

TeX jumps over a token and expands the next one, which is \expandafter, so another token is jumped over and the next is expanded. It is \@if, which takes two arguments. The macro is not followed by {, so the first argument is the following (non space) token, which is \iffoo; a { follows, so the second argument is all tokens up to and including the matching }, so {true}. Recall that TeX strips off a pair of braces from an undelimited argument (and also from a delimited one, if this doesn't leave unbalanced braces). So argument #2 is true. Substitute \if@\iffoo{true} with the replacement text
\csname\expandafter\if@\string\iffoo true\endcsname

Again, the space is not there, I leave it just for separating tokens. There are ten tokens in this token list.
Step 3
Two \expandafter's are gone, the replacement text has been put in place of \if@ and its arguments, so we have
\expandafter\def\csname\expandafter\if@\string\iffoo true\endcsname{\let\iffoo=\iftrue}

TeX jumps over \def and expands \csname. This will ultimately expand to a symbolic token, that's in turn built up by expanding whatever comes up to the matching \endcsname
Step 4
Let's look what's the token list up to \endcsname:
\expandafter\if@\string\iffoo true

(the space is not there, remember). TeX jumps over \if@ and expands \string. This produces the five character tokens iffoo (because \escapechar is –1) all with category code 12. Thus we're left with
\if@ iffootrue

and \if@ is expanded. The required tokens are found and swallowed, so we get footrue. Now TeX finalizes the \csname...\endcsname construction, producing the token \footrue.
Step 5
The input stream has
\def\footrue{\let\iffoo\iftrue}

that's executed and removed.
Step 6
TeX now finds
\expandafter\expandafter\expandafter\def\@if\iffoo{false}{\let\iffoo=\iffalse}

and does exactly the same as before, but the final token list is
\def\foofalse{\let\iffoo\iffalse}

that's executed and removed.
Step 7
Now we have
\@if\iffoo{false}

that does the same as before, producing just
\let\iffoo\iffalse

so the conditional starts out false.
Step 8
The final tokens
\escapechar\count@

reset \escapechar to the value it had before starting \newif\iffoo.

A: The Knuth's macro \newif is very cryptic. I spent full page 402 in my "TeXbook naruby" with explanation of this. But we can ask if there isn't more straightforward and more understandable solution of this task with equivalent result. I mean that it exists. For example:
\def\newif#1{\expandafter\newifA\string#1\relax#1}
\edef\tmp{\string\if}
\expandafter\def\expandafter\newifA\tmp#1\relax#2{%
   \newifB#2{\csname#1true\endcsname}{\csname#1false\endcsname}%
}
\def\newifB#1#2#3{% #1=\iffoo  #2=\footrue  #3=\foofalse
   \let#1=\iffalse
   \expandafter\def#2{\let#1=\iftrue}%
   \expandafter\def#3{\let#1=\iffalse}%
}

A: working backwards:
{\uccode'1='i \uccode'2='f \uppercase{\gdef\if@12{}}} % 'if' required

\uppercase works on tokens and any token other than a character token is left unchanged. Character tokens produce new character tokens with the same catcode as before but with character code obtained by looking up the uccode (if that is non zero)
so \gdef uppercases to \gdef not to \GDEF and you get
\gdef\if@ if{}

which defines \if@ to take no argument and expand to nothing but gobble a catcode 12 i and f (or generate an error).
It's like this:
\catcode`i=12
\catcode`f=12
\def\if@if{}

except that doesn't work as the f in \def needs to be catcode 11 and as do the i and f in \if@
the construct is enclosed in brackets as you do not want the uppercase of 1 to be i for the rest of the document.
I'm not sure I understand your \string question. \string\iffoo makes the sequence of catcode 12 tokens \ i f f o o  except that the first \ is whatever character is specified by \escapechar or nothing if that is not a legal character code, so as it is -1 here \string\iffoo produces iffoo.


text:
Q: Gradient effect with UInt32 Colors? Hey I am new in programming and I want to know if it's possible to create a gradient effect having 2 colors (red and blue for example) of type UInt32.
Any suggestions? Thanks
ADDITION TO QUESTION
The idea is that I have only pixels informations:
        func fillRegion(pixelX: Int, pixelY: Int, withColor color: UIColor) {

    var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
    color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

    let newColor = (UInt32)(alpha*255)<<24 | (UInt32)(red*255)<<16 | (UInt32)(green*255)<<8 | (UInt32)(blue*255)<<0

    let pixelColor = regionsData.advanced(by: (pixelY * imageHeight) + pixelX).pointee

    if pixelColor == blackColor { return }

    var pointerRegionsData: UnsafeMutablePointer<UInt32> = regionsData
    var pointerImageData: UnsafeMutablePointer<UInt32> = imageData

    var pixelsChanged = false

    for i in 0...(imageHeight * imageHeight - 1) {
        if pointerRegionsData.pointee == pixelColor {
            pointerImageData = imageData.advanced(by: i)
            if pointerImageData.pointee != newColor {
                pointerImageData.pointee = newColor
                pixelsChanged = true
            }
        }
        pointerRegionsData = pointerRegionsData.successor()
    }

    if pixelsChanged {
        self.image = UIImage(cgImage: imageContext.makeImage()!)
        DispatchQueue.main.async {
            CATransaction.setDisableActions(true)
            self.layer.contents = self.image.cgImage
            self.onImageDraw?(self.image)
        }
        self.playTapSound()
    }
}

now it's filling with simple color, but I need to set a gradient somehow, I do not have a proper form, and I can't manage to set CAShapeLayer... as I have only pixel number information, and his color, though I am able to change the color here :
if pointerImageData.pointee != newColor {
                pointerImageData.pointee = newColor
                pixelsChanged = true
            }

But I don't know how to make a smooth changing of color, to make gradient effect, or to identify somehow the perimeter and set up a layer, dunno, any ideas will be as gold.

A: Yes it possible using CoreGraphics or CALayer.
To simplify, you can override the layer of a view returning a CAGradientLayer.
This is an implementation:
@implementation PGSGradientView

+ (Class)layerClass {
    return [CAGradientLayer class];
}

- (instancetype) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initializeGradient];
    }
    return self;
}

- (instancetype) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeGradient];
    }
    return self;
}

- (void) initializeGradient {
    [(CAGradientLayer*)self.layer setLocations:locations];
    [(CAGradientLayer*)self.layer setColors:colors];

}

@end

Imagine that you have 2 arrays as properties, one is locations and the other one are the colors that you want to add in the gradindient.
locations represents:

the starting location for each color. Also, and
  that's important, those numbers should mandatorily range from 0.0 to
  1.0.
  and is paired with the colors arrays.


text:
Q: mysql: connection refused when trying to connect to localhost using remote IP When I try to connect to a local mysql database using it's remote ip-address I get a access denied. When I try to connect to that same database from an external machine, it works without any problems. When I connect to the local database using localhost, it works perfectly as well. E.g., if the database server has the ip 1.2.3.4 then I get the following results:
# From the db server
mysql -u username -h localhost -p #works perfectly
mysql -u username -h 127.0.0.1 -p #works perfectly
mysql -u username -h 1.2.3.4 -p #Access denied

# From any other machine
mysql -u username -h 1.2.3.4 -p #works perfectly

What can I do to allow local access to my database using its remote ip-address? The OS of the database server is Fedora 15 and the MySQL version is 5.5.23.

A: I found the solution to my problem myself, but I still don't quite understand why it didn't work:
I granted privileges to that user on the hosts % and localhost:
# Before
+-----------------+------------+
| Host            | User       |
+-----------------+------------+
| %               | username   |
| localhost       | username   |
+-----------------+------------+

With these settings I got the results I showed above. When I granted privileges to that user on host  it suddenly did work.
# After
+-----------------+------------+
| Host            | User       |
+-----------------+------------+
| %               | username   |
| localhost       | username   |
| <myIpAddress>   | username   |
+-----------------+------------+

Apparently % does work for remote connections, but not for local connections.

A: Try to edit/add bind-address = 0.0.0.0 to your [mysqld] section of your /etc/mysql/mysql.conf.d/mysqld.cnf file and restart MySQL Service.

A: This particular issue can be caused by host name resolution.
I have resolved it in my particular case by deleting this variable from my my.cnf config file:
skip-name-resolve
Either remark the variable by placing a pound sign # or just delete it from your my.cnf after making sure you back it up, of course.


text:
Q: Recombination rate/time calculation for plasma vs. solid state semiconductors I've been able to find how to calculate the recombination rate for semiconductors as a function of the type of semiconductor (like silicon), the doping material, the concentration of the excess carrier and resistivity, and the model for recombination.  However, I don't know about the recombination rate calculation for a gaseous plasma.  Can a similar relationship be used to calculate the recombination rate of plasma, where the electrons would be more excited?  I suppose that would have to assume that the plasma would be a semiconductor, while generally atmospheric gases are considered insulators, but otherwise I was wondering what calculation you apply for plasma of say, neon or nitrogen (not sure if it differs for thermally or electrically dominated plasma).

A: There are two types of recombination processes in plasma, three-body (collisional) and radiative (or photo-recombination). The distinction is based on what particle removes excessive momentum and energy when an ion and an electron recombine. In the three-body recombination it is another electron, in the radiative recombination it is a photon. A good starting point for this subject is the NRL Plasma Formulary, it contains main formulas and references. This is extracted from the Formulary:


text:
Q: react bootstrap Card component - how to not display image on mobile? I am using the React Bootstrap Card component, and it looks fine on a browser, but on mobile the image gets squashed horribly, so I thought it would probably look better if it just didn't render it on mobile.
function RowCard({title, sub_title, post_text, image})
{
return (
    <Card style={{flexDirection: "row"}}>

        <Card.Img style={{width: "25%",objectFit: "cover"}} src={image} alt="banner" />

As an example this is the start of a function that produces a Card component given a struct with the relevant args.  I tried wrapping the <Card.Img..> line using BrowserView from react-device-detect, but this made the image tiny for some reason, and I tried importing isMobile from the same package, but wasn't sure how to actually make  use of it  (just doing if(!isMobile){<Card.Img...>} didn't work).
Can anyone provide any insight into how to do this?
Thanks

A: you can edit it with css by using media query for phone size
<Card.Img className="image" style={{width: "25%",objectFit: "cover"}} src={image} alt="banner" />
 @media only screen and (max-width: 600px) {
  .image{
    display: none  }
}

you can check it here https://www.w3schools.com/css/css_rwd_mediaqueries.asp
but you can also just resize the image size to fit on mobile screen and also a good practice to design a responsive website
here are also some of the media queries for other screen sizes
   /* Media Query for Mobile Devices */
    @media (max-width: 480px) {
        body {
            background-color: red;
        }
    }

    /* Media Query for low resolution  Tablets, Ipads */
    @media (min-width: 481px) and (max-width: 767px) {
        body {
            background-color: yellow;
        }
    }

    /* Media Query for Tablets Ipads portrait mode */
    @media (min-width: 768px) and (max-width: 1024px){
        body {
            background-color: blue;
        }
    }

    /* Media Query for Laptops and Desktops */
    @media (min-width: 1025px) and (max-width: 1280px){
        body {
            background-color: green;
        }
    }

    /* Media Query for Large screens */
    @media (min-width: 1281px) {
        body {
            background-color: white;
        }
    }


text:
Q: Ubuntu 14.04 Lts wifi not working My Wifi is connected perfectly with a good signal strength, but sometimes it just won't get connected or the connection is very slow and not working properly. The connection on Windows 8 on the same notebook (Lenovo Flex 2-14) was working smoothly.
After the bootup it works fine, but after a few minutes the problem arrives. The wifi adapter doesn't react anymore and I'm not able to (re/dis)connect with the router anymore. I have to restart to get it working again...
########## wireless info START ##########

Report from: 26 Mar 2015 10:56 CET +0100

Booted last: 26 Mar 2015 10:53 CET +0100

Script from: 20 Sep 2014 23:04 UTC +0000

##### release ###########################

Distributor ID: Ubuntu
Description:    Ubuntu 14.04.2 LTS
Release:    14.04
Codename:   trusty

##### kernel ############################

Linux 3.16.0-33-generic #44~14.04.1-Ubuntu SMP Fri Mar 13 10:33:29 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

Parameters: ro, quiet, splash, vt.handoff=7

##### desktop ###########################

Ubuntu

##### lspci #############################

02:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8723BE PCIe Wireless Network Adapter [10ec:b723]
    Subsystem: Lenovo Device [17aa:b736]
    Kernel driver in use: rtl8723be

03:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 10)
    Subsystem: Lenovo Device [17aa:3810]
    Kernel driver in use: r8169

##### lsusb #############################

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 04f3:0447 Elan Microelectronics Corp.
Bus 001 Device 003: ID 0bda:b728 Realtek Semiconductor Corp.
Bus 001 Device 002: ID 5986:055e Acer, Inc
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

##### PCMCIA card info ##################

##### rfkill ############################

0: ideapad_wlan: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: ideapad_bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: no
2: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
3: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

##### lsmod #############################

rtl8723be              85054  0
btcoexist              50304  1 rtl8723be
rtl8723_common         23361  1 rtl8723be
rtl_pci                26690  1 rtl8723be
rtlwifi                64255  2 rtl_pci,rtl8723be
mac80211              652718  3 rtl_pci,rtlwifi,rtl8723be
cfg80211              494362  2 mac80211,rtlwifi
snd_soc_rt5640         93042  0
snd_soc_rl6231         13037  1 snd_soc_rt5640
snd_soc_core          200204  1 snd_soc_rt5640
snd_pcm               104112  7 snd_soc_rt5640,snd_soc_core,snd_hda_codec_hdmi,snd_hda_codec,snd_hda_intel,snd_hda_controller,snd_pcm_dmaengine
wmi                    19193  0
ideapad_laptop         18278  0
sparse_keymap          13948  1 ideapad_laptop

##### interfaces ########################

auto lo
iface lo inet loopback

##### ifconfig ##########################

eth0      Link encap:Ethernet  HWaddr <MAC 'eth0' [IF]>
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

wlan0     Link encap:Ethernet  HWaddr <MAC 'wlan0' [IF]>
          inet addr:10.0.0.26  Bcast:10.0.0.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1174 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1036 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:665425 (665.4 KB)  TX bytes:140032 (140.0 KB)

##### iwconfig ##########################

eth0      no wireless extensions.

lo        no wireless extensions.

wlan0     IEEE 802.11bgn  ESSID:"WichtelLAN"
          Mode:Managed  Frequency:2.462 GHz  Access Point: <MAC 'WichtelLAN' [AC1]>
          Bit Rate=65 Mb/s   Tx-Power=20 dBm
          Retry short limit:7   RTS thr=2347 B   Fragment thr:off
          Power Management:off
          Link Quality=70/70  Signal level=-40 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:8   Missed beacon:0

##### route #############################

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.0.0.138      0.0.0.0         UG    0      0        0 wlan0
10.0.0.0        0.0.0.0         255.255.255.0   U     9      0        0 wlan0

##### resolv.conf #######################

nameserver 127.0.1.1
search home

##### nm-tool ###########################

NetworkManager Tool

State: connected (global)

- Device: eth0 -----------------------------------------------------------------
  Type:              Wired
  Driver:            r8169
  State:             unavailable
  Default:           no
  HW Address:        <MAC 'eth0' [IF]>

  Capabilities:
    Carrier Detect:  yes

  Wired Properties
    Carrier:         off

- Device: wlan0  [WichtelLAN] --------------------------------------------------
  Type:              802.11 WiFi
  Driver:            rtl8723be
  State:             connected
  Default:           yes
  HW Address:        <MAC 'wlan0' [IF]>

  Capabilities:
    Speed:           65 Mb/s

  Wireless Properties
    WEP Encryption:  yes
    WPA Encryption:  yes
    WPA2 Encryption: yes

  Wireless Access Points (* = current AP)
    foo:         Infra, <MAC 'foo' [AC3]>, Freq 2462 MHz, Rate 54 Mb/s, Strength 80 WPA WPA2
    UPC2038313:      Infra, <MAC 'UPC2038313' [AC8]>, Freq 2412 MHz, Rate 54 Mb/s, Strength 74 WPA WPA2
    foo:         Infra, <MAC 'foo' [AC2]>, Freq 2462 MHz, Rate 54 Mb/s, Strength 67 WPA WPA2
    1ADialup:        Infra, <MAC '1ADialup' [AN4]>, Freq 2412 MHz, Rate 54 Mb/s, Strength 64 WPA WPA2
    WichtelLAN_EXT:  Infra, <MAC 'WichtelLAN_EXT' [AC4]>, Freq 2462 MHz, Rate 54 Mb/s, Strength 64 WPA2
    UPC2757394:      Infra, <MAC 'UPC2757394' [AC6]>, Freq 2462 MHz, Rate 54 Mb/s, Strength 57 WPA WPA2
    BIBULE:          Infra, <MAC 'BIBULE' [AC7]>, Freq 2462 MHz, Rate 54 Mb/s, Strength 54 WPA
    *WichtelLAN:     Infra, <MAC 'WichtelLAN' [AC1]>, Freq 2462 MHz, Rate 54 Mb/s, Strength 80 WPA2
    UPC0397341:      Infra, <MAC 'UPC0397341' [AC12]>, Freq 2437 MHz, Rate 54 Mb/s, Strength 67 WPA WPA2
    UPC0055582:      Infra, <MAC 'UPC0055582' [AN10]>, Freq 2437 MHz, Rate 54 Mb/s, Strength 60 WPA WPA2
    UPC2126316:      Infra, <MAC 'UPC2126316' [AC5]>, Freq 2412 MHz, Rate 54 Mb/s, Strength 57 WPA WPA2
    Haiti3D:         Infra, <MAC 'Haiti3D' [AC10]>, Freq 2437 MHz, Rate 54 Mb/s, Strength 47 WPA WPA2
    ThomsonE579A7:   Infra, <MAC 'ThomsonE579A7' [AN13]>, Freq 2437 MHz, Rate 54 Mb/s, Strength 54

  IPv4 Settings:
    Address:         10.0.0.26
    Prefix:          24 (255.255.255.0)
    Gateway:         10.0.0.138

    DNS:             10.0.0.138

##### NetworkManager.state ##############

[main]
NetworkingEnabled=true
WirelessEnabled=true
WWANEnabled=true
WimaxEnabled=true

##### NetworkManager.conf ###############

[main]
plugins=ifupdown,keyfile,ofono
dns=dnsmasq

[ifupdown]
managed=false

##### NetworkManager profiles ###########

[[/etc/NetworkManager/system-connections/WLAN am See]] (600 root)
[connection] id=WLAN am See | type=802-11-wireless
[802-11-wireless] ssid=WLAN am See | mac-address=<MAC 'wlan0' [IF]>
[ipv4] method=auto
[ipv6] method=auto

[[/etc/NetworkManager/system-connections/WichtelLAN]] (600 root)
[connection] id=WichtelLAN | type=802-11-wireless
[802-11-wireless] ssid=WichtelLAN | mac-address=<MAC 'wlan0' [IF]>
[ipv4] method=auto
[ipv6] method=auto

A: I would start by doing this
echo "options rtl8723be fwlps=0 swlps=0" | sudo tee /etc/modprobe.d/rtl8723be.conf

Reboot and see if it works