text:
Q: How to create an alias from an select result in oracle? I want to create an alias from an select result.I've tried to use oracle dynamic query but doesn't working.Here is my sql:
declare
    v_a varchar2(50);
    sql_smt varchar2(200);
begin
    select TO_CHAR('#'||TO_CHAR(sysdate-30,'yyyymmdd')||'-'||TO_CHAR(sysdate+2,'yyyymmdd')) INTO v_a from dual;
    sql_smt :='SELECT sysdate as :1 FROM dual';
    execute immediate sql_smt using v_a;
end;

I want to reach to an result like in the photo.
Thanks for any help!

A: As you've tagged this for SQL Developer you could use (ab)use substitution variables for this; in your worksheet do:
column x_title new_value y_title noprint;

select TO_CHAR('#'||TO_CHAR(sysdate-30,'yyyymmdd')||'-'||TO_CHAR(sysdate+2,'yyyymmdd'))
  as x_title
from dual;

set verify off

select sysdate as "&y_title" from dual;

which when you run as a script (F5) produces this in the Script Output window:
<blank lines ...>

#20190126-
----------
2019-02-25

and then if you run the last line again as a statement (control-enter) the Query Result window shows it as you wanted, from the image in your question.
You could also use the column command which makes the output in the Script Output closer to what you wanted when run as a script:
column sysdate heading &y_title
select sysdate from dual;

#20190126-20190227
------------------
2019-02-25

but then when run as a statement the Query Results window doesn't honour that heading.
Note that this is all client-specific functionality, not SQL - it will work in SQL Developer, and the script versions will work in SQL*Plus and SQLcl, but not in other clients (unless they have tried to feature-match SQL*Plus to some extent).
If you aren't only going to be viewing the results in one of those clients but actually want to end up, say, pulling them into an application over JDBC or whatever, then other solutions would be more appropriate. Generating a ref cursor with the column as the name you want would be fairly simple. But that's not what you've asked for...

OK, since you asked in a comment, you can open a ref cursor in an anonymous block:
var rc refcursor

declare
  l_alias varchar2(50);
begin
  select TO_CHAR('#'||TO_CHAR(sysdate-30,'yyyymmdd')||'-'||TO_CHAR(sysdate+2,'yyyymmdd'))
  into l_alias
  from dual;

  open :rc for 'SELECT sysdate as "' || l_alias || '" FROM dual';
end;
/

PL/SQL procedure successfully completed.

print rc

#20190127-
----------
2019-02-26

or without the local variable:
var rc refcursor

begin
  open :rc for 'SELECT sysdate as "'
    || TO_CHAR('#'||TO_CHAR(sysdate-30,'yyyymmdd')||'-'||TO_CHAR(sysdate+2,'yyyymmdd'))
    || '" FROM dual';
end;
/

PL/SQL procedure successfully completed.

print rc;

#20190127-
----------
2019-02-26

Again var[iable] and print are client-specific commands; and I don't think there's a way to get the results in the Query Results grid with this approach. But you can use the same anonymous block approach from other clients or applications; e.g. from JDBC you could have a statement as:
String sql = "begin open ? for 'SELECT sysdate as \"'"
    + "|| TO_CHAR('#'||TO_CHAR(sysdate-30,'yyyymmdd')||'-'||TO_CHAR(sysdate+2,'yyyymmdd'))"
    + "|| '\" FROM dual'; end;";

and then bind the ? parameter placeholder as a cursor type before executing. That probably isn't very useful though as you'd have to examine the metadata to find the column alias anyway, and you could generate it on the application side using the application language tools (e..g Java date manipulation).
You could also create a function that returns a ref cursor, which you could then call from a plain query (instead of an anonymous block), which would allow you to see it in the Query Results grid - possibly with an extra step to show the cursor result. But you made not need that extra level of code or want another object to be created in your DB.

A: Would something like this work?
declare
  col_hdr   varchar2(50);
  sys_date  varchar2(26);
  sql_smt   varchar2(200);
begin
  select TO_CHAR('#'||TO_CHAR(sysdate-30,'yyyymmdd')||'-'||TO_CHAR(sysdate+2,'yyyymmdd')) INTO col_hdr from dual;
  sql_smt :='SELECT sysdate ' || ' as "' || col_hdr || '" FROM dual';
  dbms_output.put_line(sql_smt);
  execute immediate sql_smt into sys_date;
  dbms_output.put_line('done');
end;


text:
Q: Multiply multi-dimensional matrix to get new dataframe with new column names I created 2 DataFrames with [6,2] and [3,2]. I want to multiple 2 DataFrames to get [6,3] matrix. I am using the loop below but it is giving me a return self._getitem_column(key) error.Below is an example.
df1= pd.DataFrame{[1,2,3,4,5,6],
                  [23,24,25,26,27,28]}
df2= pd.DataFrame{[1,2,3],
                  [12,13,14]}

for j in range(len(df2)):
    for i in range(len(df1)):
       df3 = (df1[i, 2] * df2[j,2])
#expected result
df3= {0  1       2        3
      1  276     299     322
      2  288     312     336
      3  300     325     350
      4  312     338     364
      5  324     351     378
      6  336     364     392}

I am trying to replicate what I did in an excel sheet

A: It might be easier to leave it out of dataframes altogether, unless you have the information in dataframes currently (in which case, write back and I'll show you how to do that).
For now, this might be easier:
list1 = list(range(23,29)) # note that you have to go one higher to include 28
list2 = list(range(12,15)) # same deal
outputlist = []
for i in list1:
    for j in list2:
        outputlist.append(i * j)

import numpy as np
outputlist = np.array(outputlist).reshape(len(df1),len(df2))
import pandas as pd
df3 = pd.DataFrame(outputlist)

EDIT: Ok, this might get you where you need to go, then:
list3 = []
for j in range(len(df2)):
    for i in range(len(df1)):
       list3.append(df1.loc[i+1,0] * df2.loc[j+1,0])
import numpy as np
list3 = np.array(outputlist).reshape(len(df1),len(df2))
df3 = pd.DataFrame(list3)

EDIT AGAIN: Try this!  Just make sure you replace "thenameofthecolumnindf1" with the actual name of the column in df1 that you're interested in, etc.
import numpy as np
list3 = []
for i in df1[thenameofthecolumnindf1]:
    for j in df2[thenameofthecolumnindf2]:
       list3.append(i * j)

list3 = np.array(list3).reshape(len(df1),len(df2))
df3 = pd.DataFrame(list3)

A: The math for this simply won't work. To do matrix multiplication, Number of columns in the first matrix (6) should be equal to the number of rows in the second matrix (2). You're likely getting a key indexing error because of the mismatched row/column value.
You'll have to account for 3 different dimensions in order to properly multiply them, not just 2 as is done above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating New Column based on condition on Other Column in Pandas DataFrame I have this dataframe:
+------+--------------+------------+
| ID   | Education    |      Score |
+------+--------------+------------+
|    1 |  High School |      7.884 |
|    2 |  Bachelors   |      6.952 |
|    3 |  High School |      8.185 |
|    4 |  High School |      6.556 |
|    5 |  Bachelors   |      6.347 |
|    6 |  Master      |      6.794 |
+------+--------------+------------+

I want to create a new column which is categorizing the score column. I want to label it as: 'bad', 'good', 'very good'.
Which maybe would look like this:
+------+--------------+------------+------------+
| ID   | Education    |      Score | Labels     |
+------+--------------+------------+------------+
|    1 |  High School |      7.884 | Good       |
|    2 |  Bachelors   |      6.952 | Bad        |
|    3 |  High School |      8.185 | Very good  |
|    4 |  High School |      6.556 | Bad        |
|    5 |  Bachelors   |      6.347 | Bad        |
|    6 |  Master      |      6.794 | Bad        |
+------+--------------+------------+------------+

How can I do that?
Thanks in advance

A: I suppose it is the score you would like to map to the labels.
You could define a mapping function taking score as input and then returning the label:
def map_score(score):
  if score >= 8:
    return "Very good"
  elif score >= 7:
    return "Good"
  else:
    return "Bad"

df["Labels"] = df["Score"].apply(lambda score: map_score(score))

A: import pandas as pd

# initialize list of lists
data = [[1,'High School',7.884], [2,'Bachelors',6.952], [3,'High School',8.185], [4,'High School',6.556],[5,'Bachelors',6.347],[6,'Master',6.794]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['ID', 'Education', 'Score'])

df['Labels'] = ['Bad' if x<7.000 else 'Good' if 7.000<=x<8.000 else 'Very Good' for x in df['Score']]
df

    ID  Education    Score    Labels
0   1   High School  7.884    Good
1   2   Bachelors    6.952    Bad
2   3   High School  8.185    Very Good
3   4   High School  6.556    Bad
4   5   Bachelors    6.347    Bad
5   6   Master       6.794    Bad

A: Here is my solution. I amed to avoid if-else usage and make the solution more flexible.
The main idea is to create DataFrame of labels with their minimum and maximum values and then find the right label for each score value.
The code:
import pandas as pd

class Label(object):
    name = ''
    min = 0
    max = 100

    def __init__(self, name, min, max):
        self.name = name
        self.min = min
        self.max = max

    def data(self):
        return [self.name, self.min, self.max]

class Labels:
    labels = [
        Label('Bad', 0, 7).data(),
        Label('Good', 7, 8).data(),
        Label('Very good', 8, 100).data()]

    labels_df = pd.DataFrame(labels, columns=['Label', 'Min', 'Max'])

    def get_label(score):
        lbs = Labels.labels_df
        tlab = lbs[(lbs.Min <= score) & (lbs.Max > score)]
        return tlab.Label.values[0]

class edu:
    hs = 'High School'
    b = 'Bachelors'
    m = 'Master'

df = pd.DataFrame({
        'ID': range(6),
        'Education': [edu.hs, edu.b, edu.hs, edu.hs, edu.b, edu.m],
        'Score': [7.884, 6.952, 8.185, 6.556, 6.347, 6.794]})

df['Label'] = df.apply(lambda row: Labels.get_label(row['Score']), axis=1)

print(df)

Output:
   ID    Education  Score      Label
0   0  High School  7.884       Good
1   1    Bachelors  6.952        Bad
2   2  High School  8.185  Very good
3   3  High School  6.556        Bad
4   4    Bachelors  6.347        Bad
5   5       Master  6.794        Bad


text:
Q: How to properly merge CEF 2623 into 2454-based project I have a CEF-2454-based project that I wish to upgrade to 2623. However, I have made some changes to libcef needed for the project and I want to incorporate all changes made in 2623 without discarding my own changes. This raises me some questions:

*

*What git merge strategy should I employ?

*Can I build in my old 2454 directory, or I need to merge then build from scratch?

*Should I merge 2526 then 2623, or I can directly merge 2623?

What is the proper way to incorporate a new CEF release into my own project?

A: Typical way is to merge your changes onto new CEF version. Unfortunately all other methods are more difficult.
You can try to take a diff between your changes and original CEF 2454, and try to apply that patch on 2623.


text:
Q: How i add image map in joomla article? I have to give link to multiple parts of the image.so please tell me how i can do it in joomla1.5.22.

A: You are using JCE as your WYSIWYG editor right? If not, start by adding that. It's free and way better than TinyMCE. Once you have JCE installed, go to Components > JCE > Configuration and add map[name],area[shape|coords|href|alt|title] to the extended elements. Now you will be able to add the map code without losing it when you save plus you get a much better editor.


text:
Q: Changing ec2 instance type from m4.4xlarge to m5a.4xlarge I've an m4.4xlarge instance running Percona MySQL 5.7 on Ubuntu 16.04 and I plan to change the instance family to m5a.4xlarge. Are there any unforeseen problems that I might run into when doing this or is it just a matter of shutting down the instance, changing the instance type and restarting it again? Are there any linux kernel level compatibility issues that I need to look into?

A: The only potential data issue would be if you used instance store (as opposed to Elastic Block Storage) for the disk, but that's unlikely. Also, the IP address of the instance will change, so any applications that depend on that IP will need to be configured with the new IP. And as @ceejayoz pointed out, it's easy enough to test!


text:
Q: Log scale axis ticks & labels not removed after setting custom linear ticks I'm plotting with matplotlib. When I set the x-scale to 'log' and change the tick labels and formatting to display linearly, the logspace tick labels don't go away, and I end up with two sets of xticklabels (one linear and one logspace).
This didn't happen on another machine, so I think it is version-specific? Right now I'm working in Jupyter Notebook with matplotlib 2.0.2 and python 3.6.1.
MWE:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
%matplotlib inline
fig, ax = plt.subplots(1, 1)
xmin = 5
xmax = 50
ax.set_xscale('log')
ax.set_xticklabels(np.logspace(np.log10(xmin), np.log10(xmax), num=6))
ax.set_xticks(np.logspace(np.log10(xmin), np.log10(xmax), num=6))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
ax.set_xlim([xmin, xmax])


text:
Q: How can I search by specific category selected by the user I am trying to let the user select a category (3 in total) and then search for items in that category only.
Image for reference: https://ibb.co/zRspdFs
So, when a user clicks on, for example category 1, and then clicks on the form input, the search should show items from the selected category.
For now I have some dummy data as value for the input field. and I can retrieve values from the dropdown selection. But I don't know how to filter the search.

var availableTags = [
  "mama",
  "tata",
  "PAPI"
];

$('#menu li').click(function(ev) {
  ev.preventDefault();
  var value = $(this).val();
  $("#custId").val(value);
});

$("#searcher").autocomplete({
  source: availableTags,
  minLength: 0
}).click(function() {
  $(this).autocomplete("search", $(this).val());
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

<form class="form-inline col-lg-4 col-md-4 col-xs-12">
  <svg class="svg-custom" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                                <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
                            </svg>
  <input class="input-custom srch form-control mr-sm-2" type="search" placeholder="Search by Keywords" id="searcher" aria-label="Search">

1

2

3

        <input type="hidden" id="custId" name="custId" value="3487">

</form>

A: Can you make array that contains list of items that you can pass to autocomplete after category is selected?
eg:
var availableTags = [
    "mama",
    "tata",
    "PAPI"
];

var categories = [
[searchItem1, searchitem2...],
[searchItem1, searchitem2...],
[searchItem1, searchitem2...]
]

On category select you take index, and you pull searchable items by index, and then pass that to autocomplete:
$( "#searcher" ).autocomplete({
  source: categories[indexOfCategory]
});

Im sure there is a bit cleaner solution, jquery is not my specialty, but you can do something like this


text:
Q: Jenkins: skip if node is offline I have a task that executes on n machines based on a label. If for some reason, some of these machines are offline, I do not want Jenkins to put them in a queue, and wait until they are online. I would like Jenkins to execute the job on the remaining machines and complete the job. Any suggestions?
Edit 1:
I realized that the job is tied to all the machines:

I was forced to do this because I needed this job to run simultaneously on all the machines. So, my question remains the same. If some of these machines are offline, I would like to skip the job on them, rather than wait/queue.
Edit 2:
Jenkins CLI has a clear queue command. It seems promising for the time.

A: A fine solution can be achieved using GroovyAxis Plugin and the following script, that will return Axis list of online slaves only:
def axis = []
for (slave in hudson.model.Hudson.instance.slaves) {
 if (slave.getComputer().isOnline().toString() == "true") {
   axis += slave.name
 }
}
return axis

UPDATE:
Since Jenkins 2.0 the node API has been changed, so use Node.toComputer() instead:
http://javadoc.jenkins-ci.org/hudson/model/Node.html#toComputer%28%29
def axis = []
for (slave in jenkins.model.Jenkins.instance.getNodes()) {
 if (slave.toComputer().isOnline()) {
    axis += slave.getDisplayName()
 }
}
return axis

A: If the task is attached in a way that it only runs on a particular node, it will not be able to run it on other machines.
If that isn't the case then the task will run on any of the available executors, this is the default behaviour.
So in order check to see if the task can run on other nodes go to the job > configure and check the setting of the following.

If that is disable on the task, then you will need to check the nodes that they accept any jobs this can be found under the node settings. It should read like the following.

Goodluck.


text:
Q: Highlight several table cells with headers I want to highlight table cells when mouse drug on that cell. I really want to do
1. when mouse drug on the table cell that are highlighted by a border.
2. Which cells are highlighted the headers of that cell are also highlighted.
How can I do this?
Thank you
<script type="text/javascript">
     $(window).load(function() {
     $(function () {
         $("#Mytable td")
             .mousedown(rangeMouseDown)
             .mouseup(rangeMouseUp)
             .mousemove(rangeMouseMove);
     });

     var dragStart = 0;
     var dragEnd = 0;
     var isDragging = false;

     function rangeMouseDown(e) {
         if (isRightClick(e)) {
             return false;
         } else {
             var allCells = $("#Mytable td");
             dragStart = allCells.index($(this));
             isDragging = true;

             if (typeof e.preventDefault != 'undefined') { e.preventDefault(); }
             document.documentElement.onselectstart = function () { return false; };
         }
     }

     function rangeMouseUp(e) {
         if (isRightClick(e)) {
             return false;
         } else {
             var allCells = $("#Mytable td");
             dragEnd = allCells.index($(this));

             isDragging = false;
             if (dragEnd != 0) {
                 selectRange();
             }

             document.documentElement.onselectstart = function () { return true; };
         }
     }

     function rangeMouseMove(e) {
         if (isDragging) {
             var allCells = $("#Mytable td");
             dragEnd = allCells.index($(this));
             selectRange();
         }
     }

     function selectRange() {
         $("#Mytable td").removeClass('selected');
         if (dragEnd + 1 < dragStart) { // reverse select
             $("#Mytable td").slice(dragEnd, dragStart + 1).addClass('highlighte');
         } else {
             $("#Mytable td").slice(dragStart, dragEnd + 1).addClass('highlighte');
         }
     }

     function isRightClick(e) {
         if (e.which) {
             return (e.which == 3);
         } else if (e.button) {
             return (e.button == 2);
         }
         return false;
     }
     });
 </script>

A: It seems like you already have requirement #1 working fine in your code, to highlight the headers you could add this to your selectRange() function to get the index of the selected cells and add the class to the corresponding headers:
function selectRange() {
    $("#Mytable td").removeClass('selected');
    if (dragEnd + 1 < dragStart) { // reverse select
       var tds = $("#Mytable td").slice(dragEnd, dragStart + 1).addClass('highlighted');
    } else {
       var tds = $("#Mytable td").slice(dragStart, dragEnd + 1).addClass('highlighted');
    }
    tds.each(function(){
        $('#Mytable th').eq($(this).index()).addClass('highlighted');
    });
 }

Demo fiddle


text:
Q: Differentiate complex function? $$f(z)=3z^2+\bar{z}$$
I want to show the function is either differentiable or not so I can state if it is holomorphic or not. What is the method for this ?
Edit - Can some give an example of how to apply cauchy riemann equation to this question ?

A: If $f(z)$ were differentiable, then $f(z)-3z^2=\bar{z}$ would be differentiable since $3z^2$ is. However, $\bar{z}$ is not complex differentiable. Check this with the Cauchy-Riemann equations.

A: This function is differentiable everywhere except at z=0.  As with real differentiation, complex differentiation is still a linear operation, meaning that d/dz( $3z^2 + \bar{z}$) = d/dz ($3z^2$) + d/dz ($\bar{z}$).  The first term is differentiable everywhere.  The second term is not differentiable at zero because $\bar{z}'(0) = \lim_{z->0} (\bar{z}-0)/(z-0)$, and $\bar{z}/z$ can take on different values as $z->0$ for different directions (e.g. if you approach z from the positive real axis, $\bar{z}/z -> 1$; if you approach from the positive imaginary axis, $\bar{z}/z->-1$.  Here is a good page detailing this: http://en.wikipedia.org/wiki/Holomorphic_function


text:
Q: Date format not working in matplotlib figure I am trying to format dates on the X-axis in the format "Month, DD YYYY" in the figure that I am creating using the following code(with the problem line of code commented);
df = pd.read_csv('data_bitcoin.csv')
price_date = df['Date']
price_close = df['Close']

plt.plot_date(price_date, price_close, linestyle = 'solid')
plt.gcf().autofmt_xdate()
date_format = mpl_dates.DateFormatter('%b, %d %Y')
#plt.gca().xaxis.set_major_formatter(date_format)    <-- problem line
plt.show()

Once I execute this code I get the following figure;

but when I uncomment the problem line in the above code I get the following figure, with X-axis labels totally changed;

What could be the problem? Why is date totally changing? I think its because of some behavior of plt.gca() but I am not sure. Kindly help. Thanks.
Update:
The same problem line of code is working here in this piece of code:
plt.style.use('seaborn')
dates = [
    datetime(2016,1,1),
    datetime(2016,1,12),
    datetime(2016,1,15),
    datetime(2016,1,20),
    datetime(2016,1,22),
    datetime(2016,1,26),
    datetime(2016,1,30),
]

y = [1,2,3,4,5,6,7]

plt.plot_date(dates,y,linestyle='solid')
plt.gcf().autofmt_xdate()
date_format = mpl_dates.DateFormatter('%b, %d %Y')
plt.gca().xaxis.set_major_formatter(date_format)
plt.show()

and giving the following output;


text:
Q: Why Arduino needs to be restarted after PS2 controller communication in Arduino? And how to to do this via coding? When I ran the code for a drivetrain and opened serial monitor it was working, but when I powered on Arduino via dc Jack and ran the code. It was not working, because code is needed to restart after connection. I want to know that how can I solve this problem of PS2 communication and run my drivetrain without restart or starting serial monitor.
Code that I uploaded was given in this instructable
http://www.instructables.com/id/Control-anything-with-ps2-controller-and-Arduino-/

A: I got my answer by experimenting a lot. First thing is that you have to either restart your arduino or configure your pin after connection of ps2 to arduino. This can be done by 2 ways :
1) Restart arduino after connection by code or
2) configure again after connection
1 option you know well, i am discussing 2nd i.e configure :
as you know that you have already configured pins by function ps2x.config_gamepad();
Now you have to reconfigure it after connection of ps2 to arduino, you can use a function called reconfig_gamepad(); after read_gamepad(); in void loop.
my code for holonomic drive train is below find out comments //         there are total four commented lines in code. good luck. Hope this will solve your problem also.
#include <PS2X_lib.h>  //for v1.6
int dir1=13;
int dir2=11;
int dir3=9;
int dir4=7;

int pwm1=12;
int pwm2=10;
int pwm3=8;
int pwm4=6;

int value_mapped;
/******************************************************************
 * set pins connected to PS2 controller:
 *   - 1e column: original
 *   - 2e colmun: Stef?
 * replace pin numbers by the ones you use
 ******************************************************************/
#define PS2_DAT        44  //14
#define PS2_CMD        46  //15
#define PS2_SEL        48  //16
#define PS2_CLK        50  //17

/******************************************************************
 * select modes of PS2 controller:
 *   - pressures = analog reading of push-butttons
 *   - rumble    = motor rumbling
 * uncomment 1 of the lines for each mode selection
 ******************************************************************/
//#define pressures   true
#define pressures   false
//#define rumble      true
#define rumble      false

PS2X ps2x; // create PS2 Controller Class

//right now, the library does NOT support hot pluggable controllers, meaning
//you must always either restart your Arduino after you connect the controller,
//or call config_gamepad(pins) again after connecting the controller.

int error = 0;
byte type = 0;
byte vibrate = 0;

void setup(){

  Serial.begin(57600);
  pinMode(dir1,OUTPUT);
  pinMode(dir2,OUTPUT);
  pinMode(dir3,OUTPUT);
  pinMode(dir4,OUTPUT);

  pinMode(pwm1,OUTPUT);
  pinMode(pwm2,OUTPUT);
  pinMode(pwm3,OUTPUT);
  pinMode(pwm4,OUTPUT);
  delay(1000);  //added delay to give wireless ps2 module some time to startup, before configuring it

  //CHANGES for v1.6 HERE!!! **************PAY ATTENTION*************
  if_error_is_found:                                                                                //      <!---- changed here --->
  //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
  error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble);

  if(error == 0){
    Serial.print("Found Controller, configured successful ");
    Serial.print("pressures = ");
  if (pressures)
    Serial.println("true ");
  else
    Serial.println("false");
  Serial.print("rumble = ");
  if (rumble)
    Serial.println("true)");
  else
    Serial.println("false");
    Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;");
    Serial.println("holding L1 or R1 will print out the analog stick values.");
    Serial.println("Note: Go to www.billporter.info for updates and to report bugs.");
  }
  else if(error == 1)
  {
    Serial.println("No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips");
    goto if_error_is_found;                                       //      <!---- changed here --->
  }
  else if(error == 2)
    Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips");

  else if(error == 3)
    Serial.println("Controller refusing to enter Pressures mode, may not support it. ");

//  Serial.print(ps2x.Analog(1), HEX);

  type = ps2x.readType();

  switch(type) {
    case 0:
      Serial.print("Unknown Controller type found ");
      break;
    case 1:
      Serial.print("DualShock Controller found ");
      break;
    case 2:
      Serial.print("GuitarHero Controller found ");
      break;
  case 3:
      Serial.print("Wireless Sony DualShock Controller found ");
      break;
   }
}

void loop() {

  /* You must Read Gamepad to get new values and set vibration values
     ps2x.read_gamepad(small motor on/off, larger motor strenght from 0-255)
     if you don't enable the rumble, use ps2x.read_gamepad(); with no values
     You should call this at least once a second
   */
  if(error == 1) //skip loop if no controller found
    return;

  if(type == 2){ //Guitar Hero Controller
    ps2x.read_gamepad();          //read controller

    if(ps2x.ButtonPressed(GREEN_FRET))
      Serial.println("Green Fret Pressed");
    if(ps2x.ButtonPressed(RED_FRET))
      Serial.println("Red Fret Pressed");
    if(ps2x.ButtonPressed(YELLOW_FRET))
      Serial.println("Yellow Fret Pressed");
    if(ps2x.ButtonPressed(BLUE_FRET))
      Serial.println("Blue Fret Pressed");
    if(ps2x.ButtonPressed(ORANGE_FRET))
      Serial.println("Orange Fret Pressed");

    if(ps2x.ButtonPressed(STAR_POWER))
      Serial.println("Star Power Command");

    if(ps2x.Button(UP_STRUM))          //will be TRUE as long as button is pressed
      Serial.println("Up Strum");
    if(ps2x.Button(DOWN_STRUM))
      Serial.println("DOWN Strum");

    if(ps2x.Button(PSB_START))         //will be TRUE as long as button is pressed
      Serial.println("Start is being held");
    if(ps2x.Button(PSB_SELECT))
      Serial.println("Select is being held");

    if(ps2x.Button(ORANGE_FRET)) {     // print stick value IF TRUE
      Serial.print("Wammy Bar Position:");
      Serial.println(ps2x.Analog(WHAMMY_BAR), DEC);
    }
  }
  else { //DualShock Controller
    ps2x.read_gamepad(); //read controller and set large motor to spin at 'vibrate' speed
    ps2x.reconfig_gamepad();                                                                       //      <!---- changed here --->
    if(ps2x.Button(PSB_START))         //will be TRUE as long as button is pressed
      Serial.println("Start is being held");
    if(ps2x.Button(PSB_SELECT))
      Serial.println("Select is being held");

    if(ps2x.Button(PSB_PAD_UP)) {      //will be TRUE as long as button is pressed
      Serial.print("Up held this hard: ");
      Serial.println(ps2x.Analog(PSAB_PAD_UP), DEC);
    }
    if(ps2x.Button(PSB_PAD_RIGHT)){
      Serial.print("Right held this hard: ");
      Serial.println(ps2x.Analog(PSAB_PAD_RIGHT), DEC);
    }
    if(ps2x.Button(PSB_PAD_LEFT)){
      Serial.print("LEFT held this hard: ");
      Serial.println(ps2x.Analog(PSAB_PAD_LEFT), DEC);
    }
    if(ps2x.Button(PSB_PAD_DOWN)){
      Serial.print("DOWN held this hard: ");
      Serial.println(ps2x.Analog(PSAB_PAD_DOWN), DEC);
    }

    vibrate = ps2x.Analog(PSAB_CROSS);  //this will set the large motor vibrate speed based on how hard you press the blue (X) button
    if (ps2x.NewButtonState()) {        //will be TRUE if any button changes state (on to off, or off to on)
      if(ps2x.Button(PSB_L3))
        Serial.println("L3 pressed");
      if(ps2x.Button(PSB_R3))
        Serial.println("R3 pressed");
      if(ps2x.Button(PSB_L2))
        Serial.println("L2 pressed");
      if(ps2x.Button(PSB_R2))
        Serial.println("R2 pressed");
      if(ps2x.Button(PSB_TRIANGLE))
        Serial.println("Triangle pressed");
    }

    if(ps2x.ButtonPressed(PSB_CIRCLE))               //will be TRUE if button was JUST pressed
      Serial.println("Circle just pressed");
    if(ps2x.NewButtonState(PSB_CROSS))               //will be TRUE if button was JUST pressed OR released
      Serial.println("X just changed");
    if(ps2x.ButtonReleased(PSB_SQUARE))              //will be TRUE if button was JUST released
      Serial.println("Square just released");

  //  if(ps2x.Button(PSB_L1) || ps2x.Button(PSB_R1)) { //print stick values if either is TRUE
      Serial.println("Stick Values:");
      Serial.print(ps2x.Analog(PSS_LY), DEC); //Left stick, Y axis. Other options: LX, RY, RX
//Forward Direction And BAckward Diretion

if(ps2x.Button(PSB_R1)){
 if(ps2x.Analog(PSS_RY)>=0)
   {

//Forward Direction
     if(ps2x.Analog(PSS_RY)<127)
     {
      Serial.println("All MOtor Running Forward");
      digitalWrite(dir1,LOW);
      digitalWrite(dir2,HIGH);
      digitalWrite(dir3,HIGH);
      digitalWrite(dir4,LOW);
      value_mapped=map(ps2x.Analog(PSS_RY),127,0,0,80);
      analogWrite(pwm1,value_mapped);
      analogWrite(pwm2,value_mapped);
      analogWrite(pwm3,value_mapped);
      analogWrite(pwm4,value_mapped);
      }
//BAckward Direction
      if(ps2x.Analog(PSS_RY)>=127)
      {
        Serial.println("All MOtor Running Backward");
      digitalWrite(dir1,HIGH);
      digitalWrite(dir2,LOW);
      digitalWrite(dir3,LOW);
      digitalWrite(dir4,HIGH);
      value_mapped=map(ps2x.Analog(PSS_RY),127,255,0,80);
      analogWrite(pwm1,value_mapped);
      analogWrite(pwm2,value_mapped);
      analogWrite(pwm3,value_mapped);
      analogWrite(pwm4,value_mapped);
      }
  }

// LEft OR Right Direction
   if(ps2x.Analog(PSS_RX)>=0)
   {

      //Left diretion
      if(ps2x.Analog(PSS_RX)<128)
      {
      Serial.println("All MOtor Running Left");
      digitalWrite(dir1,HIGH);
      digitalWrite(dir2,HIGH);
      digitalWrite(dir3,LOW);
      digitalWrite(dir4,LOW);
      value_mapped=map(ps2x.Analog(PSS_RX),128,0,0,80);
      analogWrite(pwm1,value_mapped);
      analogWrite(pwm2,value_mapped);
      analogWrite(pwm3,value_mapped);
      analogWrite(pwm4,value_mapped);
      }
      //Right Direction
      if(ps2x.Analog(PSS_RX)>128)
      {
      Serial.println("All MOtor Running Right");
      digitalWrite(dir1,LOW);
      digitalWrite(dir2,LOW);
      digitalWrite(dir3,HIGH);
      digitalWrite(dir4,HIGH);
      value_mapped=map(ps2x.Analog(PSS_RX),128,255,0,80);
      analogWrite(pwm1,value_mapped);
      analogWrite(pwm2,value_mapped);
      analogWrite(pwm3,value_mapped);
      analogWrite(pwm4,value_mapped);
      }
    }

//All MOtors Clock

      if( (ps2x.Analog(PSS_LX)<128)  )
      {
      Serial.println("CLOCKWISE RUNNING ALL MOTORS");
      digitalWrite(dir1,LOW);
      digitalWrite(dir2,LOW);
      digitalWrite(dir3,LOW);
      digitalWrite(dir4,LOW);
      value_mapped=map(ps2x.Analog(PSS_LX),128,0,0,80);
      analogWrite(pwm1,value_mapped);
      analogWrite(pwm2,value_mapped);
      analogWrite(pwm3,value_mapped);
      analogWrite(pwm4,value_mapped);
      }

//All MOtors Anti-CLockwise
     if(ps2x.Analog(PSS_LX)>128)
     {
      Serial.println("CLOCKWISE RUNNING ALL MOTORS");
      digitalWrite(dir1,HIGH);
      digitalWrite(dir2,HIGH);
      digitalWrite(dir3,HIGH);
      digitalWrite(dir4,HIGH);
      value_mapped=map(ps2x.Analog(PSS_LX),128,255,0,80);
      analogWrite(pwm1,value_mapped);
      analogWrite(pwm2,value_mapped);
      analogWrite(pwm3,value_mapped);
      analogWrite(pwm4,value_mapped);
     }
}
if(ps2x.Button(PSB_L1)){

   if((ps2x.Analog(PSS_LX)>=120) && (ps2x.Analog(PSS_LX)<=128)){

   analogWrite(pwm1,0);
   analogWrite(pwm3,0);

   }

 //dIAGONAL L

        if(ps2x.Analog(PSS_LX)<120)
         {
          Serial.println("CLOCKWISE RUNNING ALL MOTORS");
          digitalWrite(dir1,LOW);
          digitalWrite(dir3,HIGH);
          value_mapped=map(ps2x.Analog(PSS_LX),128,0,0,80);
          analogWrite(pwm1,value_mapped);
          analogWrite(pwm3,value_mapped);
         }
    //dIAGONAL R
         if(ps2x.Analog(PSS_LX)>=128)
         {
          Serial.println("CLOCKWISE RUNNING ALL MOTORS");
          digitalWrite(dir2,HIGH);
          digitalWrite(dir4,LOW);
          value_mapped=map(ps2x.Analog(PSS_LX),128,255,0,80);
          analogWrite(pwm2,value_mapped);
          analogWrite(pwm4,value_mapped);
         }

}

  Serial.print(",");
  Serial.print(ps2x.Analog(PSS_LX), DEC);
  Serial.print(",");

    Serial.print(ps2x.Analog(PSS_RY), DEC);
      Serial.print(",");
      Serial.println(ps2x.Analog(PSS_RX), DEC);
  //  }
  }
  delay(50);
}

A: Here's how I did it.....
void setup()
{
  Serial.begin(9600);

  // retry logic to avoid a reset after power up
  do
  {
    delay(1000);
    error = ps2x.config_gamepad(13, 11, 10, 12, true, true);
    if (error == 1)
      Serial.println("No controller found, retry in a sec");
  } while (error == 1);

  if (error == 0)
  {
    Serial.println("Found Controller, configured successful");
    Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;");
    Serial.println("holding L1 or R1 will print out the analog stick values.");
    Serial.println("Go to www.billporter.info for updates and to report bugs.");
  }
  else if (error == 2)
    Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips");
  else if (error == 3)
    Serial.println("Controller refusing to enter Pressures mode, may not support it. ");

  type = ps2x.readType();
  switch (type)
  {
  case 0:
    Serial.println("Unknown Controller type");


text:
Q: Setting up Exchange server 2013 in Azure VM with Server 2012 I have a couple of questions relating to setting up exchange server on Azure.
Firstly, how would I estimate the approximate monthly cost of hosting my email server on Azure?
Secondly, is there a tutorial that provides steps for install and setup?
I assume it is something like
Create VM running Server 2012 essentials
Download Exchange server to folder on VM
Install exchange
Thanks in advance

A: It's worth noting that you will be unable to get any form of support if you have problems with your Exchange Server once operational as Microsoft does not support Exchange Server running on Azure (they would point you to Exchange Online as part of Office 365).
Also note that even if you do setup your mail server you will most likely suffer bounced messages from recipients as it's most likely the public IP of your Exchange server will be a member of the IP address ranges that most spam managers would rank low on the trust level.  This is why Microsoft partners with SendGrid for the purpose of mail delivery out of applications hosted in Azure.
Some cautionary reading: http://windowsitpro.com/blog/why-running-exchange-azure-unattractive-proposition

A: Microsoft provides a Calculator at Windows Azure site, which let you calculate the cost involved in hosting Server on Windows Azure.
To set up Exchange 2013 in Azure VM, follow the steps given below:

*

*Configure the virtual networking settings (not mandatory)

*Create a storage account

*Provision a virtual machine from the Windows Azure Gallery and
configure it as a Domain Controller

*Provision the Exchange virtual machine using PowerShell

*Install Exchange Server 2013

Please do let me know if there is any confusion.


text:
Q: How can i join sys.columns of view to sys.columns of the table it is referencing in T-SQL? I am trying to join records in sys.columns for a view, to the records in sys.columns for the table it is referencing, because i need the values of is_nullable, is_computed and default_object_id columns for the columns that are selected in the view.
The sys.columns records for the view have "incorrect" values, which you can observe by running the example queries below:
CREATE TABLE TestTable (
    FieldA int NOT NULL,
    FieldB int DEFAULT (1),
    FieldC as CONVERT(INT, FieldA + FieldB),
    FieldD int NOT NULL
)
GO

CREATE VIEW TestView WITH SCHEMABINDING AS
SELECT  FieldA, FieldC as TestC, FieldB + FieldC as TestD
FROM dbo.TestTable WHERE FieldD = 1
GO

SELECT  OBJECT_NAME(c.object_id) as ViewName, c.name as ColumnName,
        c.is_nullable as Nullable, c.is_computed as Computed,
   cast(CASE WHEN c.default_object_id > 0 THEN 1 ELSE 0 END as bit) as HasDefault
FROM sys.columns c
WHERE object_id = OBJECT_ID('TestTable')
GO

SELECT  OBJECT_NAME(c.object_id) as ViewName, c.name as ColumnName,
        c.is_nullable as Nullable, c.is_computed as Computed,
   cast(CASE WHEN c.default_object_id > 0 THEN 1 ELSE 0 END as bit) as HasDefault
FROM sys.columns c
WHERE object_id = OBJECT_ID('TestView')
GO

I have tried using system views to join on dependencies, but they do not give us information about which column in the view refers to which column in the table:
-- dm_sql_referenced_entities gives us all columns referenced, but all records
-- have referencing_minor_id 0, so we do not know which column refers to what
SELECT * FROM sys.dm_sql_referenced_entities('dbo.TestView', 'OBJECT')
GO

-- sql_dependencies gives us all columns referenced, but all records has
-- column_id 0 so we can not use this either of joining the columns
SELECT * FROM sys.sql_dependencies WHERE object_id = OBJECT_ID('TestView')
GO

-- sql_expression_dependencies just tells us what table we are referencing
-- if view is not created WITH SCHEMABINDING. If it is, it will return columns,
-- but with referencing_minor_id 0 for all records, so not able use this either
SELECT * FROM sys.sql_expression_dependencies
    WHERE referencing_id = OBJECT_ID('TestView')
GO

This unanswered post on social.msdn submitted by someone seems to be the same issue:
http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/4ae5869f-bf64-4eef-a952-9ac40c932cd4

A: You said "i need to know that TestView TestC refers to a computed column". This is not supported by SQL Server 2008 R2 (not sure for 2012 though, but i doubt it).
First you can query sys.columns or INFORMATION_SCHEMA.COLUMNS and you won't find what you want.
If you dig deeper, you will most probably try sys.sql_expression_dependencies and sys.dm_sql_referenced_entities (N'dbo.TestView', N'OBJECT'), but you can find table-column mapping there, not column-column. SQL server stores dependency information by 'high level' object (table, trigger...), not by its details (column). You will find same in sys.sysdepends. As a matter of fact dependency information is in SQL server unreliable.
At last, your only possibility would be to parse the view body by yourself. It can be found in sys.sql_modules:
SELECT m.definition
FROM
    sys.objects o
    JOIN sys.sql_modules m
        ON m.object_id = o.object_id
WHERE
    o.object_id = object_id('dbo.TestView')
    and o.type = 'V'

Parsing T-SQL is VERY hard, it could really push you to the limit of your efforts. For instance, it should be more or less easy to grab table references from the view, and then table columns, especially if your view is schema-bound. But if it's not, well... just think of asterisks that reference OUTER APPLY, which references recursive CTE...
Anyway, good luck!

A: Currently, when views are created there are two operations that happen at a high level - parsing & binding. Parsing is basically checking for syntax of the statement, keywords & such. Binding is the process of mapping the identifiers (object names, column names) in the statement to the corresponding objects (tables, views, functions, columns etc.) & derivation of types. Additionally, in case of view similar to SELECT statements you can optionally alias column references and expressions in the SELECT list or after the view name (ex: create view v1(a) as select i from t).
After binding, we persist only the column aliases & the derived types in the metadata since a view is logically a table derived from a query expression. So there is currently no way to determine the expression that the column aliases map to or what it contains (columns or functions or literals etc.)
 Only way to obtain the information you are looking for is to parse the view definition & perform your own binding. I believe we already have a bug that tracks the feature request to expose more richer dependency information regarding the mapping of aliases to column expressions in view definitions.
Lastly, SQL Server Developer Studio or Visual Studio Database Project uses the managed T-SQL parser to track such references so you can do refactoring or renaming for example using the project.
  Hope this helps clarify the problem/current implementation.

A: It seems like the misunderstanding is the assumption that object_id is a primary key in sys.columns. It is not. The object_id in sys.columns relates to the object_id in sys.objects.
So:
SELECT C.*
FROM sys.objects T
INNER JOIN sys.columns C
ON T.object_id = C.object_id
WHERE T.type in ('S','U') -- System Tables and User Tables
AND T.name = 'Address' -- Table Name
order by C.Column_ID

will return the columns in the "Address" table in AdventureWorks.


text:
Q: How to store the decimal remainder of a calculation in Java I'm trying to figure out how to store the remainder after casting to a whole number.
For example:
int amount = 274
int numDollars = amount/100;
//this returns 2 for numDollars, but clears out the .74, and I would like to store 74 to amount

Does this seem possible?

A: Without introducing a new operator, you could subtract the dollars from the amount:
int amount = 274;
int dollars = amount / 100;
int cents = amount - (dollars * 100);

However, Java, like C and C++, has a "modulo" ("mod") operator that gives the remainder:
int amount = 274;
int dollars = amount / 100;
int cents = amount % 100;

A: You can use the number you have just computed (numDollars):
int amount = 274;
int numDollars = amount / 100;
amount = amount - numDollars * 100;

Note that this line is equivalent to:
amount -= numDollars * 100;


text:
Q: Processing ASCII commands via RS232 in embedded c I have an RS232 interface to my microcontroller with a predefined set of commands. There are several hundred commands, e.g. PRESSURE 50 could be set pressure to 50; LIMIT 60 could be set some limit to 60.
Current, this is processed using a series of nested switch statements but this seems like an inelegant solution.
What would be the recommended / most efficient / most readable way to process these commands? A LUT would be the tidiest, but would surely have a lot of empty entries for letter combinations which don't exist (not ideal..).
Thanks for any ideas..

A: *

*Run-time proposal:
With a sorted array of struct { string, function pointer )

*

*sorted by qsort()

*retrieved by bsearch()
I hope qsort() and bsearch() are available in your platform (stdlib.h)

*Design-time proposal:
As comments suggest, it's better to sort the entries of the array initialization at design-time. A lot of ways exists, from code generation (luxurious) to macro processing (poor).
Suggestion of declaration, one into many:
typedef unsigned char byte;

typedef char commandId_t[40];

typedef void (*commandHandler_t)( const byte * payload );

typedef struct command_s {
   const commandId_t      commandId;
   const commandHandler_t handler;
} command_t;

static const command_t commands[] = {
#include "sortedCommandInitializers"
};

The file sortedCommandInitializers is a list of {"command-name", function-name}, which may be sorted by the command sort CommandInitializers.c > sortedCommandInitializers in the Makefile.
For make it's a dependencies like any other:
sortedCommandInitializers: CommandInitializers.c
    sort CommandInitializers.c > sortedCommandInitializers

myProgram.o: myProgram.c myProgram.h sortedCommandInitializers

A: Ever tried the strnstr function? It really is very fast. For a few 100 words, it would probably be faster then 8 or 9 separate strcmp() with some extra code in between to walk through a tree, and will need less memory to store.
I would try the following
a)build a list of the commands and put the most common at the beginning, and add a unique number to each i.e.
char command_names[] =

"PRESSURE 1"
"LIMIT 2"

;
int command_names_len = sizeof(command_names_str)

The C compiler should append these strings for you, so it is easy to move them in a another position
b) these numbers added are an index into a function pointer array, each function should have the same signature, probably that is possible when you allow that some will have unused parameters?
i.e.
/* just an example */
void (command*)(int a, int b, int c, int d);

void command_pressure (int a, int b, int c, int d) { }
void command_limit(int a, int b, int c, int d) { }

command commands[] =
( /*notused*/ NULL

, /*     1 */ command_pressure
, /*     2 */ command_limit

);

Both lists would match each other visually as well, makes controlling and maintaining it easier. The numbers in the comments are only for help and should match the numbers in the big string build with the function names
Then processing an incoming command is string format is very simple
char search_command[20]; /* or whatever the longest command name is */
char* position_of_command = NULL;
int number_of_command = -1;

strncpy( search_command, incomming_command, sizeof(search_command) );
strcat( search_command, " " );  /* must end with blank */

command_position = strnstr( command_names, search_command, command_names_len );
if( command_position != NULL ) {
  position_of_command += strlen(s earch_command) ; /* at beginning of number */
  number_of_command = atoi( position_of_command );
}

if( number_of_command > 0 ) {
  (*commands[number_of_command])(a,0,0,d);
} else {
  /* unknown */
}

Some time ago I wrote plain old C, so it might contain syntax error, but that would be the idea.
Advantages:
a) small memory print: no extra pointers or other extra structure overhead to find the command, few programming lines
b) simple to maintain: it is 'table' organized
c) most frequently used commands are handled the fastest!
Disadvantage:
a) keep in mind that commands ending with the same string are not allowed. Can be overcome by adding a blank at the beginning of the names, and also at the search_command. i.e.
" PRESSURE 1"
" LIMIT 2"


text:
Q: Why does Pillow convert return colours outside the specified palette? Using Pillow 5.4.1, Python 3.6.8
Given an image image.png with 9 distinct colours, and given a data palette with 5 distinct colours, one would expect that asking pillow to reduce the image to the described palette that the resulting image would contain colours from only that palette.
However, using the im.im.convert method returns an image with colours outside the specified palette; specifically they are always greyscale images (R==B==G values)
Sample Code, outputting the unique set of colours for the original image, palette, and converted image.
from PIL import Image
im = Image.open("image.png")

# create palette from raw data
# colours: Red, Green, Blue, Black, and White (5 total)
RGBBW = [(255,0,0), (0,255,0), (0,0,255), (0,0,0), (255,255,255)]
data = sum([list(x) for x in RGBBW], [])[:256]
pimg = Image.new("P",(16,16))
pimg.putpalette(data)

# Hack
im.convert("RGB")
cim_ = im.im.convert("P", 0, pimg.im)
cim = im._new(cim_).convert("RGB")

def colors(im):
    cs = []
    for x in range(im.width):
        for y in range(im.height):
            cs.append(im.getpixel((x,y)))
    return list(set(cs))

print("Original: %s" % colors(im))
print("Palette: %s" % RGBBW)
print("Convert: %s" % colors(cim))

Input image: ->  <- (3x3 pixel image, all pixels unique colours)
(Larger version, for visualisation only: )
Output:
Original: [(85, 85, 85, 255), (0, 0, 255, 255), (0, 0, 0, 255), (255, 0, 0, 255), (0, 255, 255, 255), (255, 255, 255, 255), (255, 255, 0, 255), (255, 0, 255, 255), (0, 255, 0, 255)]
Palette: [(255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 0, 0), (255, 255, 255)]
Convert: [(252, 252, 252), (0, 0, 255), (255, 0, 0), (0, 0, 0), (170, 170, 170), (0, 255, 0), (84, 84, 84)]

(Note that the hack to prevent dither is a workaround, pending a fix I've contributed to master (yet to be cut into a new release))
The values [(170, 170, 170), (84, 84, 84), (252, 252, 252)] appear in the converted image, but were not specified in the original palette. They all happen to be greyscale.
I think there's something in src/libImaging/Palette.c that's effecting this, but I'm not sure if this is a bug of the code, or a 'feature' of libjpeg

A: Turns out this issue is both user error and an unexpected initialisation issue.
The initialisation issue: As pointed out in the comments, the palette for a new image is specifically initialised as greyscale.
If we replace the entire palette with our own, then we're fine. Except, I wasn't.

data = sum([list(x) for x in RGBBW], [])[:256]

This line is logically incorrect.
The palette expects a flattened list of up to 256 triples of RGB, that is, an array of max len 768. If the array is anything less than this, then the rest of the greyscale will still be in play.
The better way to re-initialise the palette is to ensure we repeat a value as to override the greyscale.
In this case:
data = (sum([list(x) for x in RGBBW], []) + (RGBBW[-1] * (256 - len(RGBBW))))[:256*3]

That is:
data = (
    sum([list(x) for x in RGBBW], []) # flatten the nested array
    + (RGBBW[-1] * (256 - len(RGBBW))) # extend with the last value, to our required length, if needed
    )[:256*3] # and trim back, if needed.

This will result in the palette always being 768 length.
Using the last value from our provided array is an arbitrary choice, as is only used as a valid padding value.


text:
Q: How to redirect http traffic to https with spring boot 2.3.1 Good afternoon, I am working with spring boot and already implement http safe mode (https), but I need to know how to redirect http requests to https, and if it is necessary to specify a particular safe port like 443, or I can do it with any port. At the moment I use ports 8080 8443
My class
Main Class
package com.prueba.https;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class PruebaHttpsApplication {

    public static void main(String[] args) {
        SpringApplication.run(PruebaHttpsApplication.class, args);
    }

}

Request Class
package com.prueba.http.request;

public class PruebaRequest {

    public String nombre;

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

}

Response Class
package com.prueba.https.response;

public class PruebaResponse {

    public String saludo;

    public String getSaludo() {
        return saludo;
    }

    public void setSaludo(String saludo) {
        this.saludo = saludo;
    }

}

Controller Class
package com.prueba.https.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.prueba.http.request.PruebaRequest;
import com.prueba.https.response.PruebaResponse;

@RestController
public class PruebaController {

    @PostMapping(value = "/PruebaHTTPS")
    public Object PruebaController(@RequestBody PruebaRequest req) {
        PruebaResponse res = new PruebaResponse();
        res.setSaludo("Hola " +req.getNombre());
        return res;

    }

}

application properties
server.port=8443

server.ssl.key-store = classpath:keystore.p12
server.ssl.key-store-password = pass
server.ssl.keyStoreType = PKCS12
server.ssl.keyAlias = tomcat

pom xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.prueba.https</groupId>
    <artifactId>PruebaHTTPS</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>PruebaHTTPS</name>
    <description>Pruebas HTTPS</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Structure of my project

Conexion HTTPS

Conexion HTTP

UPDATE
Use the following code that works for my version of spring, however it gives me error with http requests:
package com.prueba.https;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
@Configuration
@EnableAutoConfiguration
public class WebsocketSourceConfiguration {

      @Bean
      public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new  TomcatServletWebServerFactory() {
          @Override
          protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
          }
        };
        tomcat.addAdditionalTomcatConnectors(getHttpConnector());
        return tomcat;
      }

      private Connector getHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
      }

}

HTTPS (8443)

HTTP(8443)

HTTP(8080)

Why can't I point to http: 8443 and redirect me to https?

A: To redirect your HTTP request to HTTPS requests you need add below configurations :
@Bean
public EmbeddedServletContainerFactory servletContainer() {
  TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
      @Override
      protected void postProcessContext(Context context) {
        SecurityConstraint securityConstraint = new SecurityConstraint();
        securityConstraint.setUserConstraint("CONFIDENTIAL");
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern("/*");
        securityConstraint.addCollection(collection);
        context.addConstraint(securityConstraint);
      }
    };

  tomcat.addAdditionalTomcatConnectors(redirectConnector());
  return tomcat;
}

private Connector redirectConnector() {
  Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
  connector.setScheme("http");
  connector.setPort(8080);
  connector.setSecure(false);
  connector.setRedirectPort(8443);
  return connector;
}

I hope this will work for you.


text:
Q: Cauchy functional equation over the complex field It is known that the only measurable solutions to the Cauchy functional equation $f(x+y) =f(x)+f(y)$ are the linear ones ($x,y\in \mathbb{R}$). Does the same hold if we take $x,y \in \mathbb{C}$?
Edit: After the first answer, I rephrase my question: Are the only measurable functions $f:\mathbb{C} \to \mathbb{C}$ which satisfy the Cauchy functional equation linear or anti-linear (that is of the form $f(z)=a \bar{z}+b)$?

A: $f(x)=\bar{x}$ satisfies the functional equation, and is not of the form $ax+b$ for any $a,b\in \mathbb{C}$ since $\overline{-x}=-\bar{x} \Rightarrow b=0$ and $ax=x$ for $x \in \mathbb{R}$ would force $a$ to be $1$.

A: $\mathrm{Re}(x+y) = \mathrm{Re}(x) + \mathrm{Re}(y)$.

 and more generally, map $x+iy$ to $u+iv$, using a $2\times 2$ real matrix.


text:
Q: After maximizing the form, half of the windows is lost and are out of windows for some screens So here is my form onstartUp event code:
        int height = Screen.PrimaryScreen.Bounds.Height;
        int width = Screen.PrimaryScreen.Bounds.Width;
        this.StartPosition = FormStartPosition.Manual;
        this.Size = new Size(width, height);
        this.WindowState = FormWindowState.Maximized;

the code works fine and the form starts up maximized. After distributing the applications to the user. A user complained and sent a screen shot with the form buttons on the RHS not appearing on the screen!!!
I figured what the problem is, but i don't know how to fix it. The problem is with windows fonts, Control Panel\Appearance and Personalization\Display\ font size on the development machine is small, on the customers it's medium.
how to accommodate for this in code?

A:
The problem is with windows fonts

Not exactly.  It is not the font size you are changing, it is the video adapter's dots-per-inch (DPI) setting.  The legacy setting is 96 dpi, since Vista it got a lot easier to change this setting.  Common other choices are 120 dpi (125%) and 144 dpi (150%), they are directly accessible from the Display applet with a radio button.
Monitor resolutions have been stuck for a very long time, ducking Moore's Law for a good 30 years already.  That's finally changing, in no small part due to Apple's push for "retina" displays.  The latest MacBook Pro has 2560 x 1600 pixels on a 13 inch screen, about 230 dpi.
That does come with a problem, any program that creates a, say, 1024x768 window has its UI turned into a postage stamp on such a display.  The UI just becomes unusable without a magnifying glass.  What is needed is for such a program to become aware of the video DPI setting and create a larger window, proportionally larger by the increase of the DPI setting compared to the way the window was originally designed.
This is automatic both in WPF and in Winforms.  WPF gets it by default since all of its locations and sizes are expressed in inches, with a unit of 1/96".  Winforms still works with pixels, but it has automatic scaling built-in through its AutoScaleMode property.
Which is what is happening on that user's machine, he's got the video DPI setting at a larger value than your machine.  However, without also having a larger number of pixels available on his screen.  Somewhat typically picked by someone that has a vision impairment, a side-effect of increasing the DPI setting is that fonts get larger and thus easier to read.  But with the inevitable problem that any controls that you put near the right and bottom edge of your window are going to fall off, the screen just isn't big enough.
You address this kind of problem by making your window layout adjustable.  Or in other words, by making your UI design work with any window size.  A very common feature of Windows programs.  Just try it on Visual Studio.  Drag the bottom right window corner around and observe how it deals with having less space available but still staying usable.  Lots of Winforms features to help you doing this, like the Control.Anchor and Dock properties, FlowLayoutPanel and TableLayoutPanel controls, the Resize event for tough cases.
The Q&D fix for this is the Form.AutoScroll property.  Set it to True to permit the UI to still be usable, the scrollbars allows the user to still get to controls that are off the window.

A: The code you posted has nothing to do with the problem. You designed the form in a higher screen resolution than the screen resolution of the user and didn't consider docking/anchoring the controls inside the form.


text:
Q: Rendering a display name containing HTML that's stored in Resource file I need to render a HTML link that exists inside of a resource file
[Display(Name = "MyPropertyName" ResourceType = typeof(Res.Props))]
public bool MyProperty{ get; set; }

The MyPropertyName resource has some HTML:
"Click here to find out more."

I need to render this on the View so the link is clickable. The HTML will never render despite what method I attempt, some attempts (not exact syntax but you get the gist) will display the raw HTML, and some don't display anything at all.
var htmlLabel = Html.LabelFor(m => m."MyPropertyName" ).ToString()
Html.Raw(htmlLabel)

Html.Raw(Html.LabelFor(m => m."MyPropertyName" ).ToString())
Html.Raw(Html.LabelFor(m => m."MyPropertyName")

MvcHtmlString.Create(htmlLabel);
Html.Raw(MvcHtmlString.Create(htmlLabel))

etc.
I found a suggestion of getting the attribute info on the controller and passing it in via ViewBag and then rendering it with HTML.Raw, So I followed this here (and a a few others) but that code only pulls in the name of the property "MyPropertyName" and not string from the resource file.
Any ideas? Thanks.

A: well now this suddenly decided to work after one last silly attempt. For anyone that hits this kind of issue in the future:
The application has a StronglyTypedResourceBuilder class that contains all of the data I need. So the following works without trouble:
@using StringResources = Namespace.Resources.StringResources

...

@Html.CheckBoxFor(m => m.MyPropertyName)
@Html.Raw(@StringRes.MyPropertyName)

...

what a waste of a morning.


text:
Q: Share a value across Tornado Websockets server I have a basic websocket server using Tornado framework in python. I want to share a value between the server functions:
class EchoWebSocket(websocket.WebSocketHandler):

    def check_origin(self, origin):
        return True
    def open(self):
        print ("connection opened")
    def on_close(self):
        tornado.ioloop.IOLoop.instance().stop()
        print ("connection closed")
    def on_message(self,message):
        print (message)

def Main():
    application = tornado.web.Application([(r"/", EchoWebSocket),])
    application.listen(9000)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    Main()

I tried to create a global object from a class like this:
class operate:
    state = "mutual"

    def __init__(self):
        self.state = 'mutual'

    def play(self):
        self.state = 'play'

    def pause(self):
        self.state = 'pause'

    def getStatus(self):
        return self.state

and call a global object, guessing that since the object is global it will be the same not creating a new one every message:
def open(self):
    global objectTV
    objectTV = operate()
    objectTV.play()
.
.
.
.
 def on_message(self,message):
        global objectTV
        objectTV = operate()
        print(objectTV.getStatus())

But it always print 'mutual'?

A: In the method on_message(), every time a new message arrives, you're instantiating objectTV again and again at objectTv = operate(). The new instance of operate class has the initial state set to 'mutual', that is why it's printing 'mutual'.
A simple fix would be to remove objectTV = operate() line from on_message() and it should work like you want it to.
But read some answers on this question: Why are global variables evil?.
So, the better approach to solve your problem would be to set a local attribute on the handler instance instead:
class EchoWebSocket(websocket.WebSocketHandler):
    ...
    def open(self):
        self.objectTV = operate()
        self.objectTV.play()

    def on_message(self, message):
        print(self.objectTV.getStatus()) # -> 'play'


text:
Q: Access Hangs on Subform recordsource set to SQL from VBA I have a "Search" form in my database that takes in a string, explodes it into an array and builds an SQL string based on a selected join type ("Or", "And", or "Exact Phrase" radio buttons). My code works perfectly 95% of the time, but every once and while the database hangs when I switch between the different join types and requery. I have confirmed that the SQL is being created properly and I think that the problem stems from trying to change the subform's recordsource while it is still loading.
The exact way that my search form works is as follows:

*

*The user puts a search term/phrase in a text box

*On the "After Update" event of the textbox, VBA creates an SQL string and stores it in a hidden text field (dubbed "ModifiedSearchValue")

*If the user changes the join type (radiobuttons with options "Or", "And", Or "Exact Phrase") the "After Update" event on the group evokes the VBA sub (as in #2) and VBA creates an SQL string which it stores in the hidden text field (dubbed "ModifiedSearchValue")

*When the user hits the "Search" button, VBA sets the RecordSource of the subform to the value of "ModifiedSearchValue" by:
Me!Results.Form.RecordSource = Me.ModifiedSearchValue
Again, this works perfectly most of the time, but if you enter the search term, click "Search", then change the join type and hit "Search" again, it causes the database to hang approximately 5% of the time.
My main VBA code is as follows
    Private Sub SearchString()
Dim SearchString, SearchStringTitle, SearchStringName, SearchStringDescription, SearchStringInvestigator, JoinValue, j, SQLString As String, SearchArray, varValue As Variant

    SearchString = Trim(Me.SearchValue)

    If Not IsNull(SearchString) Then
        SearchArray = Split(SearchString, " ")

        SQLString = "SELECT tbl_Studies.StudyID, tbl_Studies.Study_Short_Title, tbl_Studies.Study_Name, tbl_Studies.Study_Description, [qry_General:FullName_FMLD].FullName AS Investigator, tbl_Studies.Project_Type, IIf([Project_Type]=1,[tbl_Studies:Status]![Status],[tbl_Studies:NR_Status]![NR_Status]) AS Overall_Status, tbl_Studies.Date_Submitted, tbl_Studies.Date_Updated, tbl_Studies.Results_Summary, tbl_Studies.Inactive " & _
                    "FROM ([tbl_Studies:NR_Status] RIGHT JOIN ([tbl_Studies:Status] RIGHT JOIN tbl_Studies ON [tbl_Studies:Status].StatusID = tbl_Studies.Status) ON [tbl_Studies:NR_Status].NR_StatusID = tbl_Studies.NR_Status) LEFT JOIN [qry_General:FullName_FMLD] ON tbl_Studies.Investigator = [qry_General:FullName_FMLD].PersonID " & _
                    "WHERE "

        If Me.Join_Type <> 3 Then

            If Me.Join_Type = 1 Then
                JoinValue = "OR"
            ElseIf Me.Join_Type = 2 Then
                JoinValue = "AND"
            Else
                JoinValue = " "
            End If

    '--
            SearchStringTitle = "(("
            For Each varValue In SearchArray
                j = Trim(varValue)
                SearchStringTitle = SearchStringTitle & "(tbl_Studies.Study_Short_Title) Like ""*" & j & "*"""

                If varValue <> SearchArray(UBound(SearchArray)) Then
                    SearchStringTitle = SearchStringTitle & " " & JoinValue & " "
                End If
            Next varValue
            SearchStringTitle = SearchStringTitle & "))"

    '--
            SearchStringName = "(("
            For Each varValue In SearchArray
                j = Trim(varValue)
                SearchStringName = SearchStringName & "(tbl_Studies.Study_Name) Like ""*" & j & "*"""

                If varValue <> SearchArray(UBound(SearchArray)) Then
                    SearchStringName = SearchStringName & " " & JoinValue & " "
                End If
            Next varValue
            SearchStringName = SearchStringName & "))"

    '--
            SearchStringDescription = "(("
            For Each varValue In SearchArray
                j = Trim(varValue)
                SearchStringDescription = SearchStringDescription & "(tbl_Studies.Study_Description) Like ""*" & j & "*"""

                If varValue <> SearchArray(UBound(SearchArray)) Then
                    SearchStringDescription = SearchStringDescription & " " & JoinValue & " "
                End If
            Next varValue
            SearchStringDescription = SearchStringDescription & "))"

    '--
            SearchStringInvestigator = "(("
            For Each varValue In SearchArray
                j = Trim(varValue)
                SearchStringInvestigator = SearchStringInvestigator & "([qry_General:FullName_FMLD].FullName) Like ""*" & j & "*"""

                If varValue <> SearchArray(UBound(SearchArray)) Then
                    SearchStringInvestigator = SearchStringInvestigator & " " & JoinValue & " "
                End If
            Next varValue
            SearchStringInvestigator = SearchStringInvestigator & "))"

            SearchString = SearchStringTitle & " OR " & SearchStringName & " OR " & SearchStringDescription & " OR " & SearchStringInvestigator
        Else
            SearchStringTitle = "(((tbl_Studies.Study_Short_Title) Like ""*" & SearchString & "*""))"
            SearchStringName = "(((tbl_Studies.Study_Name) Like ""*" & SearchString & "*""))"
            SearchStringInvestigator = "((([qry_General:FullName_FMLD].FullName) Like ""*" & SearchString & "*""))"
            SearchStringDescription = "(((tbl_Studies.Study_Description) Like ""*" & SearchString & "*""))"

            SearchString = SearchStringTitle & " OR " & SearchStringName & " OR " & SearchStringDescription & " OR " & SearchStringInvestigator
        End If

        SearchString = SQLString & SearchString & ";"

        Me.ModifiedSearchValue.Value = SearchString
    End If
End Sub

Again, my theory is that the hanging is caused by changing the RecordSource of the subform before it has finished loading from the previous search, but I can't seem to determine any workaround.
Thanks in advance for any and all insight/help!

A: As per Olivier's suggestions, the true cause of the problem was VBA being called as part of the query [qry_General:FullName_FMLD]; switching to [qry_General:FullName_FML] (which doesn't call any VBA) eliminated all problems. I am guessing that the root of the problem was that the form was attempting to apply the filter before the query had returned a result thereby creating a corrupt filter string.
Here is the updated code using a filter method and replacing all bangs with dots:
Private Sub Search_Click()
    On Error GoTo Err_Search_Click

    Dim SearchString, SearchStringTitle, SearchStringName, SearchStringDescription, SearchStringInvestigator, JoinValue, j, SQLString As String, SearchArray, varValue As Variant

        Me.Results.Form.FilterOn = True
        SearchString = Trim(Me.SearchValue)

        If Not IsNull(SearchString) Then
            SearchArray = Split(SearchString, " ")

            If Me.Join_Type <> 3 Then

                If Me.Join_Type = 1 Then
                    JoinValue = "OR"
                ElseIf Me.Join_Type = 2 Then
                    JoinValue = "AND"
                Else
                    JoinValue = " "
                End If

        '--
                SearchStringTitle = "(("
                For Each varValue In SearchArray
                    j = Trim(varValue)
                    SearchStringTitle = SearchStringTitle & "(tbl_Studies.Study_Short_Title) Like ""*" & j & "*"""

                    If varValue <> SearchArray(UBound(SearchArray)) Then
                        SearchStringTitle = SearchStringTitle & " " & JoinValue & " "
                    End If
                Next varValue
                SearchStringTitle = SearchStringTitle & "))"

        '--
                SearchStringName = "(("
                For Each varValue In SearchArray
                    j = Trim(varValue)
                    SearchStringName = SearchStringName & "(tbl_Studies.Study_Name) Like ""*" & j & "*"""

                    If varValue <> SearchArray(UBound(SearchArray)) Then
                        SearchStringName = SearchStringName & " " & JoinValue & " "
                    End If
                Next varValue
                SearchStringName = SearchStringName & "))"

        '--
                SearchStringDescription = "(("
                For Each varValue In SearchArray
                    j = Trim(varValue)
                    SearchStringDescription = SearchStringDescription & "(tbl_Studies.Study_Description) Like ""*" & j & "*"""

                    If varValue <> SearchArray(UBound(SearchArray)) Then
                        SearchStringDescription = SearchStringDescription & " " & JoinValue & " "
                    End If
                Next varValue
                SearchStringDescription = SearchStringDescription & "))"

        '--
                SearchStringInvestigator = "(("
                For Each varValue In SearchArray
                    j = Trim(varValue)
                    SearchStringInvestigator = SearchStringInvestigator & "([qry_General:FullName_FML].FullName) Like ""*" & j & "*"""

                    If varValue <> SearchArray(UBound(SearchArray)) Then
                        SearchStringInvestigator = SearchStringInvestigator & " " & JoinValue & " "
                    End If
                Next varValue
                SearchStringInvestigator = SearchStringInvestigator & "))"

                SearchString = SearchStringTitle & " OR " & SearchStringName & " OR " & SearchStringDescription & " OR " & SearchStringInvestigator
            Else
                SearchStringTitle = "(((tbl_Studies.Study_Short_Title) Like ""*" & SearchString & "*""))"
                SearchStringName = "(((tbl_Studies.Study_Name) Like ""*" & SearchString & "*""))"
                SearchStringInvestigator = "((([qry_General:FullName_FML].FullName) Like ""*" & SearchString & "*""))"
                SearchStringDescription = "(((tbl_Studies.Study_Description) Like ""*" & SearchString & "*""))"

                SearchString = SearchStringTitle & " OR " & SearchStringName & " OR " & SearchStringDescription & " OR " & SearchStringInvestigator
            End If

            Me.Results.Form.Filter = SearchString
        End If

    Exit_Search_Click:
        Exit Sub

    Err_Search_Click:
        MsgBox ("There are no active records to review.")
        Resume Exit_Search_Click
End Sub

Again, the credit for this solution belongs to Olivier Jacot-Descombes - thanks for all your help and suggestions!


text:
Q: PIG - ExecException: ERROR 1070: Could not resolve testPyUDF.testFunc using imports I am facing a basic issue of importing a python script into PIG. i'm just trying a simple script like this:
PIG script
REGISTER 'test.py' using jython as testPyUDF;
load_data = LOAD '$input_path' USING PigStorage(',') AS (row1);
resp = FOREACH load_data generate row1, testPyUDF.testFunc() as (test:CHARARRAY);
DUMP resp;

test.py (Python UDF to import):
@outputSchema("test:chararray")
def testFunc():
    return "test"

But this results in an error: ExecException: ERROR 1070: Could not resolve testPyUDF.testFunc using imports: [, org.apache.pig.builtin., org.apache.pig.impl.builtin., com.yahoo.yst.sds.ULT., org.apache.pig.piggybank.evaluation., org.apache.pig.piggybank.evaluation.datetime., org.apache.pig.piggybank.evaluation.decode., org.apache.pig.piggybank.evaluation.math., org.apache.pig.piggybank.evaluation.stats., org.apache.pig.piggybank.evaluation.string., org.apache.pig.piggybank.evaluation.util., org.apache.pig.piggybank.evaluation.util.apachelogparser., string., util., math., datetime., sequence., util., java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
I even tried changing the python script path in REGISTER to HDFS path:
REGISTER 'hdfs:///user/xxx/......./test.py' using jython as testPyUDF;
and also absolute path on local..
REGISTER '/homes/user/..../test.py' using jython as testPyUDF;
No luck either way. What I am missing here?


text:
Q: UICollectionView.scrollToItem set animation speed When using collectionView.scrollToItem with IndexPath. is it possible to set custom scroll speed?

A: Yes, it is possible. Try this:
UIView.animate(withDuration: 5, animations: { [weak self] in
    self?.collectionView.scrollToItem(at: IndexPath(item: 10, section: 10), at: .middle, animated: false)
})

A: Use .layoutIfNeeded() on the collectionView to prevent the white flashing.
 UIView.animate(withDuration: 5, animations: { [weak self] in
        self?.collectionView.scrollToItem(at: IndexPath(item: 10, section: 10), at: .middle, animated: false)
        self?.collectionView.layoutIfNeeded()
 })