text:
Q: Spring Boot - catch all error controller for all 404 errors? (Multi Tenant specific?) I would like to implement a simple error controller within my Spring Boot app that handles all 404 errors. I currently have one now, however it won't catch any errors with a "/" after the initial error. So for example:
myapp.localhost/asdflas - this will be caught by my controller
myapp.localhost/asdflas/sadfdsfd - this will not be handled correctly.
I have a multi-tenant Spring Boot app, so I need to pass in variables to my error.html template in order to process custom properties. Currently, for the simple errors it is working fine.
I'm sure the following code I have is not correct, but my current "ErrorHandingController" class looks like this:
@Controller
public class ErrorHandlingController implements ErrorController {

@Autowired
private Environment environment;

@Autowired
private ErrorAttributes errorAttributes;

@Autowired
private SaleService saleService;

@Autowired
private OperatorService operatorService;

@Autowired
private AppProperties appProperties;

public void setAppProperties(AppProperties appProperties) {

    this.appProperties = appProperties;
}

@Override
public String getErrorPath() {
    return "/error";
}

@RequestMapping(value = {"/error/**", "error", "/error"}, produces = "text/html; charset=utf-8")
public String errorGeneric(ModelMap modelMap) {

    String tenantName = TenantContext.getCurrentTenant();

    String thisURL = environment.getProperty("server.address") + ":" + environment.getProperty("local.server.port");

    ReceiptConfig receiptProperties = operatorService.getOperatorProperty();

    TenantDTO tenantDTO = operatorService.getOperatorInfo(saleService.getOperatorId(TenantContext.getCurrentTenant()));

    if (tenantDTO.getTenantCode() == null)
        return "redirect:http://" + thisURL;

    modelMap.addAttribute("tenant", tenantDTO);
    modelMap.addAttribute("receiptProperties", receiptProperties);
    modelMap.addAttribute("url", "http://" + receiptProperties.getUrl() + "." + thisURL);

    return "error";

}

}
Is this approach somewhat correct or am I way off? (I'm guessing way off..)


text: Q: Как отсортировать и удалить лишние неймспейсы во всех файлах в VisualStudio 2022? Как отсортировать и удалить лишние неймспейсы во всех файлах в VisualStudio 2022, чтобы не заходить в каждый из них и не вызывать эту команду, а стразу выполнить для всех?

redpajama_set_name: RedPajamaStackExchange


text:
Q: ggplot position_dodge with multiple error bars I have five data points for each cross-classification of two categorical variables. I am trying to add some even spacing between error bars, so that they do not overlap in a faceted ggplot2 plot, but failing. Data is much like this...
library(ggplot2)
library(dplyr)

df0 <- iris %>%
  group_by(Species) %>%
  mutate(long_sepal = ifelse(Sepal.Length > mean(Sepal.Length),
                             yes = "long", no = "short")) %>%
  group_by(Species, long_sepal) %>%
  mutate(petal_rank = order(Petal.Width)) %>%
  filter(petal_rank <= 5)

> df0
# Source: local data frame [30 x 7]
# Groups: Species, long_sepal [6]
#
#    Sepal.Length Sepal.Width Petal.Length Petal.Width Species long_sepal petal_rank
#           (dbl)       (dbl)        (dbl)       (dbl)  (fctr)      (chr)      (int)
# 1           5.4         3.9          1.7         0.4  setosa       long          1
# 2           4.6         3.4          1.4         0.3  setosa      short          1
# 3           5.0         3.4          1.5         0.2  setosa      short          2
# 4           4.4         2.9          1.4         0.2  setosa      short          3
# 5           4.9         3.1          1.5         0.1  setosa      short          4
# 6           5.4         3.7          1.5         0.2  setosa       long          3
# 7           5.8         4.0          1.2         0.2  setosa       long          4
# 8           5.2         4.1          1.5         0.1  setosa       long          2
# 9           5.5         4.2          1.4         0.2  setosa       long          5
# 10          4.5         2.3          1.3         0.3  setosa      short          5
# ..          ...         ...          ...         ...     ...        ...        ...

Plot code thus far.
ggplot(data = df0,
       aes(x = long_sepal, y = Petal.Width,
           ymin = Petal.Width-0.05,
           ymax = Petal.Width+0.05)) +
  geom_pointrange(position = position_dodge(width = 0.4)) +
  facet_wrap(~ Species, scales = "free")

I have tried messing around with the width argument, but I get the same plot regardless of the value.

A: I believe you need to add a factor variable to df0 that will be allow you to dodge the observations within long_sepal.
# Create new grouping column by which we can dodge
df0$fac <- factor(unlist(sapply(as.vector(table(df0$long_sepal)), seq_len)))

# Assign fac to "group = " inside the aes()
... aes(x = long_sepal, y = Petal.Width, group = fac, ...

A: I've used position = position_jitter() before to avoid point overlapping,
I think this could be a solution for you.
Try :
    ggplot(data = df0,
       aes(x = long_sepal, y = Petal.Width,
           ymin = Petal.Width-0.05,
           ymax = Petal.Width+0.05)) +
  geom_pointrange(position = position_jitter()) +
  facet_wrap(~ Species, scales = "free")


text:
Q: Открытый текст одной ссылки по умолчанию Есть скрипт, который раскрывает текст по нажатию на ссылку.
Как сделать так, чтобы по умолчанию один всегда был открыт (первая ссылка)?

$(document).ready(function() {
    $('.view-source .hide').hide();
    $('.view-source a').on('click', function() {
        $('.view-source .hide').slideUp(500);
        $(this).parent().find('.hide').slideDown(500);
    });
});

    111

Спрятанный текст

    222

Спрятанный текст

    333

Спрятанный текст

A: Размещу тогда я ответом. Идея в том, чтобы при загрузке страницы скрывать не все блоки текста, а "все кроме первого":

$(document).ready(function() {
    var $texts = $('.view-source .hide');
    $texts.not(':first').hide();
    $('.view-source a').on('click', function () {
        $texts.slideUp(500);
        $(this).parent().find('.hide').slideDown(500);
    });
});

    111

Спрятанный текст

    222

Спрятанный текст

    333

Спрятанный текст

*

*.parent() - достаточно негибкое решение (в случае изменения HTML-структуры блока код может сломаться). Имеет смысл использовать вместо этого .closest('.view-source').

*Так как элемент с классом hide может быть виден на экране, имеет смысл переименовать класс, дав ему более правильное название для обозначения блока текста. Например, text.


text:
Q: In a microservice environment, who should 'own' services that are no longer in active development? In typical development environment, sizeable teams are typically aligned with largish projects. New features are shoe horned into existing monoliths. The team owns the monolith. Despite many parts of the monolith being no longer developed they are still being released and owned by the associated team. If there is a fix to be made it is clearly that team who perform it.
In a microservices world, many smaller services are built, typical by small teams of 1s and 2s that once built may no longer require changes. The developers then move on to something else. The service may be a dependency of a number of applications. There is no specific 'team' associated with the service.
So, when changes are required to the service, how does one assign ownership?

A: There is a saying where I come from "a dog with too many owners dies of starvation", meaning, when everyone things someone else is in charge, no one is really in charge even if people have agreed to share the responsibility.
There are many ways to address your situation but in all of them someone should be in charge. Some ways to address this issue:

*

*A single person should be responsible for the project. If this person moves to a new team, he or she should appoint the new project manager. If this person quits the company, someone else should be chosen by the remaining staff.

*Periodically check who is in charge of each project. If no one is in responsible, then act fact and assign someone.

*Everyone who was just appointed to a project should necessarily check if he or she can keep evolving the project. For instance, if the documentation is badly written or absent, or if the source code is too hard to read, then the newly appointed person should ask the previously responsible people during project handover.

There is no silver bullet but there are principles you can follow that will avoid some future headaches.

A: Like @Akira said. If everyone is responsible for one microservice, noone is.
Shared responsibility
Every two weeks team which is responsible for given MS will change.
So according to the date, you will have the owner.
Align teams according to the product they serve
Every team is responsible for Product, which is not microservice. It's group of microservices, which together bring value to the business. They work together to accomplish business needs in given domain. You may understand Product as a system, which is constructed with few microservices working together.
Such team should have domain knowledge about the whole system and should be more effective in supporting MS, which are under their's product.
Team which is created and destroyed after creating new MS
Thats kind of management is problematic. If MS isn't just another CMS, but very complex solution it may become even more problematic. People who wrote MS should be responsible for supporting it. If they are to value for the company to become supporters, take someone else, but let them communicate and ask question to the creators of MS. Otherwise MS may be come mess sooner or later.
Whatever you choose, keep your MS documentation up to date.


text:
Q: Global or pointer in managed C++ for customized class My project has both managed & unmanaged code.  I wrote a class cIVR in managed code, while defining it in an unmanaged cpp file.  The project has been working fine for some time.
Now I need to call a member function of one of objects in array 'arrChannels' from another function in the same file.
During array definition it's not allowing me to declare as static due to managed code, so I want to pass a reference to my array in a global pointer so I can access member function throughout the file.
I am using .Net 2008.
main() {
    array<cIVR^>^ arrChannels = gcnew array<cIVR^>(num_devices); //MAXCHAN
    for(int i=0; i< num_devices; i++) { //MAXCHAN
        arrChannels[i] = gcnew cIVR();
}

I want some thing like ->
cIVR *ch; //global
    ch =  arrChannels; //last in above code
func2(int index) {
    ch[index]->setNumber("123");
}

A: Aside from the 'having a global is generally not a good idea issue', the place to correctly initialise ch would be inside main() after you created the array.
I'd also strongly recommend using the correct prototypes for the functions that you're using, for example:
int main()

and
void func2(int index)


text:
Q: Using dropout with CudnnLSTM for training and validation I am trying to use dropout with CudnnLSTM (tf.contrib.cudnn_rnn.python.layers.CudnnLSTM), and I would like to be able to build just one graph and set the dropout to some non-zero fractional value for training and then set the dropout to 0 for measuring validation error metrics. With the usual Tensorflow LSTM cell (tf.contrib.rnn.LSTMCell) this is not too difficult because the keep_prob parameter accepts a Tensor but I find this is not an option for CudnnLSTM.
To be able to set the dropout, I tried to use a global variable to set the dropout and then change the value of that global variable between training and validation, but I don't think this works (can't prove it but it's my best guess). In particular my training and validation errors are about the same, whereas in the past when I train with dropout in an RNN (on the same data set) the validations tends to quickly be better than the training (since validation has dropout % set to 0). I have used the usual LSTM with such results (on the same data set), so I expected to see something similar with Cudnn.
So I have two questions.

*

*How can I definitely know whether the dropout is changing or not as I change the value of the global variable I used to set it? (my guess is not but if someone tells me I am wrong...how can I verify this?). I notice the git commit history, at least to me, is a little confusing as to whether the dropout is actually working even in the layers implementation.

*If setting the dropout via a global doesn't work, and I can't use a Tensor, how can I set the dropout to be different for training and validation? I suppose one way to do this is to build two graphs sharing weights, but how would I do this given that CudnnLSTM makes its own weights rather than having them passed in? Would someone be able to provide a code example as I have not been able to find one?

Thanks for any help.

A: The training parameter in the model call method in part controls whether dropout takes effect. If training = true, then dropout is applied; if training = false, dropout is ignored.
### testing out dropout with cudnn_rnn to see how it works
layers       = 5
hidden_units = 3
dropout      = 1.0
model        = cudnn_rnn.CudnnGRU(layers, hidden_units, dropout = dropout)

data = tf.ones([128, 100, 3])
model.build(data.shape)

training_output,  training_state  = model(data, training = True)
inference_output, inference_state = model(data, training = False)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
x, y = sess.run([training_output,  training_state])
w, v = sess.run([inference_output, inference_state])

We can see that x and y are all 0 because dropout is set to 1.0. But w and v are non-zero.


text:
Q: assign color to mouse cursor using CSS How can I assign color to the mouse cursor in a web-page?
Can anyone suggest me a way to do it using any of the technologies e.g. HTML, CSS, JavaScript?

A: Just to add the possibility to dynamically adding a cursor without providing an image but generating it on client with JavaScript and Canvas.
Demo contains a simple cursor drawn with shapes, but this could just as easily have been images, video and so forth (everything a canvas support).
Fiddle (updated 5/2016 for Firefox - moved from document to element).
Note: FireFox has problem when the cursor is changed so frequent as in this demo - updated to change only once per second. FF clears the cursor when setting a new image but since the new image needs to be decoded it shows the default in the mean time. Chrome waits until the image is decoded before switching over.
In any case it is merely to show it can be done using canvas - test demo using Chrome and don't change mouse so often :-).
The animation loop which here changes color randomly to demonstrate:
function loop() {

    var color = 'rgb(' + ((255 * Math.random())|0) + ','
                       + ((255 * Math.random())|0) + ','
                       + ((255 * Math.random())|0) + ')';
    makeCursor(color);

    setTimeout(loop, 1000);
}

The cursor maker:
function makeCursor(color) {

    // create off-screen canvas
    var cursor = document.createElement('canvas'),
        ctx = cursor.getContext('2d');

    cursor.width = 16;
    cursor.height = 16;

    // draw some shape for sake of demo
    ctx.strokeStyle = color;

    ctx.lineWidth = 2;
    ctx.moveTo(2, 10);
    ctx.lineTo(2, 2);
    ctx.lineTo(10, 2);
    ctx.moveTo(2, 2);
    ctx.lineTo(30, 30)
    ctx.stroke();

    // set image as cursor (modern browsers can take PNGs as cursor).
    element.style.cursor = 'url(' + cursor.toDataURL() + '), auto';
}

A: Use an image along with CSS cursor property, I don't see any need of JavaScript heere...
Demo
div {
   cursor: url(YOUR_IMAGE_URL), auto;
}

As commented, I've used auto which is nothing but default cursor just incase your image fails to load, exactly like we declare multiple font families.

A: You should create/look for a customized cursor. Then, use the cursor CSS property to include it on your website.
There's a tutorial for this here: http://www.axialis.com/tutorials/use-cursors-to-customize-websites.htm


text:
Q: CMD: Получение даты создания файла Подскажите, как через командную строку получить дату создания файла для её последующей записи в текстовый файл?
Дата изменения меня не устраивает, но среди модификаторов даётся только она: %~tимя_переменной
for %x in (*) do (echo %~nx %~tx >> F.txt)
Сейчас есть мысль выводить дату через dir /tc в файл, потом его разбирать, отлавливая значения, и уже их снова выводить в итоговый файл.
A: В общем, стал таки развивать эту мысль. Пришёл к такому результату:
dir folder\ /tc > dates.txt
set str=
for %x in (folder\*) do set str=!str!%~nx
findstr "%str%" < dates.txt > result.txt

Правда результат теперь и размеры файлов содержит, без них было бы идеально.
14.02.2015  18:08           131 072 f1
14.02.2015  18:08           262 144 f2
14.02.2015  18:10           393 216 f3


text:
Q: Savings settings in a custom PHP plugin for WordPress First, I'd like to pre-emptively apologize for doing anything naive or foolish. I'm a novice programmer, but I'm trying to learn. Right now, I'm trying to develop a plugin for wordpress as part of my internship. The plugin does what it needs to do for the most part, but I just can't seem to make the settings page work the way I want. I know the initialization part of the plugin is working properly, but I'm having trouble with using the settings page. Specifically, I don't where or how to use _POST in order to save the information. I also don't where to place the update_option function call after I've received the information from the settings page. Here's my code right now:
add_action( 'admin_menu', 'menu' );
add_action( 'admin_init', 'plugin_admin_init' );

function plugin_admin_init() { // whitelist options
  register_setting( 'plugin_options', 'plugin_options', 'plugin_options_validate' );
  add_settings_section('plugin_main', 'Main Settings', 'plugin_section_text',           'plugin');
  add_settings_field('plugin_text_string', 'REE View Count Settings',           'plugin_setting_string', 'plugin', 'plugin_main');
}

function menu() {
    add_options_page( 'REE View Count Options', 'REE View Count', 'manage_options',     'plugin', 'plugin_options_page' );
}

// generates the settings web page
function plugin_options_page() {
    echo '
';
    echo '
Options
';
    echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
    // In the line above, I don't know what to put. The file name of the plugin?
    // The URL of the settings page on the admin page? Or what I have currently?
    // Both the first and last options bring up a 404 page.
    settings_fields('plugin_options');
    do_settings_sections('plugin');
    echo '<input name="Submit" type="submit" value="' . esc_attr_e('Save Changes') . '"         />';
    echo '</form>';
    //update_option('plugin_options', $_POST['plugin_options']);
    // Where should I try to update the option? And how?
    echo '
';
}

//from add_settings_section parameter 3, in plugin_admin_init
function plugin_section_text() {
    echo '
Main description of this section here.
';
}

//Function from 3 paramter of add_settings_field in plugin_admin_init that outputs     input HTML
function plugin_setting_string() {
    $options = get_option('plugin_options');
    echo 'value of options is: ' . $options;
    echo "<input id='plugin_text_string' name='plugin_options' size='40' type='text'
    value='{$options}' />";
}

//Validation function from register_setting in plugin_admin_init
function plugin_options_validate($input) {
    echo "this is input: " . $input;
    $newinput = trim($input);
    if(!preg_match('/^[0-9]+$/', $newinput)) {
        $newinput = 10;
    }
    update_option('plugin_options', $newinput);
    return $newinput;
}

Note: I don't actually use these exact function/variable names - I have them prefixed with the actual plugin name.
Can you help me? I want to take the information the admin inputs into the settings page and update the database with the that information (which in this case is just a single number). I understand that I need to use PHP _POST, but I don't know how. Furthermore, I don't where to post to, because when I use action="the_file_name.php," I get a 404 error upon submission. What should the action of the form be so that I can use the information that I got from the admin submission and use it for later? And after I do that, how do update the setting? And by how, I mean where do I place update_option? I apologize if this seems rambly or vague - I feel like I'm somewhat over my head.
If it helps, I've been building this settings page in the same file as the plugin itself, with the help of this guide: http://ottopress.com/2009/wordpress-settings-api-tutorial/
Unfortunately, I don't see anything in that guide that speaks of updating information, just creating the page itself.

A: You want to point to action="options.php".  It handles updating the values.  Check out the following links to get more detailed info.
http://planetozh.com/blog/2009/05/handling-plugins-options-in-wordpress-28-with-register_setting/
http://www.sitepoint.com/wordpress-options-panel/


text:
Q: Why am I getting the warning message that NaNs are produced and the error message that function cannot be evaluated at initial parameters? Here is my code.  I'm trying to model an ROC curve using a custom function.  My goal is to estimate the 8 parameters that minimize the sse_total.  However, I keep running into two messages.
The first message is a warning message that tells me NaNs are produced.  The second message is an error message that says the function cannot be evaluated at the initial parameters.
X are non-cumulative false alarm rates, and Y are non-cumulative hit rates.  Non-cumulative are for model estimation only.
Any help would be greatly appreciated.
`
X<-c(0.01666667,
     0.00000000,
     0.06666667,
     0.11666667,
     0.36666667,
     0.43333333)
Y<-c(0.03333333,
     0.05000000,
     0.06666667,
     0.05000000,
     0.10000000,
     0.70000000)

df_dpsd<-data.frame(x=X,y=Y)

DPSD_1<-function(par){
R<-par[1]
Rn<-par[2]
dprime<-par[3]
c6<-par[4]
c5<-par[5]
c4<-par[6]
c3<-par[7]
c2<-par[8]
# c1<-par[9]

pred_FAR6<-((1-Rn)*qnorm(c6,0,1))
pred_FAR5<-((1-Rn)*(qnorm(c5,0,1)-qnorm(c6,0,1)))
pred_FAR4<-((1-Rn)*(qnorm(c4,0,1)-qnorm(c5,0,1)))
pred_FAR3<-((1-Rn)*(qnorm(c3,0,1)-qnorm(c4,0,1)))
pred_FAR2<-((1-Rn)*(qnorm(c2,0,1)-qnorm(c3,0,1)))
pred_FAR1<-(Rn+(1-Rn)*(1-qnorm(c2,0,1)))

pred_HR6<-(R+(1-R)*qnorm(c6,-dprime,1))
pred_HR5<-((1-R)*(qnorm(c5,-dprime,1)-qnorm(c6,-dprime,1)))
pred_HR4<-((1-R)*(qnorm(c4,-dprime,1)-qnorm(c5,-dprime,1)))
pred_HR3<-((1-R)*(qnorm(c3,-dprime,1)-qnorm(c4,-dprime,1)))
pred_HR2<-((1-R)*(qnorm(c2,-dprime,1)-qnorm(c3,-dprime,1)))
pred_HR1<-((1-R)*(1-qnorm(c2,-dprime,1)))

# SSE
sseH6<-(Y[1]-pred_HR6)^2
sseH5<-(Y[2]-pred_HR5)^2
sseH4<-(Y[3]-pred_HR4)^2
sseH3<-(Y[4]-pred_HR3)^2
sseH2<-(Y[5]-pred_HR2)^2
sseH1<-(Y[6]-pred_HR1)^2

sseF6<-(X[1]-pred_FAR6)^2
sseF5<-(X[2]-pred_FAR5)^2
sseF4<-(X[3]-pred_FAR4)^2
sseF3<-(X[4]-pred_FAR3)^2
sseF2<-(X[5]-pred_FAR2)^2
sseF1<-(X[6]-pred_FAR1)^2

sse_total<-(
  # sseH1+
              sseH2+sseH3+sseH4+sseH5+sseH6+
              # sseF1+
                sseF2+sseF3+sseF4+sseF5+sseF6)
return(sse_total)
}

(result <-optim(par=c(R=.25,Rn=.25,dprime=1,c6=-1.5,c5=-1,c4=-.5,c3=1,c2=1.5),
                fn=DPSD_1))

`
I've tried varying the initial parameters and have played around with various ways to configure the function so that it will optimize, but to no avail.
I've also looked through multiple top solutions to similar problems, but I have not had any luck in solving my problem.


text:
Q: 401 Unauthorized using ExchangeService for shared mailbox I know somebody here will say that this is a duplicate of some thread but, I dont get a clear answers from those thread and also not found anything that works as of this writing.
We just encounterred the 401 unauthorized on our API that uses Microsoft.Exchange.WebServices.Data's codes for sending automated emails that was working before
I checked the shared mailbox we used if its credential thats causing the issue however, it seems to not be the issue as its still valid
Are there any changes or updates done relating to this?
Are there any new approach to make it work again?


text:
Q: Incremental Sqoop on Dataproc gives "util.AppendUtils: Cannot append files to target dir; no such directory" I can run a full export of a postgresql table via a sqoop job on hadoop/google dataproc to export to a google storage bucket.  But when I try an incremental export it fails.
gcloud dataproc jobs submit hadoop \
  --cluster="$CLUSTER_NAME" \
  --class=org.apache.sqoop.Sqoop \
  --properties=mapreduce.job.classloader=true \
  --jars="$UBER_JAR" \
  --region="$CLUSTER_REGION" \
  -- job --create "$job_name" \
  -- import \
  --connect="${CONNECTION_STRING}" \
  --username="${SOURCE_USER}" \
  --password="${SOURCE_PASSWORD}" \
  --target-dir="gs://$WAREHOUSE_BUCKET_NAME/${EXPORT_DIRNAME}/${job_name}" \
  --table="$table_name" \
  --as-avrodatafile \
  --incremental=append \
  --split-by="${split_by}" \
  --check-column created \
  --last-value "2017-01-01 00:00:00.000000" \
  --verbose

The logs indicate that it was able to export data, but nothing appears in the google storage bucket.  I see the warning "util.AppendUtils: Cannot append files to target dir; no such directory":
...
20/03/13 20:52:18 INFO mapreduce.ImportJobBase: Transferred 4.6844 MB in 15.9306 seconds (301.106 KB/sec)
20/03/13 20:52:18 INFO mapreduce.ImportJobBase: Retrieved 27783 records.
20/03/13 20:52:18 DEBUG util.ClassLoaderStack: Restoring classloader: sun.misc.Launcher$AppClassLoader@7dc36524
20/03/13 20:52:18 WARN util.AppendUtils: Cannot append files to target dir; no such directory: _sqoop/df1bc552c9754b5aa2db3a6c04b03a75_insights_action
20/03/13 20:52:18 INFO tool.ImportTool: Incremental import complete! To run another incremental import of all data following this import, supply the following arguments:
20/03/13 20:52:18 INFO tool.ImportTool:  --incremental append
20/03/13 20:52:18 INFO tool.ImportTool:   --check-column created
20/03/13 20:52:18 INFO tool.ImportTool:   --last-value 2020-03-13 14:54:01.997784
20/03/13 20:52:18 INFO tool.ImportTool: (Consider saving this with 'sqoop job --create')
Job [1673b419f6c042d18dd8124f06e9c412] finished successfully.

Any idea if there's a workaround for this?

A: This is not an error just a warning, and should not lead to Sqoop job failure:
// This occurs if there was no source (tmp) dir. This might happen
// if the import was an HBase-target import, but the user specified
// --append anyway. This is a warning, not an error.


text:
Q: Android ListView Text Color I am trying to set the ListView textColor to black, since I am using a white background.
Here is my MailActivity
public class MailActivity extends ListActivity {

    String[] listItems = { "Compose", "Inbox", "Drafts", "Sent" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.mails);

        setListAdapter(new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, listItems));

    }
}

and my XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Empty set"
        android:textColor="#000000" />

</LinearLayout>

I'm getting the background as white, but am not sure where to set the foreground to black. I've tried in the xml and looks like it's not helping.

A: You have to define the text color in the layout *simple_list_item_1* that defines the layout of each of your items.
You set the background color of the LinearLayout and not of the ListView. The background color of the child items of the LinearLayout are transparent by default (in most cases).
And you set the black text color for the TextView that is not part of your ListView. It is an own item (child item of the LinearLayout) here.

A: *

*Create a styles file, for example: my_styles.xml and save it in res/values.

*Add the following code:
<?xml version="1.0" encoding="utf-8"?>
<resources>

<style name="ListFont" parent="@android:style/Widget.ListView">
    <item name="android:textColor">#FF0000</item>
    <item name="android:typeface">sans</item>
</style>

</resources>

*Add your style to your Activity definition in your AndroidManifest.xml as an android:theme attribute, and assign as value the name of the style you created. For example:
<activity android:name="your.activityClass" android:theme="@style/ListFont">

NOTE: the Widget.ListView comes from here. Also check this.

A: I cloned the simple_list_item_1(Alt + Click) and placed the copy on my res/layout folder, renamed it to list_white_text.xml with this contents:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:textColor="@color/abc_primary_text_material_dark"
    android:minHeight="?android:attr/listPreferredItemHeightSmall" />

The android:textColor="@color/abc_primary_text_material_dark" translates to white on my device.
then in the java code:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_white_text, myList);

A: Ok, here are some things that you should be clear about:

*

*The background color you are setting in your xml file is of the activity and not of the ListItems you are trying to define.

*Every list item has its own layout file which should be passed or inflated in case you are using complex layout for list item.

I'll try to explain this with a code sample:
****Lets start with ListItems layout** : save it in your res/layout folder of you Android project with say **list_black_text.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Definig a container for you List Item-->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center_vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- Defining where should text be placed. You set you text color here-->
    <TextView
        android:id="@+id/list_content"
        android:textColor="#000000"
        android:gravity="center"
        android:text="sample"
        android:layout_margin="4dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</LinearLayout>

Well, a simple layout with a TextView to be precise. You must have an id assigned to TextView in order to use it.
Now coming to you screen/activity/chief layout, as I said you are defining background to your screen with android:background attribute. I see you have defined a TextView there as well and I suspect you are trying to define content/list item there, which is not at all needed.
Here's your edited layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">

    <ListView
        android:id="@android:id/list" android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
        <!-- REMOVED TEXT VIEW, AND KEEPING BACKGROUND WHITE -->
</LinearLayout>

And lastly, most importantly, set your adapter.
setListAdapter(new ArrayAdapter<String>(
            this, R.layout.list_black_text, R.id.list_content, listItems));

Notice the layout resource which we are passing to adapter R.layout.list_black_text, and R.id.list_content which is TextView ID we declared. I have also changed ArrayAdapter to String type since it's generic.
I hope this explains everything. Mark my answer accepted if you agree.
Messy but a good quick fix way
You can also do this with a quick fix if you do not want to go ahead with complex layout defining etc.
While instantiating the adapter declare an inner class to do this, here is the code sample:
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(
            this, android.R.layout.simple_list_item_1, listItems){

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view =super.getView(position, convertView, parent);

            TextView textView=(TextView) view.findViewById(android.R.id.text1);

            /*YOUR CHOICE OF COLOR*/
            textView.setTextColor(Color.BLUE);

            return view;
        }
    };

    /*SET THE ADAPTER TO LISTVIEW*/
    setListAdapter(adapter);

A: never use getApplicationContext(). Just use your Activity as the Context. See if that helps.
Please check here:
CommonsWare answers

A: You can do this in your code:
final ListView lv = (ListView) convertView.findViewById(R.id.list_view);

for (int i = 0; i < lv.getChildCount(); i++) {
    ((TextView)lv.getChildAt(i)).setTextColor(getResources().getColor(R.color.black));
}

A: if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.
ADD android:theme="@style/AppTheme" in Android Manifest.

A: I needed to make a ListView with items of different colors. I modified Shardul's method a bit and result in this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, colorString) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setBackgroundColor(assignBackgroundColor(position));
                textView.setTextColor(assignTextColor(position));
                return textView;
            }
        };
        colorList.setAdapter(adapter);

assignBackgroundColor() and assignTextColor() are methods that assign color you want. They can be replaced with int[] arrays.


text:
Q: MISRA-2012 Rule 20.12 violation: misra_c_2012_rule_20_12_violation: macro parameter "val" is used in both expanded and raw forms I've been facing this MISRA violation:

Definitions:
#define A                 (1UL << 10)
#define INIT_A            ((A) | (1UL << 15))
#define INIT_A_MASK       (0xFFFFUL << 15)

#define IS_STATE_IFSET(state, val)  ((((state) & (val##_MASK)) == (val)) ? true : false)   //issue is here ?

Caller Details:
uint64_t state = 1234UL;
if (!IS_STATE_IFSET(state, INIT_A)) {
    printf("Hoo-Haa\n");
}

Misra-2012 reports Rule 20.12 violation misra_c_2012_rule_20_12_violation: macro parameter "val" is used in both expanded and raw forms

A: MISRA-C thinks it's stupid idea to use the same pre-processor constant twice in the same macro, where you have it expand in one case but not expand in another.
In your macro val##_MASK will not be expanded, so you getINIT_A_MASK. But later in the very same macro val is also expanded and replaced with ((A) | (1UL << 15)).
The only acceptable solution is to rewrite all of this crazy code from scratch and get rid of all use of secret macro languages.
For example, just what is the meaning of #define A (1UL < 10)? I assume << was intended. If not for the secret macro language, bugs like these are easy to find. But instead, you injected a hard-to-find dormant bug in your application.

A: Not sure if this can ever work in any case, when you write "if (!IS_STATE_IFSET(state, INIT_A))", the INIT_A will immediately be expanded into its macro definition, and the name will not be passed to the definition of IS_STATE_IFSET in the first place. I guess this is a case where your MISRA checker is behaving differently from a real C preprocessor.


text:
Q: Automatically creating and filling data frames in R Here is the code that I am working with.
  rnumbers <- data.frame(replicate(5,runif(20000, 0, 1)))
dt <- c(.001)
A <- dt*1
B <- dt*.5

## A = 0
## B = 1

rstate <- rnumbers  # copy the structure
rstate[] <- NA      # preserve structure with NA's
# Init:
rstate[1, ] <- rnumbers[1, ] <  .02 & rnumbers[1, ] > 0.01

step_generator <- function(col, rnum){
    for (i in 2:length(col) ){
            if( rnum[i] < B) { col[i] <- 0  }
                       else { if (rnum[i] < A) {col[i] <- 1 }
                              else {col[i] <- col[i-1] } }
                        }
    return(col)
    }
#  Run for each column index:
for(cl in 1:5){ rstate[ , cl] <-
                        step_generator(rstate[,cl], rnumbers[,cl]) }

rstate1 <- transform(rstate, time = rep(dt))
rstate2 <- transform(rstate1, cumtime = cumsum(time))

This gives me a data frame with 5 columns that contain state switches over time. Time interval is in the 6th column (seconds) and cumulative time is in the 7th column (seconds). Now I want to see how long each state lasts in seconds. This is what I am doing -
1) lengths <- rle(rstate2[,1])
>Run Length Encoding
  lengths: int [1:15] 366 3278 1817 451 3033 1655 1901 748 742 1780 ...
  values : num [1:15] 0 1 0 1 0 1 0 1 0 1 ...

2) lengths1 <- data.frame(state = lengths$values, duration = lengths$lengths)
> lengths1
       state duration
    1      0      366
    2      1     3278
    3      0     1817
    4      1      451
    5      0     3033
    6      1     1655
    7      0     1901
    8      1      748
    9      0      742
    10     1     1780
    11     0       26
    12     1      458
    13     0      305
    14     1     1039
    15     0     2401

3) library("plyr")
lengths2 <- transform(lengths1, time = duration*dt)
lengths3 <- arrange(lengths2, desc(state))

> lengths3
   state duration  time
1      1     3278 3.278
2      1      451 0.451
3      1     1655 1.655
4      1      748 0.748
5      1     1780 1.780
6      1      458 0.458
7      1     1039 1.039
8      0      366 0.366
9      0     1817 1.817
10     0     3033 3.033
11     0     1901 1.901
12     0      742 0.742
13     0       26 0.026
14     0      305 0.305
15     0     2401 2.401

4) col1 <- ddply(lengths3, .(state), function(df) 1/mean(df$time))
> col1
  state        V1
1     0 0.7553583
2     1 0.7439685

So, col1 is showing me "1/mean(time in each state)" for column1 of rstate2. What I would like to do is iterate steps 1-4 for every column in rstate2 and generate a data frame that looks like this :
> rates
  state col1 col2 col3 col4 col5
1     0  0.1  0.2  0.3  0.4  0.5
2     1  0.3  0.4  0.5  0.6  0.7

Where the numbers for each column are  equal to the 1/mean(df$time) for each of the column from rstate2.
Thank you for any and all help.

A: I'd do this using the development version of data.table (v 1.8.11) in this manner:
require(data.table) # 1.8.11
require(reshape2)
DT <- data.table(rstate2)
DT.m <- melt(DT, id=6, measure=1:5)
ans <- DT.m[, {dl=data.table:::duplist(list(value));
               list(state=value[dl], time=c(diff(dl),
               .N-dl[length(dl)]+1)*dt)
              }, by=list(variable)]
ans <- ans[, 1/mean(time), by=list(variable, state)]
dcast.data.table(ans, state ~ variable)

   state        X1        X2        X3        X4        X5
1:     0 0.9875568 1.0777521 0.3227194 2.2371365 0.7237054
2:     1 1.0127608 0.4442799 0.2802691 0.2887169 1.0576415

Unfortunately, it's still building on R-Forge. So, probably you can install 1.8.10 from CRAN and use reshape2's melt and cast (which'll output a data.frame) and convert the result back to a data.table and do the grouping as follows:
require(data.table) # 1.8.10
require(reshape2)
DT.m <- data.table(melt(rstate2, id=6, measure=1:5))
ans <- DT.m[, {dl=data.table:::duplist(list(value));
               list(state=value[dl], time=c(diff(dl),
               .N-dl[length(dl)]+1)*dt)
              }, by=list(variable)]
ans <- ans[, 1/mean(time), by=list(variable, state)]
dcast(ans, state ~ variable)


text:
Q: A container for accessing contents by 2d/3d coordinates There are a lot of games that can generally be viewed as a bunch of objects spread out through space, and a very common operation is to pick all objects in a sub-area. The typical example would be a game with tons of units across a large map, and an explosion that affects units in a certain radius. This requires picking every unit in the radius in order to apply the effects of the explosion.
Now, there are several ways to store objects that allows efficiently picking a sub-area. The easiest method is probably to divide the map into a grid; picking units in an area would involve selecting only the parts of the grid that is affected, and do a fine-grained coordinate check grid tiles that aren't 100% inside the area.
What I don't like about this approach is answering "How large should the grid tiles be?" Too large, and efficiency may become a real problem. Too small, and the grid takes up tons of memory if the game world is large enough (and can become ridiculous if the game is 3d). There may not even be a suitable golden mean.
The obvious solution to the above is to make a large grid with some kind of intelligent subdivision, like a pseudo tree-structure. And it is at this point I know for sure I am far into premature optimization. (Then there are proper dynamic quad/octrees, but that's even more complex to code and I'm not even confident it will perform any better.)
So my question is: Is there a standard solution to the above problem? Something, in the lines of an STL container, that can just store any object with a coordinate, and retreive a list of objects within a certain area? It doesn't have to be different than what I described above, as long as it's something that has been thought out and deemed "good enough" for a start.
Bonus points if there is an implementation of the algorithm in Python, but C would also do.

A: The first step to writing a practical program is accepting that choices for some constants come from real-world considerations and not transcendent mathematical truths. This especially applies to game design/world simulation type coding, where you'd never get anywhere if you persisted in trying to optimally model the real world. :-)
If your objects will all be of fairly uniform size, I would just choose a grid size proportional to the average object size, and go with that. It's the simplest - and keep in mind simplicity will buy you some speed even if you end up searching over a few more objects than absolutely necessary!
Things get a big harder if your objects vary greatly in size - for example if you're trying to use the same engine to deal with bullets, mice, humans, giant monsters, vehicles, asteroids, planets, etc. If that's the case, a common accepted (but ugly) approach is to have different 'modes' of play depending on the type of situation you're in. Short of that, one idea might be to use a large grid with a binary-tree subdivision of grid cells after they accumulate too many small objects.
One aside: if you're using floating point coordinates, you need to be careful with precision and rounding issues for your grid size, since points close to the origin have a lot more precision than those far away, which could lead to errors where grid cells miss some objects.

A: Here is a free book available online that will answer your question.
Specifically look at Chapter 18 on collision detection and intersection.

A: I don't know anything about games programming, but I would imagine (based on intuition and what I've read in the past) that a complete grid will get very inefficient for large spaces; you'll lose out in both storage, and also in time, because you'll melt the cache.
STL containers are fundamentally one-dimensional.  Yes, things like set and map allow you to define arbitrary sort relationships, but it's still ordered in only one dimension.  If you want to do better, you'll probably need to use a quad-tree, a kd-tree, or something like that.


text:
Q: Multiple case merge sql I have two datasets a and b each with fields for cusip and ticker. The sql i'd like to perform would take a column from set b if a.cusip=b.cusip, but if i cannot find a match for the cusip, i'd like to take the column from b if a.ticker=b.ticker.
Is there an easy way to execute this?  I'm having trouble constructing the code in one go.

A: You'll need to join to your B table twice, once on cusip and once on ticker.  Then you can use coalesce to take the first non-null value.
select
coalesce (b_cusip.column, b_ticker.column),
...

    from
    a
    left outer join b b_cusip
      on a.cusip = b_cusip.cusip
    left outer join b b_ticker
      on a.ticker = b_ticker.ticker

A: Inner join and Or in your where Clause condition should do the job.
Select *     from a
inner join   b on a.cusip=b.cusip
or           a.ticket = b.ticket;

A: You could try something like this:
data dataset_a;
input cusip ticker;
datalines;
1 111
2 222
3 333
5 555
;
run;
data dataset_b;
input cusip ticker value;
datalines;
1 111 10
20 222 25
30 333 40
4 444 55
;
run;

proc sql _method;
create table mydata as
select
a.*
,b.value
from dataset_a as a
left join dataset_b as b
on (case
        when a.cusip=b.cusip then 1
        when a.ticker=b.ticker then 1
        else 0
    end)=1
;
quit;

returns:
cusip    ticker    value
1   111   10
2   222   25
3   333   40
5   555    .


text:
Q: Plot certain points only I want to plot trading signal buy snd hold as follow:
!pip install yfinance
import yfinance as yf

# Data
df=yf.download('^GSPC',start='2009-11-26',end='2014-12-31',interval='1d')

# generate signal
df["SMA-25"]=df['Close'].rolling(25).mean()
df['SMA-diff']=df["SMA-25"].diff()
df['prediction-signal']= [1 if df.loc[ei,'SMA-diff'] > 0 else 0 for ei in df.index ]
df['yesterday-signal']= df['prediction-signal'].shift(1)

df['Sell']=[df.loc[ei,'Close'] if (df.loc[ei,'prediction-signal']==0 ) &( df.loc[ei,'yesterday-signal']==1) else 0 for ei in df.index ]
df['Buy']= [df.loc[ei,'Close']  if (df.loc[ei,'prediction-signal']==1) & (df.loc[ei,'yesterday-signal']==0) else 0 for ei in df.index ]
# I did the following but it also plotted 0 which made the graph funny
plt.plot(df['Close'],color='b',linestyle='-')
plt.plot(df['Buy'],color='g',linestyle='None',marker='*')
plt.plot(df['Sell'],color='r',linestyle='None',marker='*')

Any insights would be appreciated
thanks

A: You should replace the 0 values with None. Datapoints with value None will not be drawn.
There are two ways to get None instead of 0:

*

*in the two lines where you create the columns for Buy and Sell, you can replace the 0 in the else branch with None:

df['Sell']=[df.loc[ei,'Close'] if (df.loc[ei,'prediction-signal']==0 ) &( df.loc[ei,'yesterday-signal']==1) else None for ei in df.index ]
df['Buy']= [df.loc[ei,'Close']  if (df.loc[ei,'prediction-signal']==1) & (df.loc[ei,'yesterday-signal']==0) else None for ei in df.index ]

*

*if you do not want to change your calculation logic, you can replace the values afterwards just before plotting:

df.replace({0: None}, inplace=True)
plt.plot(...


text:
Q: Combining two ratios in a pastry ingredient To make 'short' pastry one uses flour to fat in the ratio 2 : 1. To make 'flaky' pastry requires a ratio of 4 : 3.
If I have 29 kg of flour and 20 kg of fat and wish to use all the ingredients making some of each type of pastry. How much flaky pastry do I make?
So my approach, long winded no doubt and possibly incorrect results, to make sense of the individual ratios:

*

*To make just 'short' pastry, using 29kg of flour + $\frac{29}{2}=14.5kg$ of fat (2:1 ratio), one could make a maximum of 43.5kg of 'short' pastry.

*To make just 'flaky' pastry, using all the fat this time as 29kg of flour would require 21.75kg of fat i.e. more than we have. 20kg of fat + $20*\frac{4}{3}=26.67kg$ of flour (4:3 ratio), one could make a maximum of 46.67kg of 'flaky' pastry.
How to then "combine" these ratios to make "some of each type of pastry" and use ALL of the ingredients?
Assume to use ALL the ingredients the ratios would have to fit neatly into the given quantities?
Based on @peterwhy direction:

*

*To make  kg of short pastry we use $\frac{2}{3}s$ of flour $\frac{1}{3}s$ of fat, to make  kg of flaky pastry we use $\frac{4}{7}f$ of flour $\frac{3}{7}f$ of fat.

So:

*

*total flour used: $\frac{2}{3}s$ + $\frac{4}{7}f$ = 29

*total fat used: $\frac{1}{3}s$ + $\frac{3}{7}f$ = 20

Solving simultaneously gives: s = 10.5, f = 38.5
So 38.5 kg of 'flaky' pastry is produced using all the ingredients.


text:
Q: trying to get the value of php into javascript I'm trying to get value of the $dateyearrange to put in yearRange:
For example my $dateyearrange = 2001
then the yearRange:'dateyearrange:+0' should be yearRange:'2001:+0'
but I can't seem to make it work
Edit: the problem in my code is in  yearRange:('dateyearrange:+0')
If I put echo <?php $Dateyear ?> the code wouldn't execute
because if I use yearRange:dateyearrange the ouput on the yearrange is only 2001 which is the code is working fine. so the problem in my code is in yearRange:
What i wanted is to be shown in yearrange is 2001:+0
I'm so sorry for my english I can't really explain myself to it.
EDIT 2:(Solution):
I use yearRange:"<?php echo $DateYear ?>:+0" and removed var dateyearrange = "<?php $Dateyear ?>";
I just made my code more complicated I don't know why I go in that way. Thanks for the replies it helps me.
<?php
$DateYear = date("Y", strtotime($Datebirth))
;?>
var dateminimum = "<?php Echo($Datebirth); ?>";
var dateyearrange = "<?php $Dateyear ?>";
  $(function() {
    $( "#datepicker" ).datepicker({minDate:dateminimum, maxDate:'0', yearRange:('dateyearrange:+0'), dateFormat: "yy-mm-dd",changeMonth: true,
      changeYear: true});
  });

A: <?php
$DateYear = date("Y", strtotime($Datebirth))
;?>
var dateminimum = <?php echo $Datebirth; ?>;
var dateyearrange = <?php echo $Dateyear ?>;
  $(function() {
    $( "#datepicker" ).datepicker({minDate:dateminimum, maxDate:'0', yearRange:('dateyearrange:+0'), dateFormat: "yy-mm-dd",changeMonth: true,
      changeYear: true});
  });

A: Change it to :
<?php
$DateYear = date("Y", strtotime($Datebirth))
;?>
var dateminimum = "<?php echo $Datebirth; ?>";
var dateyearrange = "<?php echo $Dateyear; ?>";
  $(function() {
    $( "#datepicker" ).datepicker({minDate:dateminimum, maxDate:'0', yearRange:('dateyearrange:+0'), dateFormat: "yy-mm-dd",changeMonth: true,
      changeYear: true});
  });

A: You still need to echo or print or =
var dateminimum = "<?php echo $Datebirth; ?>";
var dateyearrange = "<?php echo $Dateyear; ?>";


text:
Q: angular - Type 'Object' is not assignable to type 'any[]' I am trying to get data from a Django backend via a REST framework. I am using Angular 2 and the HttpClient & HttpClientModule modules, and basing my code off of a previous (working) project that used the Http module. When I run my code, I get an error stating that "Type 'Object' is not assignable to type 'any[]'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?". I am super new to Angular (this is only the second service I've ever written, and the first with HttpClient) and I am not sure how to correct this. I've looked at several similar questions, including this one and this one but I'm not sure how to generalize the answers back to a service instead of a component.
My code is here:
import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class FacultyService {
  private apiURL = 'http://localhost:8000/api/faculty';

  constructor(private http: HttpClient) { }

  getFaculty() {
    return this.http.get(this.apiURL)
      .toPromise()
      .catch(this.handleError);
  }

  private handleError(error: any) {
    console.error('An error occured', error);
    return Promise.reject(error.message || error);
  }

}


text:
Q: Can rasters in same CONSTRAINED table have different alignments in PostGIS? Context
I have a table filled with ASTER GDEM data for the state of Colorado tiled at 100x100 pixels. I want to query the table and return a single raster that covers all of the supplied bounding box (it surrounds Fort Collins, in this case).
Then, I export that raster in the selected GDAL format using a custom function written in Python/PL called write_raster.
I am attempting to do so using this query:
SELECT write_raster(ST_AsGDALRaster(ST_Union(rast), 'Gtiff'),  -- Raster bytea to write
  '/home/nronnei/gis/data/postgis-raster/colorado_elevation.tif'::text  -- Path to write to
)
FROM public.co_dem_tiled
WHERE ST_Intersects(
  ST_MakeEnvelope(-105.4330444336, 40.3789822705,
    -104.7024536133, 40.7170785158, 4326),
  ST_Envelope(co_dem_tiled.rast)
);

I'm using PostGIS v2.1, and the 'same_alignment' constraint is not set on the table. When I try to add the constraint it fails because the data aren't aligned.
The Problem
When I run this query, I get the following output:
ERROR:  rt_raster_from_two_rasters: The two rasters provided do not have the same alignment

Everything runs just fine if I remove ST_Union from the query above. What really makes this weird is that I'm only pulling raster from a single, constrained table.
Naturally, I tried using ST_NotSameAlignmentReason like so:
WITH base AS (
  SELECT rast
  FROM public.co_dem_tiled
  WHERE ST_Intersects(
    ST_MakeEnvelope(-105.4330444336, 40.3789822705,
      -104.7024536133, 40.7170785158, 4326),
    ST_Envelope(co_dem_tiled.rast)
  )
),
top AS (
  SELECT rast
  FROM public.co_dem_tiled
  WHERE ST_Intersects(
    ST_MakeEnvelope(-105.4330444336, 40.3789822705,
      -104.7024536133, 40.7170785158, 4326),
    ST_Envelope(co_dem_tiled.rast)
  )
)
SELECT ST_NotSameAlignmentReason(base.rast, top.rast)
FROM base, top;

However, this doesn't give me anything useful. It simply reports that all rasters have the same alignment, as expected.
What's going on here?!

A: I'm puzzled ST_NotSameAlignmentReason is returning Same Alignment for all, is it possible you missed one.
I think there was a bug a while back with this in 2.1 but can't remember the version.  The checks use ST_SameAlignment.
What does this return:
    WITH base AS (
SELECT rid, rast
 FROM public.co_dem_tiled
WHERE ST_Intersects(
 ST_MakeEnvelope(-105.4330444336, 40.3789822705,
  -104.7024536133, 40.7170785158, 4326),
 ST_Envelope(co_dem_tiled.rast) )
)
SELECT base.rid, ST_SameAlignment(base.rast, top.rast) AS same,
ST_NotSameAlignment(base.rast, top.rast) AS reason
FROM base, (SELECT rast FROM base LIMIT 1) As top
WHERE NOT ST_SameAlignment(base.rast, top.rast) ;

If you truly have all aligned in this set, it should return no records.
To answer your question, it's best to avoid different alignments in same table if you plan to union them since ST_Union requires all tiles in operation to be aligned.


text:
Q: C# Keep Hash Salt safe, even from developers We used MD5 with salt to hash user passwords and store in database.
BUT the salt is hard coded in code.
So, any developer who has access to code and database, can use brute force algorithm to match/recreate the hash.
Can someone help me what are best practices to keep salt away, even from developers. Let's just say, I want to restrict access to salt just to me(application owner)
I was thinking in terms of U2F or HSM, but I don't see how they fit here.
I don't want to use random/different salt for each user, because it doesn't solve my problem. I still have to keep those salt in database, that developers can access.
Note: I want to protect passwords from internal users/developers, who developed the application
Thanks

A: The problem you've got with your current idea of encrypting the salt is merely "kicking the can further down the road" In order to be usable the salt will need to be decrypted, which means the code will have to know how to do the decrypting, when means the developers will know how the code does the decrypting and its parameters
You could, of course, keep the decryption key in a secure string in memory only, never save it to disk and create an interface that lets the company CEO paste the key in (over an encrypted connection) from a USB he carries on a chain around his neck, that has a thumbprint lock.. etc.. and he needs to do that every time the server is restarted..
As per the comments, having a single salt could easily be switched out for a per-user salt, but your rogue dev probably still knows the users who are worth attacking so it might not help much if there are only a handful of them.
You really need to be looking at a hash algo that is a lot slower (devices that do billions of MD5 hashes/sec have existed for a long time), which means that brute forcing the passwords is unviable. There is of course a trade-off with these; they are much more work, computationally, for your server and by deliberately implementing something that is slow and takes a lot of resources you can line yourself up for DOS attacks, that will then need mitigating by separate means.
The immediate solution to your problem, if this is actively happening, is to change all the users' passwords and have them reset them to something else. You can detect if they change them back to what they were before (because the hash of the new will be the same as the hash in the backup table you'll create before you change everything). This has the side effect of letting your users know you've been compromised, but you could window dress that as your "awesome security systems have detected suspicious activity and locked their account for their safety" if you need to avoid revealing you've been compromised. Dealing with the company image fallout of this isn't something I guarantee can be swept under the rug but it's a problem for your marketing department rather than SO..

A: The salt has its very own job, to mitigate the usage of rainbow tables when the stored hashes are known to the attacker. What you want to prevent is an entirely different threat, so we should let the salt do its job and use a different solution. See also my tutorial about safely storing passwords. BTW MD5 is not appropriate to store passwords, use a password-hash function like BCrypt, Argon2, PBKDF2 or SCrypt instead.
What you can do is, to encrypt the already calculated hash values with an additional server side key. This en-/decryption can be delegated to a service on another server if necessary (HSM).
Especially if you want to protect from an insider attack, you should switch to one of the mentioned hash algorithms with a unique salt for each password, they are possibly your only protection from a successful brute-force attack, MD5 is way too fast and can be calculated at a speed of 100 Giga MD5/sec.


text:
Q: How to test the order of parameters passed to an object constructed by a method I'm testing a simple factory class with a single method which returns a TagModel.
class TagFactory
{
    public function buildFromArray(array $tagData)
    {
        return new TagModel(
            $tagData['t_id'],
            $tagData['t_promotion_id'],
            $tagData['t_type_id'],
            $tagData['t_value']
        );
    }
}

I can test the method…
public function testbuildFromArray()
{
    $tagData = [
        't_id' => 1,
        't_promotion_id' => 2,
        't_type_id' => 3,
        't_value' => 'You are valued',
    ];

    $tagFactory = new TagFactory();
    $result = $tagFactory->buildFromArray($tagData);
    $this->assertInstanceOf(TagModel::class, $result);
}

If I change the order of the parameters in new TagModel… the test will still pass.
If I prophesize the TagModel…
$tagModel = $this->prophesize(TagModel::class);
    $tagModel->willBeConstructedWith(
        [
            $tagData['t_id'],
            $tagData['t_promotion_id'],
            $tagData['t_type_id'],
            $tagData['t_value']
        ]
    );

… but what should I then be asserting? assertSame doesn't work because they aren't.
I could test the order with the getters from the TagModel but then I've gone beyond testing just this unit. Yet I do feel that the order should be tested because if I change them the test still passes.

A: The method you're testing is a factory. It creates an object. If making sure it's of the expected type is not enough for you, you need to verify its state. Either inspect it with getters, or create an object you're expecting to receive and use assertEquals() to compare it.


text:
Q: Unable to calculate Total in my shopping-cart I Have created a shopping cart with 2 components(Productlist and cart list). when I click on the 'add to cart' button in the product list it is successfully moving into the service file and from the service file to 'cart list' but Total was showing undefined. Please help me to solve this cart Total issue.
Product-list.ts file

    import { Component, OnInit } from '@angular/core';
    import { ProductService } from '../../../service/product.service';
    import { CartService } from '../../../service/cart.service';

    @Component({
      selector: 'app-product-list',
      templateUrl: './product-list.component.html',
      styleUrls: ['./product-list.component.css']
    })
    export class ProductListComponent implements OnInit {

      Productlist = [];

      constructor(private productservice: ProductService,
                  private cartservice: CartService) {

        this.Productlist = this.productservice.send()
       }

      ngOnInit(): void {
      }

      saveproduct(item) {

        this.cartservice.get(item)

      }
    }

cart service file
    import { Injectable } from '@angular/core';

    @Injectable({
      providedIn: 'root'
    })
    export class CartService {

      cartproducts = [{Name: 'Mobile', Price: 13000, Qty: 1}]

      constructor() { }

      send() {

        return this.cartproducts
      }

       get(items) {

        this.cartproducts.push(items)

        console.log(this.cartproducts)
       }
    }

cart list file

    import { Component, OnInit, ɵConsole, ɵɵNgOnChangesFeature } from '@angular/core';
    import { CartService } from '../../../service/cart.service';

    @Component({
      selector: 'app-cart',
      templateUrl: './cart.component.html',
      styleUrls: ['./cart.component.css']
    })
    export class CartComponent implements OnInit {

      cartlist = [];

      Total: number;

      constructor( private cartservice: CartService) {

        this.cartlist = this.cartservice.send()

        console.log(this.cartlist);

        console.log(this.Total);

       }

      ngOnInit() {

        this.cartlist.forEach((_e: any) => {

          this.Total += (_e.qty * _e.price);

        });
      }
    }

A: When the Total property has been created, it is undefined by default until you assign it a value. You do assign a value to it in the ngOnInit but you calculate on an undefined value, so it returns undefined as well. Give Total a default value like so:
    ...

    Total: number = 0;

    ...

Also the code you put in ngOnInit to calculate the Total, would be better placed in a get property. This way, Total will always be calculated when it's requested instead of pre-rendered and only calculated once. In that case your code would look like:
    get Total(): number {
      let value = 0;
      this.cartlist?.forEach((_e: any) => {
          value += (_e.qty * _e.price);
        });
      return value;
    }


text:
Q: Конкатенация числа и строки по условию У меня есть фрейм, в котором две колонки:
Цена(int) и промо. В промо два вида значений: либо NaN, либо str. Не могу написать цикл, который пробегался бы по столбцу промо и выполнял следующее условие: если в промо str, то мы конкатинируем значение этой строки с ценой, а если nan, то оставляем просто цену.

A: В первом приближении можно просто использовать .str.cat:
import pandas as pd

df = pd.DataFrame({'price': [100, 223, 344234, 3423], 'promo': [pd.NA, ' - со скидкой', ' - можно в кредит', pd.NA]})
df['price-promo'] = df.price.astype(str).str.cat(df.promo.fillna(''))
df

Вывод:

    price   promo             price-promo
0   100     <NA>              100
1   223     - со скидкой      223 - со скидкой
2   344234  - можно в кредит  344234 - можно в кредит
3   3423    <NA>              3423


text:
Q: How do we print out the value_type of a C++ STL container? I know that STL containers have a value_type parameter and I've seen how it can be used to declare a type of a variable like:
vector<int>::value_type foo;

But can we just print this value_type to a console?
I want to see "string" in this example:
int main() {
    vector<string> v = {"apple", "facebook", "microsoft", "google"};
    cout << v << endl;
    cout << v.value_type << endl;
    return 0;
}

A: In addition to the typeid-based answer, I see one further possibility using Boost like this:
#include <boost/type_index.hpp>

cout << boost::typeindex::type_id_with_cvr<decltype(v)::value_type>().pretty_name() << "\n";

The advantage is a portable, human-readable name that includes const/volatile qualifications and is consistent across major compilers and systems. The output on my machine is
// when compiled with gcc:
std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >
// ... and with clang:
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >

Decide for yourself whether this output qualifies as "human-readable", but also compare it to the typeid(...).name() approach, which on my machine gives:
NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE

A: X::value_type is no different from any other type alias (aka typedef) in this regard — C++ has no native way of converting a type to its source code string representation (not the least because that could be ambiguous). What you can do is use std::type_info::name:
cout << typeid(decltype(v)::value_type).name() << endl;

The resulting text is compiler dependent (and not even guaranteed to be easily human readable). It will be consistent within the same build of a program, but you cannot expect it to be the same across different compilers. In other words, it's useful for debugging, but cannot reliably be used in a persistent fashion.

A: It's probably safe to assume that you need this type info for debug purposes(?).
If it is, don't forget gdb's built in whatis and ptype commands:
$ cat main.cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<string> v = {"apple", "facebook", "microsoft", "google" };
    cout << v[2] << endl;
    // cout << v.value_type << endl;
    return 0;
}
$ cat gdbCommands.txt
break main
run
next
next
whatis v
quit
$ g++ -ggdb -o main main.cpp
$ gdb -x gdbCommands.txt ./main
GNU gdb (Ubuntu 8.0.1-0ubuntu1) 8.0.1
// bla bla bla ...
type = std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >>

A: I had a rather similar question some time ago. The answer there shown a function able to translate a type into a human readable string:
template <typename T> std::string TypeName() {
    auto name = typeid(T()).name();  // function type, not a constructor call!
    int status = 0;

    std::unique_ptr<char, void(*)(void*)> res {
        abi::__cxa_demangle(name, NULL, NULL, &status),
        std::free
    };

    std::string ret((status == 0) ? res.get() : name);
    if (ret.substr(ret.size() - 3) == " ()") ret.resize(ret.size() - 3);
    return ret;
}

Once you have this TypeName function you can achieve your goal:
int main() {
    vector<string> v = {"apple", "facebook", "microsoft", "google" };
    cout << v << endl;
    cout << TypeName<v.value_type>() << endl;
    return 0;
}

Which should output (GCC HEAD 9 201809):

std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >

A: If it's for debug purpose, then this solution would work without any dependencies:
#include <regex>

template <typename T>
struct TypeToNameT
{
    static std::string getTypeFromName() {
#ifdef _MSC_VER
        std::regex re("<(.*)>::.*");
        std::string templateType(__FUNCTION__);
#else
        std::regex re(" = (.*);");
        std::string templateType(__PRETTY_FUNCTION__);
#endif
        std::smatch match;
        try
        {
            if (std::regex_search(templateType, match, re) && match.size() > 1)
                return match.str(1);
        }
        catch (std::regex_error& e) {
            // Syntax error in the regular expression
        }
        return "";
    }
};
/** Get the templated type name. This does not depends on RTTI, but on the preprocessor, so it should be quite safe to use even on old compilers */
template <typename T>
std::string getTypeName() { return TypeToNameT<T>::getTypeFromName(); }

int main() {
    std::vector<std::string> v = {"apple", "facebook", "microsoft", "google" };
    std::cout << getTypeName<decltype(v)::value_type>() << std::endl;  // Returns: "std::__cxx11::basic_string<char>"
    return 0;
}

Unlike the typeid based answer, this use the preprocessor and as such is not subject to name mangling (so the name is... readable).
Please notice that you can't use v.value_type as a type directly, it's not part of the instance v but of the type of v: std::vector<std::string>
The regex part is because the std::string class is too dumb and you need such oddities for a simple search/split code. If you have a decent string class, you'll not need regex here for extracting the part that's after the "=" string and before the ";".


text:
Q: Flutter: http.post the object I am trying to send a http.post request with multiple variables.
var acc = {
    'acc_type': 'normal',
    'time': 'Jan 27',
  };

  var what = await http.post(
    'http://localhost:7200/api/activity/addactivity',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(
      <String, dynamic>{
        'userId': 'aaa111',
        'location': 'hellooooo',
        'acc': acc
      },
    ),
  );

When I remove acc: acc, Flutter sends requests. However, I need to send var acc value to the server in order to post it. I tried to encode it to JSON the http.post() function. It seems not working. How can I send the object as part of the post request?

A: This will work.
import 'dart:convert';

//....

var what = await http.post(
 'http://localhost:7200/api/activity/addactivity',
  headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
  },
  body: json.encode(
    <String, dynamic>{
      'userId': 'aaa111',
      'location': 'hellooooo',
      'acc': acc
    },
  ),
);

A: var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};

var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
  'Content-Type': 'application/json; charset=UTF-8',
},
body:(
  <String, dynamic>{
    'userId': 'aaa111',
    'location': 'hellooooo',
    'acc': acc.toString(),
  },
),
);


text:
Q: How to create model with its relationship using gorm Hi im trying to create an entity with a relationship at the same time during .Create. However the relationship is never created. Any ideas what im doing wrong?
type User struct {
    ID              uuid.UUID      `json:"id" gorm:"primaryKey:type:uuid"`
    Email           string         `json:"email"`
    CreatedAt       time.Time      `json:"created_at"`
    UpdatedAt       time.Time      `json:"updated_at"`
    DeletedAt       gorm.DeletedAt `json:"deleted_at"`
    Authentications []Authentication
}

type Authentication struct {
    ID        uuid.UUID `json:"id" gorm:"primaryKey:type:uuid"`
    Type      string    `json:"type"`
    ServiceId string    `json:"email"`
    SessionId string    `json:"sessionId"`
    Password  string
    CreatedAt time.Time      `json:"created_at"`
    UpdatedAt time.Time      `json:"updated_at"`
    DeletedAt gorm.DeletedAt `json:"deleted_at"`
    UserId    uuid.UUID
    User      User `gorm:"foreignKey:UserId"`
}

newUser := Models.User{Email: request.Email,
    Authentications: []Models.Authentication{
        {Type: "default", ServiceId: request.Email, Password: *hash}},
}

result := services.PSQLDB.Clauses(clause.Returning{}).Select("Email").Create(&user)

[21.318ms] [rows:1] INSERT INTO "users"
("email","created_at","updated_at") VALUES
('test@gmail.com','2022-08-01 13:55:02.903','2022-08-01 13:55:02.903')
RETURNING * 0xc0003df850 &{c606bf38-e6d3-4602-9beb-171d66cbdfde
test@gmail.com 2022-08-01 13:55:02.903 +0000 UTC 2022-08-01
13:55:02.903 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false}
[{00000000-0000-0000-0000-000000000000 default test@gmail.com
$2a$14$ahmcLBt5Iva2MmNeCm978.vxWXyYmw5DArcWn5J9QXxfd/TjWuW3q
0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC
{0001-01-01 00:00:00 +0000 UTC false}
00000000-0000-0000-0000-000000000000
{00000000-0000-0000-0000-000000000000  0001-01-01 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC {0001-01-01 00:00:00 +0000 UTC false}
[]}}]}


text:
Q: Import class problem in Eclipse I have 2 packages each in a different project , one package is called ch6 which includes class X , the other package is game which includes class Gamer , when trying to import game.Gamer manually in X I get error : "The import game cannot be resolved " , but when I hover on the red line of the error and choose "fix project setup.." , a dialog box appears offering importing the project of class game to the path of project of X and things are fixed, why can't I add the game.Gamer manually although I use the same syntax ?
* EDIT *
Including code as requested:
project ch6:
package ch6;

abstract public class X {
    private int x = 7;
    public static final int y = 24;
}

project HFJ:
package game;

public class Gamer {
    public int z;
}

A: If you have two Eclipse projects it should look something like:
[Project ch6]
  -java
  -Build Path
   ....
[Project game]
  -java
  -Build Path
  ...

To import cross project you want -> (you can get to the path a number of ways)
  [right click] ch6 -> Properties -> Build Path
  Projects Tab -> Check [game] || (add) Project [game];

Then do a clean build. That should resolve the import and combine the paths.
edit: reversed the order per Ed's suggestion.

A: I think you might see this if you didn't use the correct directory structure - if game.Gamer.java wasn't stored as /game/Gamer.java.
Also, if you haven't already, try refreshing the project (select the project in the tree, then menu File..Refresh.


text:
Q: Optimize if condition jQuery I have this condition written in code.
I am not sure if it can be shorten or optimized.
Also would like to know that this can be considered as ideal way to write an
if condition & check few things at once.
if(isMobile() && (jQuery("body").hasClass("catalog-category-view") || jQuery("body").hasClass("catalog-product-view") || jQuery("body").hasClass("wishlist-index-index")) && !jQuery('.prev_btn').length && !jQuery('.next_btn').length){

console.log('condition');

}

A: There's a couple of tweaks you can make to shorten this:

*

*Alias $ in the document.ready handler so you don't need to use jQuery everywhere.

*Use is() instead of hasClass(), as the former accepts multiple classes

*Combine .prev_btn and .next_btn in to a single jQuery object to check for length
jQuery($ => {
  if (isMobile() && $('body').is('.catalog-category-view, .catalog-product-view, .wishlist-index-index') && !$('.prev_btn, .next_btn').length) {
    // do something...
  }
});

A: You can optimize the with following approach, though you can short by assigning some if conditions in a variable.
  var $body = jQuery("body");// get body jquery element in variable
    //put OR conditions at the end as other condition can fail fast in the initial evaluation of if block
    if(isMobile() && !jQuery('.prev_btn').length && !jQuery('.next_btn').length &&
           ($body.hasClass("catalog-category-view")
           || $body.hasClass("catalog-product-view")
           || $body.hasClass("wishlist-index-index"))){

    console.log('condition');

    }

OR
    //put AND condition as first if block
    if(isMobile() && !jQuery('.prev_btn').length && !jQuery('.next_btn').length) {
     //put OR condition in second if block
     var $body = jQuery("body");// get body jquery element in variable
     if( $body.hasClass("catalog-category-view")
         || $body.hasClass("catalog-product-view")
         || $body.hasClass("wishlist-index-index")){

    console.log('condition');
    }
    }


text:
Q: Does a completed kubernetes pod still reserves the required resources? If I have a CronJob the has requests.memory of, let's say, 100Mi, when the pod finishes and enter on Completed state, does it still "reserves" that amount of memory, or are the requested resources freed up?
Both Jobs docs and Pod Lifecycle docs don't specify what happens after the pods in on Completed phase.

A: Nope, Kubernetes no more reserves memory or CPU once Pods are marked completed.
Providing you this example using a local minikube instance.
the Job manifest
apiVersion: batch/v1
kind: Job
metadata:
  creationTimestamp: null
  name: test-job
spec:
  template:
    metadata:
      creationTimestamp: null
    spec:
      containers:
      - command:
        - date
        image: busybox
        name: test-job
        resources:
          requests:
            memory: 200Mi
      restartPolicy: Never
status: {}

the Node describe output
# kubectl describe node|grep -i mem -C 5
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests     Limits
  --------           --------     ------
  cpu                755m (37%)   0 (0%)
  memory             190Mi (10%)  340Mi (19%)

Applying the job and then describing the node
# kubectl create -f job.yaml && kubectl describe node | grep -i mem -C 5
job.batch/test-job created
(...)
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests     Limits
  --------           --------     ------
  cpu                755m (37%)   0 (0%)
  memory             390Mi (22%)  340Mi (19%)

describe again the Node after the Job completion
# kubectl describe node | grep -i mem -C 5
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests     Limits
  --------           --------     ------
  cpu                755m (37%)   0 (0%)
  memory             190Mi (10%)  340Mi (19%)
  ephemeral-storage  0 (0%)       0 (0%)


text:
Q: Python plotly choropleth does not work with GeoJSONs I am trying to use plotly choropleth to draw the map, lets say for a random variable of num for each of the feature regions of the map in Italy. However, it does not work. below is the code that I use:
I have downloaded the GeoJSON files for Italy from here.
import random
import pandas as pd
import plotly.express as px
import plotly.io as pio
import json
pio.renderers.default='browser'

with open('it-all.geo.json') as f:
     geojson = json.load(f)

n_provinces = len(geojson['features'])

province_names = [geojson['features'][k]['properties']['name'] for k in range(n_provinces)]

randomlist = []
for i in range(0,110):
    n = random.randint(1,30)
    randomlist.append(n)

datadata = pd.DataFrame({'province':province_names, 'num':randomlist})

fig = px.choropleth(datadata, geojson=geojson, color="num",
                    locations="province", featureidkey="properties.name",
                    color_continuous_scale="Viridis")

fig.show()

What I am getting is a mixed shape map as below. Can anyone let me know what I am doing wrong?


text:
Q: Metal feedback loop artifacts Hi am trying to create some feedback loops in metal for an app I am working on. However I am getting some strange artifacts. I suspect this is due to something in my pipeline, or with how I am sampling the previous frame. In the code there are extra pipelines set up for a second buffer, as eventually I will need that to make a turing pattern. But right now I have reduced the code as much as possible to isolate the issue.
Right now it is just drawing a small circle in the top left corner. Once that is drawn the buffer A fragment samples itself with a one pixel displacement. This causes the circle to stretch out down the screen with every loop. The issue is that I am getting coloured lines appearing ahead of the stretching circle. This same artifact appears when I try and do recursive blurs or other types of feedback loops. The Main buffer is only there to mix the two buffers at the end of the process. I think it can be ignored for troubshooting this. Anyone run into this before?
Video here: https://photos.app.goo.gl/ThRJHddo2xKke6CN7
Screen shot here: Picture of artifact
Calls to metal controller in my viewController
 '''
 override func viewDidLoad() {

    super.viewDidLoad()

        metal.initMetalLayer(mView: metalView) // make metal layer
        metal.initMetalPipeline()//make metal pipeline
        metal.commandQueue = metal.device.makeCommandQueue()//make metal command Queue
        timer = CADisplayLink(target: self, selector: #selector(gameloop)) //make the timer to trigger the render call
        timer.add(to: RunLoop.main, forMode: .default)  //ties the screen refresh to the render call

    }

    @objc func gameloop() {
        autoreleasepool {
            metal.currentTime = Float(CACurrentMediaTime() - metal.startTime)
            //print(metal.currentTime)
                       // metal.bufferBRender()
                        metal.bufferARender()
                        metal.mainRender() //TURNS METAL RENDER OFF OR ON
        }

}

'''

Metal declarations
'''
//
//  MTL.swift
//  Habituate
//
//  Created by Brendan Tipney on 2021-01-14.
//

import Foundation
import Metal
import UIKit
import MetalKit

struct MTL {
    var device: MTLDevice!
    var metalLayer: CAMetalLayer!
    let vertexData: [Float] = [
        -1.0,  1.0, 0.0,
        1.0, 1.0, 0.0,
        -1.0, -1.0, 0.0,
        1.0,-1.0,0.0
        ]
    var vertexBuffer: MTLBuffer!
    var textureA: MTLTexture!
    var textureB: MTLTexture!

    //MARK: - AUX data
    var layoutData = simd_float4(390,727,0.75,1.0)
    var habitData = [vector_float4(0.25,1.0,0.75,1.0),vector_float4(0.1,1.0,0.3,0.4)]
    var touchData = vector_float4(0,0,0,0)
    var startTime = CACurrentMediaTime()
    var currentTime = Float(CACurrentMediaTime())

    //MARK: - RCTDIFData
    var RCTDIFData = vector_float4(0.055,0.064,2.0,1.0)

    var pipelineState: MTLRenderPipelineState! //DO I need more then one pipeline state?
    var pipelineStateB: MTLRenderPipelineState!
    var pipelineStateA: MTLRenderPipelineState!
    var commandQueue: MTLCommandQueue!
    var timer: CADisplayLink!

    mutating func initMetalLayer(mView : MTKView) {
        device = MTLCreateSystemDefaultDevice()
        metalLayer = CAMetalLayer()
        metalLayer.device = device
        metalLayer.pixelFormat = .bgra8Unorm
        metalLayer.framebufferOnly = false// Set to false as I intend to read from the frame buffer for feedback loops. Set to true if not needed
        metalLayer.frame = mView.layer.frame
        mView.layer.addSublayer(metalLayer)
        let viewSize = simd_float2(Float(mView.layer.frame.size.width), Float(mView.layer.frame.size.height))

        layoutData = simd_float4(viewSize.x, viewSize.y, 0.75, 1.0) //Trying to load the size data.
        print("view = \(viewSize)")

        let dataSize = vertexData.count * MemoryLayout.size(ofValue: vertexData[0])
        vertexBuffer = device.makeBuffer(bytes: vertexData, length: dataSize, options: []) //makes the buffer with the vertex data.
    }

    mutating func initMetalPipeline(){
        let defaultLibrary = device.makeDefaultLibrary()!
        let vertexProgram = defaultLibrary.makeFunction(name: "vertex_main")
        let fragmentProgram = defaultLibrary.makeFunction(name: "fragment_main")
        let fragmentProgramBuffA = defaultLibrary.makeFunction(name: "fragment_BuffA")
        let fragmentProgramBuffB = defaultLibrary.makeFunction(name: "fragment_BuffB")

        //MARK: - VertexDescriptor
        let vertexDescriptor = MTLVertexDescriptor()//I think this is where the buffers are stored
        vertexDescriptor.attributes[0].format = .float3
        vertexDescriptor.attributes[0].bufferIndex = 0
        vertexDescriptor.attributes[0].offset = 0
        vertexDescriptor.layouts[0].stride = MemoryLayout<float3>.stride

        //MARK: - Texture Descriptor
        let textureDescriptor = MTLTextureDescriptor() //None of this textureDescriptors may be needed
        textureDescriptor.textureType = MTLTextureType.type2D
        textureDescriptor.width = Int(layoutData.x)
        textureDescriptor.height = Int(layoutData.y)
        textureDescriptor.pixelFormat = MTLPixelFormat.bgra8Unorm
        textureDescriptor.usage = [.renderTarget, .shaderRead]
        textureA = device.makeTexture(descriptor: textureDescriptor)
        textureB = device.makeTexture(descriptor: textureDescriptor)

        //MARK: - Pipeline Descriptor
        let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
        pipelineStateDescriptor.vertexFunction = vertexProgram
        pipelineStateDescriptor.fragmentFunction = fragmentProgram
        pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
        pipelineStateDescriptor.vertexDescriptor = vertexDescriptor
        pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)

        //MARK: - BufferA Pipeline Descriptor
        pipelineStateDescriptor.fragmentFunction = fragmentProgramBuffA
        pipelineStateA = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)

        //MARK: - BufferB Pipeline Descriptor
        pipelineStateDescriptor.fragmentFunction = fragmentProgramBuffB
        pipelineStateB = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)

    }

        //MARK: - Main Render
    mutating func mainRender() {

            let commandBuffer = commandQueue.makeCommandBuffer()!

            guard let drawable = metalLayer?.nextDrawable() else { return }
            let renderPassDescriptor = MTLRenderPassDescriptor()
            renderPassDescriptor.colorAttachments[0].texture = drawable.texture
            renderPassDescriptor.colorAttachments[0].loadAction = .clear //PERHAPS SETTING THIS TO LOAD CAN MAKE A FB LOOP
            renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 0.0)

            let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)!
            renderEncoder.label = "Main"
            renderEncoder.setRenderPipelineState(pipelineState)
            renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)//this is where the vertex buffer is loaded

            renderEncoder.setFragmentTexture(textureA, index: 0)
            renderEncoder.setFragmentTexture(textureB, index: 1)

            renderEncoder.setFragmentBytes(&layoutData, length: MemoryLayout.size(ofValue: layoutData), index: 1) //this sends the dimentions to the shader
            renderEncoder.setFragmentBytes(&habitData, length: 4 * MemoryLayout.size(ofValue: habitData), index: 2)
            renderEncoder.setFragmentBytes(&touchData, length: MemoryLayout.size(ofValue: touchData), index: 3)

            renderEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: 1)
            renderEncoder.endEncoding()

            commandBuffer.present(drawable)
            commandBuffer.commit()
        }

    //MARK: - Buffer B Render
    mutating func bufferARender(){
        let commandBuffer = commandQueue.makeCommandBuffer()!

        let renderPassDescriptorA = MTLRenderPassDescriptor()
        renderPassDescriptorA.colorAttachments[0].texture = textureA //set back to this after testing
        renderPassDescriptorA.colorAttachments[0].loadAction = .load
        renderPassDescriptorA.colorAttachments[0].storeAction = .store
        renderPassDescriptorA.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)

        let renderEncoderA = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptorA)!
        renderEncoderA.label = "BufferA"
        renderEncoderA.setRenderPipelineState(pipelineStateA)
        renderEncoderA.setVertexBuffer(vertexBuffer, offset: 0, index: 0)//this is where the vertex buffer is loaded

        renderEncoderA.setFragmentTexture(textureA, index: 0)
        renderEncoderA.setFragmentTexture(textureB, index: 1)

        renderEncoderA.setFragmentBytes(&layoutData, length: MemoryLayout.size(ofValue: layoutData), index: 1) //this sends the dimentions to the shader
        renderEncoderA.setFragmentBytes(&habitData, length: 4 * MemoryLayout.size(ofValue: habitData), index: 2)
        renderEncoderA.setFragmentBytes(&touchData, length: MemoryLayout.size(ofValue: touchData), index: 3)
        renderEncoderA.setFragmentBytes(&RCTDIFData, length: MemoryLayout.size(ofValue: RCTDIFData), index: 4)
        renderEncoderA.setFragmentBytes(&currentTime, length: MemoryLayout.size(ofValue: currentTime), index: 5)

        renderEncoderA.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: 1)
        renderEncoderA.endEncoding()

        //commandBuffer.present(drawable)
        commandBuffer.commit()
    }

    mutating func bufferBRender(){
        let commandBuffer = commandQueue.makeCommandBuffer()!

        let renderPassDescriptorB = MTLRenderPassDescriptor()
        //renderPassDescriptorB.colorAttachments[0].texture = drawable.texture
        renderPassDescriptorB.colorAttachments[0].texture = textureB //set back to this after testing
        renderPassDescriptorB.colorAttachments[0].loadAction = .load
        renderPassDescriptorB.colorAttachments[0].storeAction = .store
        renderPassDescriptorB.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)

        let renderEncoderB = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptorB)!
        renderEncoderB.label = "BufferB"
        renderEncoderB.setRenderPipelineState(pipelineStateB)
        renderEncoderB.setVertexBuffer(vertexBuffer, offset: 0, index: 0)//this is where the vertex buffer is loaded

        renderEncoderB.setFragmentTexture(textureA, index: 0)
        renderEncoderB.setFragmentTexture(textureB, index: 1)

        renderEncoderB.setFragmentBytes(&layoutData, length: MemoryLayout.size(ofValue: layoutData), index: 1) //this sends the dimentions to the shader
        renderEncoderB.setFragmentBytes(&habitData, length: 4 * MemoryLayout.size(ofValue: habitData), index: 2)
        renderEncoderB.setFragmentBytes(&touchData, length: MemoryLayout.size(ofValue: touchData), index: 3)
        renderEncoderB.setFragmentBytes(&RCTDIFData, length: MemoryLayout.size(ofValue: RCTDIFData), index: 4)
        renderEncoderB.setFragmentBytes(&currentTime, length: MemoryLayout.size(ofValue: currentTime), index: 5)

        renderEncoderB.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: 1)
        renderEncoderB.endEncoding()

        //commandBuffer.present(drawable)
        commandBuffer.commit()
    }

    mutating func getDeviceDetails(){
        let window = UIApplication.shared.windows[0]
        let safeViewTop = window.safeAreaInsets.top
    }

    mutating func getHabitDetails(_ habits: HabitData){

    }

}

'''
Vertex and Fragment shaders
'''
#include <metal_stdlib>
using namespace metal;

struct VertexIn {
    float3 position [[attribute(0)]];
};

struct VertexOut {
    float4 position [[position]];
};

vertex VertexOut vertex_main(VertexIn in [[stage_in]],
                             const device packed_float3* vertex_array [[buffer(0)]],
                             unsigned int vid [[ vertex_id ]]) {
    VertexOut out;
    out.position = float4(vertex_array[vid].xy,1.0);
    //out.data = float4(in.data, 1);
    return out;
}

fragment float4 fragment_main( VertexOut in [[stage_in]],
                              constant float4 &layoutData [[ buffer(1) ]],
                              constant array<float4, 2> &habitData [[ buffer(2) ]],
                              constant float4 &touchData [[ buffer(3) ]],
                              texture2d<float, access::sample> BuffA [[ texture(0) ]],
                              texture2d<float, access::sample> BuffB [[ texture(1) ]]) {

    float4 fragIn = in.position;
    float2 uv = float2((fragIn.x/layoutData.x), (fragIn.y/layoutData.y));
    float4 fragColor = float4(0.0,0.0,0.0,1.0);

    constexpr sampler s(coord::normalized, filter::bicubic, address::clamp_to_edge,compare_func:: less);
    float4 texA = BuffA.sample(s, uv);

    fragColor = texA;
    fragColor.w = 1.0;

  return fragColor;
}

fragment float4 fragment_BuffA( VertexOut in [[stage_in]],
                              constant float4 &layoutData [[ buffer(1) ]],
                              constant array<float4, 2> &habitData [[ buffer(2) ]],
                              constant float4 &touchData [[ buffer(3) ]],
                              constant float4 &RCTDIFData [[ buffer(4) ]],
                              constant float &currentTime [[ buffer(5)]],
                              texture2d<float, access::sample> BuffA [[ texture(0) ]],
                              texture2d<float, access::sample> BuffB [[ texture(1) ]]) {

    float4 fragIn = in.position;
    float2 uv = float2((fragIn.x/layoutData.x), (fragIn.y/layoutData.y));//Need to load the screen size here or it will only look right on my phone.
    float2 pxlRatio = float2(1)/layoutData.xy;
    float4 fragColor = float4(0.0,0.0,0.0,1.0);
    constexpr sampler s(coord::normalized, filter::nearest, address::clamp_to_zero);

    float cornerCircle = step(distance(float2(0,0), uv),0.1);

    float4 texA = BuffA.sample(s, uv+float2(-1,-1)*pxlRatio);

    fragColor = float4(cornerCircle);
    fragColor += texA;

    fragColor.w = 1.;
  return fragColor;
}

'''

A: Seems like I was able to resolve the issue by adding .shadeWrite to my texture descriptor usage array.
'''textureDescriptor.usage = [.renderTarget, .shaderRead, .shaderWrite]'''


text:
Q: How can I disable or customize the image preview, which displays when a user hovers over an app's icon on the taskbar? In Windows with Aero... When the user hovers their mouse over the application's icon, a small preview of the app appears just above the taskbar. I'm looking for any information regarding how I can disable this preview or change/customize what appears in this little preview image box.
Note that I'm not looking to disable Aero features as a user - I'm looking to control this in-app.
Thank you in advance for answers!

A: Here is wrapper lib of the API, which controls these features in Windows - Jump Lists, Icon Overlay, Progress Bar, Tabbed Thumbnails, and Thumbnail Toolbars
http://archive.msdn.microsoft.com/WindowsAPICodePack


text:
Q: How do I insert a String variable into a file path? I want to be able to use a variable that can be changed within a file path. The username relevant to the file path is declared in the constructor then I have tried to assign this to the file path in the below method.
What I wanted to happen when calling:
System.out.format("%s%n", documentsPath.resolve(username +"\\Documents"));

Was that the documents Path would then be:
C:\Users\ryanb\Documents

Instead when I call documentsPath.toString() I only get returned:
C:\Users\

How do I get the documentsPath variable to be assigned with the String username and the "\\Documents" at the end.
This is my code:
 class profileCopy{

  /*global variables */
  private Path documentsPath;
  private Path desktopPath;
  private Path favoritesPath;
  private Path networkFolder;
  private String username;
  private String foldername;

  public profileCopy(String username, String foldername)
  {
    this.username = username;
    this.foldername = foldername;
    documentsPath = Paths.get("C:\\Users");
    desktopPath = Paths.get("C:\\Users");
    favoritesPath = Paths.get("C:\\Users");
    networkFolder = (Paths.get("F:\\Data\\WP51"));

  }

  public void copyDocumentsFolder() throws IOException
  {
    Path newDir = Paths.get("C:\\Users\\ryanb\\Documents\\TestCopy");
    System.out.format("%s%n", documentsPath.resolve(username +"\\Documents"));
    System.out.format("%s%n", networkFolder.resolve(foldername + "\\Backup"));
    System.out.println(networkFolder.getFileName());
    Files.move(documentsPath, networkFolder.resolve(documentsPath.getFileName()));
    System.out.println(newDir.toString());
  }

A: The main point in order to your code doesn't work is that you don't re-assign the return value of resolve() method to your path variable, since the method returns a new object.
In order to build your Paths, you can use something like this:
documentsPath = Paths.get(string.format("C:\\Users\\%s\\%s", username, "Documents");

If you want to reuse some code, you can use an array of folders and create them:
List<Path> paths = new ArrayList();
String[] defaultFolders = {"Documents", "Desktop", "Music"};
foreach (folder : defaultFolders) {
paths.add(Path.get(string.format("C:\\Users\\%s\\%s", username, folder)));

PS: Since you're developing that in java, you should consider to make the Path's UNIX or Windows Compatible, since UNIX environments doensn't recognize the "C:/Users" path.

A: The resolve methods returns a Path
public void copyDocumentsFolder() throws IOException
{
    Path newDir = Paths.get("C:\\Users\\ryanb\\Documents\\TestCopy");
    documentsPath = documentsPath.resolve(username + "\\Documents");
    networkFolder = networkFolder.resolve(foldername + "\\Backup");
    System.out.format("%s%n", documentsPath);
    System.out.format("%s%n", networkFolder);
    System.out.println(networkFolder.getFileName());
    Files.move(documentsPath, networkFolder.resolve(documentsPath.getFileName()));
    System.out.println(newDir.toString());
}