text:
Q: C# Error - Does not implement interface member I have an obfuscated code, written in C#, that I need to build and make an exe. However, I am getting error when build the project in VS 2012. The error says:
Error:

xf1555389a70c7d5a.x39b8e005139a3d89.xdd6080d77f5137d7' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'xf1555389a70c7d5a.x39b8e005139a3d89.xdd6080d77f5137d7.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.
File: x39b8e005139a3d89.cs

Here is xdd6080d77f5137d7.cs File obfuscated code:
public class xdd6080d77f5137d7 : IEnumerable<x39b8e005139a3d89.xe657754b6d8c9c0b>, IEnumerable, IComparable, x39b8e005139a3d89.xe657754b6d8c9c0b
    {
      private readonly LOG_CODES _x9035cf16181332fc;
      private readonly BOARDS _x337e217cb3ba0627;
      private readonly DeviceMode _xa4aa8b4150b11435;

  public LOG_CODES xdc1af3a17717bf0a
  {
    get
    {
      return this._x9035cf16181332fc;
    }
  }

  public BOARDS xaf77e81a71d6921f
  {
    get
    {
      return this._x337e217cb3ba0627;
    }
  }

  public DeviceMode xad98d2ceb0921f0a
  {
    get
    {
      return this._xa4aa8b4150b11435;
    }
  }

  public xdd6080d77f5137d7(LOG_CODES code, BOARDS source, DeviceMode mode)
  {
    this._x9035cf16181332fc = code;
    this._x337e217cb3ba0627 = source;
    this._xa4aa8b4150b11435 = mode;
  }

  public xdd6080d77f5137d7(LOG_CODES code, DeviceMode mode)
  {
    this._x9035cf16181332fc = code;
    this._x337e217cb3ba0627 = BOARDS.boardNULL;
    this._xa4aa8b4150b11435 = mode;
  }

  public xdd6080d77f5137d7(LOG_CODES code, BOARDS source)
  {
    this._x9035cf16181332fc = code;
    this._x337e217cb3ba0627 = source;
    this._xa4aa8b4150b11435 = DeviceMode.None;
  }

  public xdd6080d77f5137d7(LOG_CODES code)
  {
    this._x9035cf16181332fc = code;
    this._x337e217cb3ba0627 = BOARDS.boardNULL;
    this._xa4aa8b4150b11435 = DeviceMode.None;
  }

  public int CompareTo(object obj)
  {
    x7ba9346687691c4e.x4e846d09fe48634b(obj is x39b8e005139a3d89.xdd6080d77f5137d7, "Wrong data type");
    x39b8e005139a3d89.xe657754b6d8c9c0b xe657754b6d8c9c0b = (x39b8e005139a3d89.xe657754b6d8c9c0b) obj;
    if (this.xdc1af3a17717bf0a > xe657754b6d8c9c0b.xdc1af3a17717bf0a)
      return 1;
    if (this.xdc1af3a17717bf0a < xe657754b6d8c9c0b.xdc1af3a17717bf0a)
      return -1;
    if (this.xaf77e81a71d6921f > xe657754b6d8c9c0b.xaf77e81a71d6921f)
      return 1;
    if (this.xaf77e81a71d6921f < xe657754b6d8c9c0b.xaf77e81a71d6921f)
      return -1;
    if (this.xad98d2ceb0921f0a > xe657754b6d8c9c0b.xad98d2ceb0921f0a)
      return 1;
    return this.xad98d2ceb0921f0a < xe657754b6d8c9c0b.xad98d2ceb0921f0a ? -1 : 0;
  }

  public IEnumerator<x39b8e005139a3d89.xe657754b6d8c9c0b> GetEnumerator()
  {
    throw new Exception("The method or operation is not implemented.");
  }

  IEnumerator IEnumerable.x05b0b83b5e6c5de6() // Also, I am getting Error at this Line. The error is: 'IEnumerable.x05b0b83b5e6c5de6' in explicit interface declaration is not a member of interface.
  {
    throw new Exception("The method or operation is not implemented.");
  }
}

Please see that there are 2 Errors (First one is above File x39b8e005139a3d89.cs and other error is at the end of the xdd6080d77f5137d7.cs file. )

A: Obviously the name must be IEnumerable.GetEnumerator instead of IEnumerable.x05b0b83b5e6c5de6.
See: IEnumerable Interface


text:
Q: Powershell - Schedule a Task to run a PS script with parameters I'm trying to schedule a task that runs a PS script with parameters. But I believe I'm missing an escape character somewhere or my ' and " are in the wrong place. I can't seem to get it to work properly without it splitting the action argument. Below is my code:
    $employeeID = "1234"
    $employee = "email@email.com"
    $restoretime = (Get-date).AddHours(12)
    $restoreuser = "$($employee) Offboarding"
    $trigger = New-ScheduledTaskTrigger -once -At $restoretime
    $taskAction = New-ScheduledTaskAction -Execute    '%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe' -Argument `
    -Command "& 'C:\Location\testing.ps1' -employeeID '$($employeeID)' -employee '$($employee)'"
    Register-ScheduledTask -TaskName $restoreuser -Action $taskAction -Trigger $trigger

I get this result (see image)
Any help would be appreciated!
I've tried the approaches here with no luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to do specific table in bookdown with kableExtra I trying to use kableExtra in RMarkown for a text table as the following example:
text_tbl <- data.frame(
  Items = c("Item 1", "Item 2", "Item 3"),
  Features = c(
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin vehicula tempor ex. Morbi malesuada sagittis turpis, at venenatis nisl luctus a. ",
    "In eu urna at magna luctus rhoncus quis in nisl. Fusce in velit varius, posuere risus et, cursus augue. Duis eleifend aliquam ante, a aliquet ex tincidunt in. ",
    "Vivamus venenatis egestas eros ut tempus. Vivamus id est nisi. Aliquam molestie erat et sollicitudin venenatis. In ac lacus at velit scelerisque mattis. "
  )
)
kbl(text_tbl, booktabs = T) %>%
  kable_styling(full_width = F) %>%
  column_spec(1, bold = T, color = "red") %>%
  column_spec(2, width = "30em")

However I would to change the text of the table by adding operators in one column and the example with some explanation in another, exactly to this site: https://www.tutorialspoint.com/r/r_operators.htm.
I produced this following code, with some variations, but not worked.
text_tbl <- data.frame(
  Items = c(" <- ", " %in% "),
  Features = c(
    " Here it's an example: $x <- 3$",
    " Here it's an example: $c(1, 1, 1, 2, 5, 8, 10) %in% 1$ "
  )
)
kbl(text_tbl, booktabs = T) %>%
  kable_styling(full_width = F) %>%
  column_spec(1, bold = T, color = "red") %>%
  column_spec(2, width = "30em")

Trying to be more specific I would to know:
1 - How can I add operators in a data frame that I will used in a table created by kable()?
2 - How can I add a code in a data frame that I will run out inside a table created by kable()?
Both questions I would to execute in rmarkdown.
Thank you

A: Maybe this could help you:
---
title: "Untitled"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)
```

```{r}
text_tbl <- data.frame(
  Items = c(" $<-$ ", " $$\\%$$in$$\\%$$ "),
  Features = c(
    " Here it's an example: $x <- 3$",
    " Here it's an example: $c(1, 1, 1, 2, 5, 8, 10) $$\\%$$in$$\\%$$ 1$ "
  )
)
kbl(text_tbl, booktabs = T, escape = F) %>%
  kable_styling(full_width = F) %>%
  column_spec(1, bold = T, color = "red") %>%
  column_spec(2, width = "30em")
```

1 - escape = F was added to the function kbl
2 - To insert %, you need this: $$\\%$$


text:
Q: gulp ignore doesn't remove first slash I am creating Gulp task that will inject js and css using wiredep. below is how it is getting injected.
<!-- bower:js -->
<script src="../bower_components/jquery/dist/jquery.js"></script>

<!-- inject:js -->
<script src="/public/js/config/app.js"></script>
<script src="/public/js/components/home-component.js"></script>

but I need to inject
<!-- bower:js -->
<script src="bower_components/jquery/dist/jquery.js"></script>

<!-- inject:js -->
<script src="public/js/config/app.js"></script>
<script src="public/js/components/home-component.js"></script>

I managed to replace ../ to ``
How do I Ignore first '/'?
This is what I have tried and didn't work.
Gulp task is below
gulp.task('index', function () {
    var target = gulp.src('./public/index.html');
    var sources = gulp.src(config.appjs.concat(config.appcss), {read: false});

    return target.pipe(inject(sources))
        .pipe(wiredep({
            ignorePath: "../"
        }))
        // .pipe(wiredep({
        //     ignorePath: "/"
        // }))
        // .pipe(wiredep({
        //     ignorePath: "/(.*?)\\/"
        // }))

        // .pipe(wiredep(
        //     {
        //         fileTypes: {
        //             html: {
        //                 replace: {
        //                     js: '<script src="{{filePath}}"></script>',
        //                     css: '<link rel="stylesheet" href="{{filePath}}">'
        //                 }
        //             }
        //         }
        //     }))

        .pipe(gulp.dest('./dev'))
        .pipe(browserSync.stream());
});

and
gulp.task('js', function () {
    return gulp.src('./public/js/**/*.js')
            .pipe(wiredep({
                ignorePath: '/',
                addRootSlash: false
            }))
        .pipe(gulp.dest('./dev/public/js'));
});


text:
Q: python:compare values with other values in dictionary As per this link
now i have to Randomly choose state as question and compare the answer with capital, if user provides right answer loop must exit.
I have a dictionary with
{'state': ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California'],
 'capital': ['Montgomery', 'Juneau', 'Phoenix', 'Little Rock']}

A: something like this might work (not tested), assumes that states and capitals are 1 to 1 and in the right order
import random
random_state = random.choice(your_dict.get('state')
index = your_dict.get('state').index(random_state)
answer = your_get_answer_method() #returns the answer, process if needed (lower ... etc)
if your_dict.get('capital')[index] == answer:
    #do some stuff here


text:
Q: Measuring performance difference between Merge and Append in ArcGIS Desktop? Often I find myself in a situation where I don't care whether or not my tool produces a new feature class, but I do care how long it takes to combine all of my large datasets. Does it take longer to produce a new feature class using the Merge tool instead of the Append tool, or are Merge and Append essentially the same in terms of performance?

A: Take this answers based on the tools themselves and not an actual benchmark:
The merge tool creates a new feature class, which takes time in itself, before it crams together the two datasets.
The append tool with the TEST option assumes that both datasets have the same fields (field names) and crams them together without having to create a new feature class (sounds faster).
The append tool with the NO TEST option allows for field mapping to combine like feature classes that may have different field names.  This requires some behind the scenes conditional testing, which would take more time.
As the size of the dataset grows, the amount of time it takes to create a new fc seems insignificant.  The only way to know for sure would be to do some benchmarks with your large datasets and post the answers here!
I suspect the difference isn't much it's more about what you want out of the tool in the end (field mapping vs. new feature class vs. no new feature class)

A: Merge takes both geometry and attributes and combines (merges) the entire dataset into a new feature dataset.

Append is good way to join extra data to an existing dataset - it can have options to control subtypes of features being appended.
http://resources.arcgis.com/en/help/main/10.1/index.html#//001700000055000000
The key difference is
If the Schema Type TEST is specified, the schema (field definitions) of the input datasets must match that of the target dataset in order for the features to be appended. If the Schema Type NO_TEST is specified, input dataset schema (field definitions) do not have to match the target dataset. However, any fields from the input datasets that do not match the fields of the target dataset will not be mapped to the target dataset unless the mapping is explicitly set in the Field Map control.
subtype
(Optional)
A subtype description to assign that subtype to all new data that is appended to the target dataset.
http://resources.arcgis.com/en/help/main/10.1/index.html#//001700000050000000

You might be interested in the 'Tiled processing of large datasets'
http://resources.arcgis.com/en/help/main/10.1/index.html#//01m10000000r000000

A: I just ran all three variants. I always combined the same 63 shapefiles. Each shapefile contains around 63000 points created from a RasterToPoint operation. All shapefiles have the same attribute table.
The different variants needed the following times to compile:

*

*Merge: 13 mins 57 secs

*Append with TEST: 8 mins 34 secs

*Append with NO_TEST: 9 mins 12 secs

Seems like Append with TEST as an input parameter is the fastest one. Obviously the choice of which Append to use depends not on speed but rather on your input files as explained above.
Hope it is useful.


text:
Q: degree symbol in plot R with ggplot2 using RStudio I have this code and I'm using RStudio
library(tidyverse)
library(osmdata)
bbx <- getbb("hawaii")

border <- bbx %>%
  opq() %>%
  add_osm_feature(key = "place",
                  value = c("island")) %>%
  osmdata_sf()

border

ggplot() +
  geom_sf(
    data = border$osm_lines,
    inherit.aes = FALSE,
    color = "black",
    size = .4,
    alpha = .8
  )

when I plot this I have this

As you can see instead of the degree symbol I have a white rectangle in labels.
How can I solve this problem?
Thanks in advance
P.S.: I'm using Window11 64bit and RStudio updated with default options and all packages updated.

A: Following @tjebo I did two tests:

*

*I change the Graphics Device option to CAIRO ( Tools -> General -> Graphics -> Backend)

and it worked

*I downgrade R to R4.2.1

and that worked too.
Thank you so much tjebo

A: The problem occurs at two points. First when you plot in console and second when you export using ggsave. I am providing solution for both and it is quite simple.

*

*For in console plot: Change the graphics to cairo  (Tools -> General -> Graphics -> Backend > Cairo

*While exporting the image with ggsave use the value (type = "cairo"). Example
ggsave("img.png", height = 18, width = 30, units = 'in', dpi= 200, type = "cairo")

This worked for me. Hope this helps.

A: The problem you are encountering with the white rectangle appears to be related to a character encoding issue, specifically with the degree symbol (°). It seems that the degree symbol is not being properly rendered in your plot.
There are a few things you can try to resolve this issue:

*

*Make sure that your system and RStudio are using the correct
character encoding. In RStudio, you can check the character encoding
by going to the menu "Tools > Global Options > Code > Saving", and
looking at the "Default text encoding" setting. If it is set to
something other than "UTF-8", you can try changing it to "UTF-8" and
see if that fixes the problem.

*If changing the character encoding does not work, you can try using
a different font that includes the degree symbol. You can do this by
specifying the font argument in the geom_sf() function. For example:
ggplot() + geom_sf(data = border$osm_lines,inherit.aes = FALSE,color = "black",size = .4,alpha = .8,font = "Arial")
You can try using different fonts to see if any of them work for you. Some fonts that are known to include the degree symbol and work well with ggplot2 include "Arial", "DejaVu Sans", and "Lato".


text:
Q: PHP WebSocket Chat: private conversation I tried that code: http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/
and it works very fine. But that's not really what I looked for.
That code creates a "room", with only one "instance" of websocket. I would like to have as much instances as "one-to-one conversations" like FB.
Someone has any idea how to make privates conversations websocket's chat?
tl;dr: if there are 3 conversations (6 people), I would like to create automatically 3 "rooms".
Thank you so much.
Regards

A: This could still be handled by one websocket server instance. You'll just have to store for each user1 the corresponding user2. Everytime user1 sends a message it will be forwarded only to user2 and vice versa. To avoid redundant data, you should store the relation between user1 and user2 only once, of course.


text:
Q: How to iterate through ul elements within a div and hide them individually on a submit? In my node app using express I have a view function that creates a list of inactive companies, each company has two submit input types "Active" and "Delete". I would like to be able to hit submit and have that individual ul become hidden. However, I'm not quite sure how to iterate over  individually. Every time I've tried I end up hiding all the elements. Here's my view function:
function inactiveFiltered(companyObject) {
    return `

${companyObject.company_type}

${companyObject.company_name}

${companyObject.company_location}

${companyObject.company_phone}

                <form action="/activeList" method="POST" class="myform">
                    <input type="hidden" name="companyId" value="${companyObject.id}">
                    <input type="submit" value="Active">
                </form>
                <form action="/deletecompany" method="POST">
                    <input type="hidden" name="companyId" value="${companyObject.id}">
                    <input type="submit" value="Delete">
                </form>

    `
}

function inactiveList(arrayOfCompanies){
    const companyItems = arrayOfCompanies.map(inactiveFiltered).join('');

    return `

            ${companyItems}

    `
}

module.exports = inactiveList;

One function takes an array of companies and then creates an company object. Now here's the latest JQuery attempt, but like I said it hides all the ul elements:
                $(document.body).submit(function() {
                    $('.companyinfo').each(function(i) {
                        $(this).hide();
                    })
                })

I've been stuck on this for waaay too long and would love any help whatsoever. Thank you!

A: You are hiding all elements at the same time because the selector .companyinfo returns a list of all elements using the class companyinfo which are all companies in your case. That's why they get hidden all at the same time
One way to achieve your goal is to add ids to the ul elements to be able to address them for each company individually like so:
.
Then add a method hideCompany() to replace the $(document.body).submit(function() part:
function hideCompany(companyname) {
    $('#companyinfo_' + companyname).hide();
}

Finally, modify <input type="submit" value="Delete">to read <input type="submit" value="Delete" onclick="hideCompany('${companyObject.company_name}')">.


text:
Q: Artifactory - hide the "last downloaded" info We are using the Artifactory tool to distribute gradle files and other artifacts to customers, secured by a per customer login.
However, if those customers get Webapp access (which they need to for example change their passwords) they can see all repositories and artifacts they have (read) access to, including WHO last downloaded the file.
Is there any way of changing this, besides building our own password change site?

A: Right now there is no way to remove the "Last Downloaded" information from the JFrog Artifactory screen. If that is a requirement you have, you can always reach out to the JFrog support team to have them log an enhancement request.
As an alternative, if you really want to use Artifactory for this use case, you might want to consider giving each customer their own repository and only giving them access to that repo. Artifactory stores files only once. The first time a file is uploaded, Artifactory calculates a checksum and stores the file accordingly (including putting a record in a database). If files are uploaded again, or copied to multiple destinations, only the database is updated to create a record mapping the file's checksum to its new location as well. On the positive side, you've got the artifacts stored once and your customers only see their own repo. On the down side, you'll end up with many more repos in Artifactory.


text:
Q: Suitable data structure for Java 1000*1000 matrix. I am practising java programming. I encountered a problem which requires 1000 x 1000 matrix which stores integers value less than 1500
I would want to navigate across all the elements
I might need to fetch max element and its 4 adjacent elements.
What is the best data structure which doesn't affect performance?
1  2  3  4
5  6  7  8
9  10 11 12
12 14 15 16

for the element 11 --> 7, 10, 12, 15 are adjacent elements.

A: what is wrong with the 2d array data structure?
to get an adjecent of a number at i,j return [i-1][j],[i+1][j],[i][j+1],i[j-1] (you will have to deal with cases where i is zero etc)...
as performance goes, its O(1), doesn't get any better than that...
If you are talking about finding the location of the element. if the matrix is sorted you can simply do a binary search.

A: A 2dim Array of shorts:
-> short [][] matrix = new short[1000][1000];
|  Added variable matrix of type short[][] with initial value [[S@1794d431

Generate in a second, few MB in size. What could be better than that?


text:
Q: How can i remove the empty spaces from a web page that i scrape? I am scraping a site with python3 using beautiful Soup.
I store my data into a list.
I manage to extract the info that i want
import requests
from bs4 import BeautifulSoup

source = requests.get('my site').text
soup = BeautifulSoup(source, 'lxml')

lista = []

rows = soup.find('table', class_='exchange-rates-table not-
responsive').find_all('tr')

for row in rows:          # Print all occurrences
    l.ista.append(row.contents[3].get_text())
print(lista)

This is the output:

['Cod', '\n\n                        EUR\n\n                    ',
'\n\n                        USD\n\n                    ', '\n\n
GBP\n\n                    ', '\n\n                        CHF\n\n
', '\n\n                        AUD\n\n                    ', '\n\n
DKK\n\n                    ', '\n\n                        HUF\n\n
', '\n\n                        JPY\n\n                    ', '\n\n
NOK\n\n                    ', '\n\n                        SEK\n\n
']

When i run this code i am receiving the info that i want, but with a lot of empty spaces with comma between them and the sign of new line.
So how can i remove them to get only what i want.

A: Since your data is already in a list, you can do with strip in a list comprehension:
[x.strip() for x in ['Cod', '\n\n EUR\n\n ', '\n\n USD\n\n ', '\n\n GBP\n\n ', '\n\n CHF\n\n ', '\n\n AUD\n\n ', '\n\n DKK\n\n ', '\n\n HUF\n\n ', '\n\n JPY\n\n ', '\n\n NOK\n\n ', '\n\n SEK\n\n ']]


text:
Q: uWSGI raises OSError: write error during large request My application uses nginx, with uWSGI on the server side. When I do a large request (with a response time > 4s), the following appears:
SIGPIPE: writing to a closed pipe/socket/fd (probably the client
    disconnected) on request _URL_ (ip XX.XX.XX.XX) !!!

uwsgi_response_writev_headers_and_body_do(): Broken pipe
    [core/writer.c line 287] during GET _URL_ (XX.XX.XX.XX)

OSError: write error

It seems that uWSGI tries to write in a stream but this stream has already been closed.
When I check nginx log (error.log):
upstream prematurely closed connection while reading response
    header from upstream ...

Of course, my client (REST client or browser) receives a 502 error.
I always get this error after ~4s.
However, I don't know how to prevent this issue.
I tried to set some parameters in my nginx config file:
location my_api_url {
    [...]
    uwsgi_buffer_size 32k;
    uwsgi_buffers 8 32k;
    uwsgi_busy_buffers_size 32k;

    uwsgi_read_timeout 300;
    uwsgi_send_timeout 300;

    uwsgi_connect_timeout 60;
}

But the issue is still here.
I also tried to set these parameters in the uWSGI configuration file (wsgi.ini):
buffer-size=8192
ignore-sigpipe=true
ignore-write-errors=true

Before to try to optimize the response time, I hope this issue has a solution. I don't find one that's working in another post. I work with a large amount of data, so my response time, for some case, will be between 4-10s.
Hope you can help me :)
Thanks a lot in advance.

A: It may be the case that when you upload things, you use chunked encoding.
There is uWSGI option
--chunked-input-timeout,
that by default is 4 seconds (it defaults
to value of --socket-timeout, which is 4 seconds).
Though problem theoretically may lie somewhere else, I suggest you to try
aforementioned options. Plus, annoying exceptions are the reason why I have
ignore-sigpipe=true
ignore-write-errors=true
disable-write-exception=true

in my uWSGI config (note that I provide 3 options, not 2):

*

*ignore-sigpipe makes uWSGI not show SIGPIPE errors;

*ignore-write-errors makes it not show errors with
e.g. uwsgi_response_writev_headers_and_body_do;

*disable-write-exception prevents
OSError generation on writes.

A: In my case, Nginx as a backproxy of uwsgi, the config http-timeout set the server to normally wait in long running requests.
Mind that the following options included in the nginx proxy declaration:
proxy_read_timeout 300s;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;

were doing nothing regarding the gateway timeout.

A: I added [socked-timeout=xxx] in my uwsgi.ini config, it worked.


text:
Q: PHPQuery - get all links of contains specific url page I am trying to get all links of contains specific url page on a given page using PHPQuery. I am using the PHP support syntax of PHPQuery.
include_once 'phpQuery.php';
$url = 'http://www.phonearena.com/phones/manufacturer/';
$doc = phpQuery::newDocumentFile($url);

$urls = $doc['a'];

foreach ($urls as $url) {
    echo pq($url)->attr('href') . '
';
}

The code above works . But it shows all the links
I want to show only those containing "/phones/manufacturer/".
I tried this but it shows nothing:
include_once 'phpQuery.php';
$url = 'http://www.phonearena.com/phones/manufacturer/';
$doc = phpQuery::newDocumentFile($url);

$urls = $doc['a'];

foreach ($urls as $url) {
    echo pq($url)->attr('href:contains("/phones/manufacturer/")') . '
';
}

A: Use below coding get all urls from that site,
        $doc = new DOMDocument();
                @$doc->loadHTML(file_get_contents('http://www.phonearena.com/phones/manufacturer/'));

                $ahreftags = $doc->getElementsByTagName('a');

                    foreach ($ahreftags as $tag) {
                        echo "
";
                        echo $tag->getAttribute('href');
                        echo "
";
                    }

exit;

A: Try this, a little italian guide, jquery documentation
include_once 'phpQuery.php';
$url = 'http://www.phonearena.com/phones/manufacturer/';
$doc = phpQuery::newDocumentFile($url);

$urls = $doc['a[href*="/phones/manufacturer/"]'];

foreach ($urls as $url) {
    echo pq($url)->attr('href') . '
';
}


text:
Q: Automatic testing for Microsoft Bot I am using the Microsoft Bot Framework to create a bot in NodeJs.
I manually tested the bot with the Bot Emulator, but I'm looking for the best method to automate testing for the bot.
Does Microsoft provide any tool for automatically running test or are there any other methods which can support the bot to be test automatically?
Can anyone help me out with this?

A: Here's a handy link if you're looking for Node: https://github.com/microsoftly/BotTester

A: Not sure how much useful this will be for you, but if you can use MS Test framework, have a look at this URL.

A: You could have a look at https://github.com/jvanderbiest/directline-jabber

DirectLine-Jabber focusses on automated integration testing for the
  Microsoft BotFramework. Using your BotFramework emulator transcript
  files it will check if your bot responds as it is supposed to respond.

You can use the emulator to create a chat conversation, then save the transcript, deploy your bot and replay it to your deployed bot instance.


text:
Q: Using buffer for read and read operations examples in Go my os background is not strong, could someone provide some examples (in Go please if possible), why using buffer is important?

A: Assuming you're talking about IO:
Imagine you have a var fin *os.File and that file wrapped in a buffer, var instrm *bufio.Reader. Now imagine you are writing some kind of parser that reads the input one character (lets say byte) at a time. Package bufio implements buffered I/O.
If you call myParser.Parse(fin) you will call .Read 4,194,304 times to read each byte, which will make a system call 4,194,304 times, which will cause 4,194,304 context switches. context switches are when control transfers from the userspace program to the OS and are one of the slowest (non-IO) operations. In situations where the OS is not coalescing/prefetching IO requests there is also the horrible possibility your IO device is seeking and reading one byte at a time, but most operating system's IO elevator, prefetching and device-side buffers prevent this nowadays (but it is always better to read in large sequential batches).
If you call myParser.Parse(instrm) with the default bufio.Reader buffer being 4K you will cause 1,024 context switches (each system call reads 4K rather than 1 byte). Since each system call has some overhead, this will mean less time is spent making system calls and more time for your program to run. It is also worth pointing out that running this way (without the extra context switches) will often increase the CPU instruction cache hit rate since more time will be spent branching within a smaller region of memory.
Buffers are even important in areas like network IO as it will allow you to send bursts of packets at the maximum MTU size rather than sending a trickle of tiny packets.
Just don't forget to flush your write buffers.


text:
Q: Windows-7 Pro Remote Desktop stopped going full screen Was working perfect; remote desktop of laptop filled entire screen of workstation's 2nd monitor.
But now it's just a scrolling window that fills only 2/3.
Workstation: 2013 DELL OPTIPLEX 9010 Windows-7 Pro with (2) Samsung SyncMaster SA850T 27" monitors: #1 at 2560 x 1440 vertical, and #2 at 1440 x 2560 horizontal (the one for the remote desktop session to laptop)
Laptop: 2013 DELL Precision M4800 with Win-7 Pro.
I've tried

A: Wow, I solved it while writing this question...
SOLUTION:
Edit .rdp REMOTE DESKTOP config file at workstation with changes:

Display tab:  Large, uncheck "Use all..", Colors Highest
  Experience tab:  LAN
  General tab:   SAVE
  Hit Connect button

2nd monitor now shows remote desktop session at 2560 x 1440.  Ha cha!!
NOTE: Laptop local resolution was 1600 x 900.


text:
Q: prevent java from multiple openings of the same window-JFrame for example i create this on click
//this creates autor object with default constructor properties defined in autor class
menuAutor.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent e)
            {
                autor Autor = new autor("Autor");
            }
        });

so object named Autor is created, and when i click again on the button, it pops up again the same Autor object.. how can prevent opening the same window if one is already opened?
EDIT: FINALY A SOLUTION!
After lots of thinking about this.. i made my solution...
default value for autorOpen="no" i declaired at the beginning of my class, just to let you know because its not visible in code below, the solution itself:
public void mouseClicked(MouseEvent e)
            {
                if(autorOpen=="no") {
                autor Autor = new autor("Autor");
                autorOpen = "yes";
                Autor.addWindowListener(new WindowAdapter(){
                    public void windowClosing(WindowEvent e)
                    {
                        autorOpen = "no";
                    }
                });
                }
                else
                    JOptionPane.showMessageDialog(null, "Demo notice... you can't open that window again.. its opened already!","Error",JOptionPane.ERROR_MESSAGE);
            }
        });

A: Store the variable a little bit more globally, and check whether it exists before creating a new one.

A: You could also consider implementing Autor as a singleton class (to ensure only one is ever instantiated).
public class Autor {

private static Autor instance = null;

//Must be protected or private, get a reference to this class with getInstance().
protected Autor() {
}

/**
* Returns reference to this class - use in place of constructor
*/
public static Autor getInstance() {
if(instance == null) {
instance = new Autor();
}
return instance;
}
}

A: Use a boolean flag to indicate if the dialog is up or not. Set it to true if the dialog is popped up, and set it to false when you close that dialog.

A: If you're creating something with 'new' on each click, you'll get a new window each time.  One solution is to create autor before any clicks happen, then have the event move it from hidden to visible.


text:
Q: Want to use multiple |window on a single stream with kapacitor Goal: I would like a notification 5 minutes after an alert condition and then every 30 minutes thereafter.
I played around with .count() and the time function but that went nowhere, I didn't want to have to calculate that mess out and I couldn't figure out a way to make it user friendly and reliable.
The solution I am working with now is to have two streams with separate windows.
var initialData = stream
        |from()
            .database(db)
            .measurement(metricType)
            .retentionPolicy(rPolicy)
            .groupBy(group)
            .where(lambda: "cpu" == 'cpu-total')
            .where(lambda: "host" =~ hostFilter)
        |mean(metric)
            .as('initialStat')
        |window()
            .period(10m)
            .every(5m)
            .align()

var continuousData = stream
    |from()
        .database(db)
        .measurement(metricType)
        .retentionPolicy(rPolicy)
        .groupBy(group)
        .where(lambda: metricType == 'cpu-total')
        .where(lambda: "host" =~ hostFilter)
    |mean(metric)
        .as('continuousStat')
    |window()
        .period(10m)
        .every(30)
        .align()

Beyond the fact this just seems odd, I would then need to calculate out the values for each and I also need separate |alert() nodes. The first node will only notify on state change, but the second node can't have this so I get an alert reminder every N minutes. I also have the problem that the first |alert() node will send out the OK notification and the second will also send out a dupe OK N minutes later.
I feel there has to be a better way of doing this. I am thinking I may be able to use an if statement in the second |alert() node to not send out a notification on OK as the first |window will handle that. At this point I haven't yet figured out how to even do this but I am sure it is possible. I also don't want to fight tickscript, I know it is not designed to be a full blown language per Issue 741
The full tickscript is below
// CONFIGURATION PARAMETERS

// Alerting

var emailAddress = '$EMAIL'
var pagerdutyKey = '$PD'
var slackChannel = '$SLACK'

// Static Thresholds in percent cpu steal used
var warn = 85
var crit = 95

// Dynamic thresholds in number of std deviations
var warnSig = 2.5
var critSig = 3.5

// Print INFO level (every result will be an alert)
// AlertNode.StateChangesOnly will also need to be disabled
// NOTE:
// INFO level alerts will be disregarded by the pagerduty handler, this is not configurable.
var debug = FALSE

// Datastream
// Define the data that will be acted upon
var db           = 'telegraf'
var group        = 'host'
var metricType   = 'cpu'
var metric       = 'time_steal'
var rPolicy      = 'default'

// Regex used to filter on a subset of hosts
var hostFilter = /.+/

// Window
var dataPeriod            = 10m
var initialFrequency      = 5m
var continuousFrequency   = 30m

// DATAFRAME
var initialData = stream
    |from()
        .database(db)
        .measurement(metricType)
        .retentionPolicy(rPolicy)
        .groupBy(group)
        .where(lambda: metricType == 'cpu-total')
        .where(lambda: "host" =~ hostFilter)
    |mean(metric)
        .as('initialStat')
    |window()
        .period(dataPeriod)
        .every(initialFrequency)
        .align()

var continuousData = stream
    |from()
        .database(db)
        .measurement(metricType)
        .retentionPolicy(rPolicy)
        .groupBy(group)
        .where(lambda: metricType == 'cpu-total')
        .where(lambda: "host" =~ hostFilter)
    |mean(metric)
        .as('continuousStat')
    |window()
        .period(dataPeriod)
        .every(continuousFrequency)
        .align()

// Calculations
var initialCalculation = initialData
    |eval(lambda: sigma("initialStat"))
        .as('intialSigma')
        .keep()

var continuousCalculation = continuousData
    |eval(lambda: sigma("continuousStat"))
        .as('continuousSigma')
        .keep()

// ALERT CONDITIONS
var initialCondition = initialCalculation
    |alert()
        .id('{{ index .Tags "host"  }}')
        .message('{{ .ID  }} is {{ .Level  }}: CPU STEAL USAGE {{ index .Fields "initialStat" }}% SHORT')
        .details('this is an alert')
        .stateChangesOnly()
        .info(lambda: debug)
        .warn(lambda: "stat" < warn OR
            "sigma" > warnSig)
        .crit(lambda: "stat" < crit OR
            "sigma" > critSig)

var continuousCondition = continuousCalculation
    |alert()
        .id('{{ index .Tags "host"  }}')
        .message('{{ .ID  }} is {{ .Level  }}: CPU STEAL USAGE {{ index .Fields "continuousStat" }}% LONG')
        .details('this is an alert')
        .info(lambda: debug)
        .warn(lambda: "stat" < warn OR
            "sigma" > warnSig)
        .crit(lambda: "stat" < crit OR
            "sigma" > critSig)

// ACTIONS
continuousCondition
        // .log('/tmp/alerts/cpu_steal_usage_alerts')
        // .slack()
        // .channel(slackChannel)
        .email(emailAddress)
        .pagerDuty()
                .serviceKey(pagerdutyKey)

initialCondition
        // .log('/tmp/alerts/cpu_steal_usage_alerts')
        // .slack()
        // .channel(slackChannel)
        .email(emailAddress)
        .pagerDuty()
                .serviceKey(pagerdutyKey)

A: So apparently I can do multiple windows in a single stream node.
stream
    |from()
        .database(db)
        .measurement(metricType)
        .retentionPolicy(rPolicy)
        .groupBy(group)
        .where(lambda: metricType == metricFilter)
        .where(lambda: "host" =~ hostFilter)
    |window()
        .period(dataPeriod)
        .every(initialFrequency)
        .align()
    |mean(metric)
        .as('initialStat')
    |window()
        .period(dataPeriod)
        .every(continuousFrequency)
        .align()
    |mean(metric)
        .as('continuousStat')

Still working through the OK issue though.


text:
Q: FastCGI: manager (pid YYYYY): server (pid XXXX) exited with status 13 FastCGI: manager (pid 6776): server (pid 20254) exited with status 13
FastCGI: manager (pid 6776): server (pid 18918) started FastCGI:
server (pid 18918): initialized

I am getting above mentioned error on my catalyst based application running under Apache based FASTCGI server. Due to above error it is showing me "Internal Server Error" and in next subsequent call it start running normally.
I could not able to understand the behaviour.
Regards,
Hardik


text:
Q: Can the solutions to a homogeneous second order differential equation be a function and its inverse? Is there an equation of the form $y''+p(x)y'+q(x)y= 0$, such that the two solutions $y_1$ and $y_2$ are inverses? I did the following work, where I made the assumption that $p(x) = 0$ and $y_1 = Ax^n$,  but arrived to a seemingly incorrect solution that fails upon rechecking: $$y_1 = \frac{1}{n^2}x^n, y_2 = (n^2x)^{\frac1n}, q(x) =(1-n)nx^{2-2n}$$
Here is my work:

A: You can use Cauchy-Euler's differential equation with solution $y_1=x^2$ and $y_2=\sqrt x$.
$$x^2y''+bxy'+cy=0$$
Then find the constants $b$ and $c$.
Substitute $y=x^m$:
$$\implies m^2+(b-1)m+c=0$$
Then $m=\dfrac 12$ and $m=2$.

A: It is easy to construct a such equation. Let $y_1=x,y_2=\frac1x$ and $y=C_1y_1+C_2y_2$. Then from
$$ y''+p(x)y'+q(x)y =0 $$
one has
$$ C_1[p(x)+xq(x)]+C_2\frac1{x^3}[2-xp(x)+x^2q(x)]=0. $$
Let
$$ p(x)+xq(x)=0, 2-xp(x)+x^2q(x)=0 $$
which give $p(x)=\frac1x,q(x)=-\frac1{x^2}$. Thus the DE becomes
$$ y''+\frac1x y'-\frac1{x^2} y=0. $$


text:
Q: Use of which : examples correct?
During the time of which he kept a record the number of road accidents never rose above a 100.

or

During the time in which he kept a record the number of road accidents never rose above a 100.

Which is the better of these two?

A: It's more of a question of which preposition to use to effect the meaning you're intending to convey than which one is better?
Keeping a record of a particular time is different from keeping a record in that time, with the latter, not necessarily implying, the record of that very time itself.

A: During the time in which he kept a record, the number of road accidents never rose above 100.
Note
We read "100" as "a hundred" or "one hundred".


text:
Q: How does stroking metal with a magnet magnetize the metal? How does stroking metal with a magnet magnetize the metal? I have thought about it for a while and got absolutely no clue as to how the magnetic domains in the steel rod got shifted to the same direction (regions of metallic ions pointing the same direction, in an unmagnetised metal these domains cancel each other).
related link showing the stroking of metal with a magnet. Its particularly the manner in which we are stroking that could be causing the magnetisation. The video shows it being repeatedly stroked the same direction

A: If a ferromagnetic material is placed in, and then removed from, a magnetic field, the "remnant" magnetization within the material will depend on the strength of the field.  Stroking a bar will bring the strong field from the pole of the magnet into close proximity with each part of the bar.  Then the magnetic "domains" within the bar tend to drop back into alignment with nearest crystal axis.


text:
Q: asp.net viewstate security Is asp.net viewstate by EnableViewStateMac="True" is 100% secure?
I means, it's not important for me that user decode the viewstate content and see the values.
the thing that is important is tamper proof.
Can user change a value (for example an ID) and post back the page ?
Thank you very much for your feedbacks.

A: Viewstate is tamper resistant, but not tamper proof.  This MSDN article talks about it (Threat #2)  http://msdn.microsoft.com/en-us/magazine/ff797918.aspx

A: Anything that is on your page and sent to the client can be tampered with. This includes the viewstate that is passed on. Always validate input coming from a postback afterwards. Never assume that some identifier (for example) you sent to the client hasn't been changed before posting it back.
If you want to remember values, use server-side memory, such as the Session state.


text:
Q: How to set full width and height for chrome new window How can I create new window with full of available space in display screen.
function CreateWindow () {
    chrome.app.window.create("Spreadsheet.html" , {
        "bounds"    :   {
            "width" :   500,          // need full width and height
            "height":   400
        }
    });
}

chrome.app.runtime.onLaunched.addListener(CreateWindow);

A: Create the window maximized to use all available screen space.
chrome.app.window.create("Spreadsheet.html" , { state: 'maximized'}

See app window documentation for more details.

A: You cannot access window.innerWidth and height though you can use below code
function CreateWindow () {
    chrome.app.window.create("Spreadsheet.html" , {
        "bounds"    :   {
            "width" :   window.screen.availWidth,
            "height":   window.screen.availHeight
        }
    });
}

chrome.app.runtime.onLaunched.addListener(CreateWindow);


text:
Q: ¿Cómo hacer que el RIGHT JOIN retorne ceros? El día de hoy vengo con un pequeño problemilla con Bases de Datos, estoy usando phpMyAdmin, pero eso es lo de menos.
Tengo una tabla marcaequipos, donde almaceno marcas de equipos al azar, esta tabla esta compuesta por IDMarca y NombreMarca, nada más. Tengo otra tabla llamada equipos relacionada con la primera tabla por el IDMarca. En este caso, quiero saber el total de equipos por marca.
Realicé la siguiente consulta:
SELECT m.NombreMarca, COUNT(*) as TotalPorMarca FROM equipos e
RIGHT JOIN marcaequipos m ON e.IDMarca = m.IDMarca
GROUP BY m.IDMarca;

Está bien hecho y debería retornarme valores null o al menos ceros (0), sin embargo, me retorta unos (1) cuando se crea una marca nueva y esta aún no tiene equipos asociados.

Esos deberían ser ceros (0), no sé por qué sucede esto. ¿Podrían ayudarme a resolverlo por favor?

A: Vemos un pequeño ejemplo. Usamos el LEFT JOIN en vez de RIGHT JOIN. Aquí creamos las tablas:
create table marcaequipos (
  NombreMarca TEXT NOT NULL,
  IDMarca INT PRIMARY KEY NOT NULL
);

create table equipos (
  NombreEquipo TEXT NOT NULL,
  IDMarca INT NOT NULL, IDEquipo INT PRIMARY KEY NOT NULL
);

Y aquí añadimos algunas entradas de prueba:
insert into marcaequipos (NombreMarca, IDMarca)
                  values ("Prueba 1", 1);

insert into marcaequipos (NombreMarca, IDMarca)
                  values ("Prueba 2", 2);

 insert into equipos (NombreEquipo, IDMarca, IDEquipo)
              values ("Equipo A", 1, 1);

insert into equipos (NombreEquipo, IDMarca, IDEquipo)
             values ("Equipo B", 1, 2);

insert into equipos (NombreEquipo, IDMarca, IDEquipo)
             values ("Equipo C", 1, 3);

Fíjate que el equipo Prueba 2 no tiene ningunos equipos asociados. Probamos el orden siguiente:
select marcaequipos.NombreMarca, COUNT(equipos.IDMarca)
  from marcaequipos left join equipos
  on marcaequipos.IDMarca = equipos.IDMarca
  group by equipos.IDMarca;

y produce la salida siguiente:
Prueba 2|0
Prueba 1|3

... que me parece lo que quieres, ¿no?
Para averiguar por qué tu orden produce 1 en vez de 0 para las filas de marcas sin ningún equipo, probamos el orden siguiente:
select *
  from marcaequipos left join equipos
  on marcaequipos.IDMarca = equipos.IDMarca;

que imprime la tabla
Prueba 1|1|Equipo A|1|1
Prueba 1|1|Equipo B|1|2
Prueba 1|1|Equipo C|1|3
Prueba 2|2|||

Nota la fila al final que está asociada a la marca Prueba 2 aunque ésta no tiene ningún equipo asociado. Esto me parece una particularidad del LEFT JOIN (aunque si hay alguna motivación para este comportamiento, no la sé y me interesaría saberla). Pero de todos modos, cuando realizas un COUNT(*) entonces estás incluyendo esta fila "trivial", pero realizando un COUNT(equipos.IDMarca) puedes excluirla.


text:
Q: Visual Studio 2022 does not "start" application when debugging multiple projects I have got an issue with Visual Studio Code 2022. Sometimes - not always - when debugging multiple projects in the same solution, one or more applications do not start.
When debugging console applications, VS opens a new coonsole window for each startup project.
Some of the console applications do not show any output. Moreover, the affected projects also do not hit any breakpoints at all.
This issue started with VS2022. The same code worked perfectly with VS2019. In the following screenshot it is shown the first Console.WriteLine did not even get executed (It looks to me as if main is never invoked).

I have already checked if a breakpoint in another project blocks debugging, but that is not the case.

A: click on switch between available views and solutions which will show up project solution Icon, right click on the icon and update startup projects.
VS 2022 locate startup project


text:
Q: Activeadmin 1.3.2 issues in rails 5.2.1 I am using the active admin gem into my new project with Ruby 2.5.1p57 and Rails 5.2.1. All are good. But, I am facing the issue with open new resource link or update the resource. Even, If I add permit_params, same issue.
Started GET "/admin/admin_users/new" for 127.0.0.1 at 2018-10-04 20:59:08 +0530
Processing by Admin::AdminUsersController#new as HTML
AdminUser Load (0.5ms)  SELECT  `admin_users`.* FROM `admin_users` WHERE `admin_users`.`id` = 1 ORDER BY `admin_users`.`id` ASC LIMIT 1
↳ /home/vivek/.rvm/gems/ruby-2.5.1@regroup2/bundler/gems/activeadmin-
c301ab126b3f/lib/active_admin/base_controller.rb:39
Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.5ms)

ArgumentError (wrong number of arguments (given 2, expected 0..1)):

A: But finally, Fixed the issue by adding below line code to the following
file:
config/initializers/active_admin.rb
def resource_params
[(params[resource_request_name] || params[resource_instance_name]).try(:permit!) || {}]
end

Not sure. Is this correct way to do.


text:
Q: Where trigonometry root $ 2\pi n $ comes from I've and expression like:
$$ \tan^2(x) = \frac{1-\cos^3(x)}{1-\sin^3(x)} $$
and i found roots:
$$ x = \pi n + \frac{\pi}{4} $$
$$ x = (-1)^n * arcsin \frac{\sqrt 2 - 1}{\sqrt 2} + \pi n - \frac{\pi}{4}  $$
but there should be one more which equals to $ 2 \pi n $. Where it comes from as i'm having the following expression:
$$ (\sin(x) - \cos(x)) (\sin(x) + \cos(x) + \sin(x)\cos(x)) = 0 $$
From the first multiplier i have the first root, and from the second i have two, but one is below -1 which is not satisfying requirements.
UPD: I only interested in the root of $ 2\pi n $. I want to see how could i get it, not just guessing that it suits.

A: Hint:
Writing $\sin x=s,\cos x=c$
$$\dfrac{(1-c)(1+c+c^2)}{(1-s)(1+s+s^2)}=\dfrac{(1-c)(1+c)}{(1-s)(1+s)}$$
If $1-s=0\iff s=1,$ both sides are undefined $\implies s\ne1$
If $1-c=0\iff\cos x=1,x=2m\pi$ where $m$ is any integer
Else
$$\dfrac{1+c+c^2}{1+s+s^2}=\dfrac{1+c}{1+s}$$
$$\iff(s-c)(s+c+sc)=0$$
Method$\#1:$
Use Weierstrass Substitution
Method$\#2:$
Squaring & on rearrangement  we get $$\sin^22x-4\sin2x-1=0$$
$$\sin2x=2\pm\sqrt5$$
As for real $x,\sin2x\le1,$  $$\sin2x\ne2+\sqrt5$$
Now discard the extraneous root.

A: Consider $$
\tan^2(x)=0\Leftrightarrow \tan(x)=0\Leftrightarrow x=\pi n \text{ for }n\in\mathbb Z.
$$
So you see that your formula is wrong since
$$
\tan^2(\pi)=0\neq 2=\frac{1-(-1)^3}{1-0^3}=\frac{1-\cos^3(\pi)}{1-\sin^3(\pi)}.
$$
The right formula, using $\tan=\frac{\cos}{\sin}$ and $\cos^2+\sin^2=1$, is given by
$$
\tan^2(x)=\frac{\sin^2(x)}{\cos^2(x)}=\frac{1-\cos^2(x)}{1-\sin^2(x)}
$$
Now you can also see
$$
\tan^2(x)=0\Leftrightarrow 1-\cos^2(x)=0\Leftrightarrow \cos(x)\in\{-1,1\}\Leftrightarrow x=\pi n\text{ for }n\in\mathbb Z.
$$
But if you are interested in the roots of $f(x):=\frac{1-\cos^3(x)}{1-\sin^3(x)}$ you get
$$
f(x)=0\Leftrightarrow 1-\cos^3(x)=0\Leftrightarrow \cos^3(x)=1\Leftrightarrow \cos(x)=1\Leftrightarrow x=2\pi n\text{ for }n\in\mathbb Z.
$$
Since $1-\sin^3(2\pi n)=1\neq 0$ for $n\in\mathbb Z$ we deduce that $2\pi n$ for $n\in\mathbb Z$ are all roots of $f$.


text:
Q: How to use "any" in select list of a form to work in mysql? I have form which use below codes:
<select name="ptype">
    <option selected="selected" value="">Any</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>

now, how can the php page process the "Any" field in mysql. I tried below code, but didnot worked on process page:
$q = mysql_query("SELECT * FROM `listing` WHERE ptype='{$_POST['ptype']}'");
echo mysql_error();
while($r=mysql_fetch_array($q)){

}

There are multiple select option which use "any", all fields run on same query. here any means all value
what may be the error ? or how to use "any" value ?

A: Check for it separately:
SELECT *
FROM `listing`
WHERE '{$_POST['ptype']}' = 'ANY' or ptype='{$_POST['ptype']}'

A: If the option is any, programitically change your query as :
$q=mysql_query("SELECT * FROM `listing`");

A: If any means that both can work, just drop the WHERE clause from your query if $_POST['ptype'] doesn't have a value (or give it a value and check for that).

A: $ptype = $_POST['ptype'];
if ($ptype == "Any") {
    $w = " WHERE 1";
} else {
    $w = " WHERE ptype = '" . $ptype . "'";
}
$q = mysql_query("SELECT * FROM `listing`" . $w);
echo mysql_error();
while ($r = mysql_fetch_array($q)) {
....
}


text:
Q: How to convert exe application to jar file? I have exe file called Myapp.exe. Now I want to convert .exe to jar file. That jar file should also work in NON JAVA system. I don't have any idea to implement it. Can anyone please suggest me how to do it?

A: Direct conversion not available !!!
because they are in entirely different platforms.

A: Meeting your requirements is impossible for two reasons.
1) You cannot change an EXE to a JAR file.
2) You cannot run a JAR file on a system that doesn't have Java installed.
If you want to run something on a (Windows) system with no Java installation, it needs to be an EXE ... or something else that doesn't require Java.
(It might help if you explained why you think you need to do this.  Perhaps there is an alternative set of requirements that are not impossible to meet.)

why i am doing all those stubs is for making my jar has to work in java not installed system.

It needs to be an EXE then!

I have an jar.It is working fine in java installed system.My task is to Bundle jre inside jar(Not along with jar(i.e we can put jre and jar in same folder to run a jar as given in following url mindfiresolutions.com/… ))Because i have to give jar file only to client,in such a way that they can use this Myapp.jar in non java system also.But,i don't know how to bundle jre inside jar.I Don't how to run jre inside jar?

Ermm ...

Is it possible?

No.  You cannot embed a JRE inside a JAR file in any way that would allow it (the JAR file) to run your Java code without first installing Java.  (And installing Java would defeat the purpose of embedding the JRE ... of course.)
But what you can do is create an EXE file which has a JRE and a JAR embedded in it.  And there are tools for doing this.  Here's the canonical Question on how to do it:

*

*How can I convert my Java program to an .exe file?

I think you need to read the Oracle documentation on what a JAR file really is, and how Java programs are normally executed.  That will help you understand what is feasible ... and what is nonsensical.


text:
Q: How to position an element within a table cell? I'm trying to move the "X" to the right, but whenever I change the padding in the style, the table is resized. What is the way to shift the "X" to the right side without messing with the table width?

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Untitled Document</title>

                X
                aaa / bbb / ccc

A: use text-indent. remove overflow:hidden and set max-width. also you can add text-indent to keywords. I created an example.

.hash {
  font-family: 'IBM Plex Sans', sans-serif;
  font-size: 24px;
  padding-top: 5px;
  padding-left: 20px;
  background-color: green;
  text-indent: 80px;
  max-width: 60px;
}

.keywords {
  padding-left: 0px;
  margin: 0;
  font-size: 42px;
  background: yellow;
  text-indent: 50px;
}

      X
      aaa / bbb / ccc


text:
Q: window.focus not working upon browser close , but working well when trigger via button While I'm successfully able to switch focus to Parent window while closing the child window using the close button, Unable to do the same while performing the close using the browser close button. Steps are per below.
1. Click Try it in parent window.
2. Open another tab in browser.
3.1 Click the Close Me button in the child window.
4. Focus successfully navigate to Parent window.
3.2 Click the browser close button.
4. Focus not navigating to Parent window.
Browser using : Chrome, Would be happy to get a generic way for all the browser.
parent.html

            <button onclick="myFunction()">Try it</button>

Child.html

This is 'myWindow'

<button onclick="closeWindow()">Close Me</button>


text:
Q: What do I do with occupied planets? I'm in this sweet alliance with two other empires minding my own business when one of my teammates wants to declare war on a puny neighbor, me and the other ally are down with it and agree.
I quickly send in a huge fleet and start bombarding a planet, I take down its defenses and send in a ground army to mop up their defending army. After taking them down I get this sweet victory screen saying I am successfully occupying the planet. My assumption was that it was going to be like Civ 5 and ask me to choose what to do with it, such as kill off the people in it or take it over as my own planet and make it a part of my empire; no such luck, instead it seems like I can do nothing with it, and it remains under control of its owner, sort of.
My armies are chilling on the planet, I am able to remove them, but should I? When I go to the grid screen it says nothing can be done and nothing is being produced because of the occupation.
This is a one player game, all the other empires are ai controlled. I did not start the war, instead I got an alert asking to vote whether to go to war or not.
What do I do now? Do I just ignore it and continue on with my war? Should I remove my armies? Do I ever get the planet?
What do I do with occupied planets?

A: You occupy the planet, you do not control it, this works similar to EU4.
The occupation grants a large amount of warscore and you can send your armies away, Your opponent has to reinvade to liberate the planet.
Whether you get the planet in the end depends on the war goals, the occupation merely provides additional warscore, with which you can press your demands.
Most importantly though, it prevents the enemy from using the planet and getting resources from it without you having to constantly bombard it and requiring an invasion from your opponent to liberate it.

A: You can execute the occupation of a planet, by landing of 'ASSAULT ARMIES'.
At first, you must recruit one or more of the "ASSAULT ARMY".
After clicking a planet, you will find a Tab named "ARMIES".
Then a choice "RECRUIT" is displayed on there,
and you should choose "ASSAULT ARMY" (or "ROBOTIC ARMY" if possible),
not "defence army".
Once an Assault Armies has been built, they can embark for outer space any time.
Before embarking, you should not forget to add an attachment (defensive/offensive).
ARMIES that have already embarked, they are renamed "TRANSPORT FLEET".
When you send them into orbit of a hostile planet,
the occupation will be finally possible.
plaese forgive my poor english.
Jolan Tru!


text:
Q: vb.net datagridview custom format i have a datagridview the contents are as follows when i load the datagridview

for the column Payment ID i want the IDs to be like P00001 i know i have to use the mask \P99999 but the question is how? any help would be appreciated thanks in advance.. and the input mask in the access database from where i'm importing the data is \P99999;;#

A: E.g.
Dim table As New DataTable

With table.Columns
    .Add("Formatted", GetType(Integer))
    .Add("Unformatted", GetType(Integer))
End With

With table.Rows
    .Add(1, 1)
    .Add(2, 2)
    .Add(3, 3)
End With

Me.DataGridView1.DataSource = table
Me.DataGridView1.Columns(0).DefaultCellStyle.Format = "\P00000"


text:
Q: What would be the best way to find an angular element by class? Hey thanks for checking out my question. I am trying to find angular elements by class and push them into an array for another function.
 $scope.find = function () {
    var someVar = [];
    $scope.element.find('.selectedRow').each(function(){
        someVar.push($(this).find('td').eq(0).text())

    })
    return rows;
    console.log(rows);
};

A: First off, I highly recommend reading this answer about how to "think" in angular: https://stackoverflow.com/a/15012542/1014979
With angular, you need to think in terms of the model, not the DOM. So, you should add some ng-clicks to your rows that will add them to your array (and probably remove them from the array when deselected). Then you have your array in your model already without need to do any selecting from the DOM.

A: You can make use of
angular.element(element);

and in your case
angular.element(document.querySelector('.selectedRow'))

where element can be your class selector

A: I would recommend using(creating) a directive for that.

A: As mentioned by dnc253, referencing the DOM from your controller is not an effective way to develop in Angular. Another way you might do this:
Inject the data in the table into your view from the controller:
.controller('controllerName', ['$scope', function($scope) {
    $scope.rows = [
        { col1: 'foo', col2: 'bar', selected: false },
        { col1: 'baz', col2: 'foo', selected: false }
    ];
}]);

Use the ng-repeat directive to render the models in your view script:

         {{ row.col1 }}
         {{ row.col2 }}

Provide the toggleRow function in your controller to toggle the selected property on your row:
$scope.toggleRow = function (row) {
    row.selected = !row.selected;
}

Now you can track the selected rows from your controller, since each row has the selected property.


text:
Q: How to set ContextPath for an image link i am trying to put context path for an image in HTML.
Here /MyWeb is the ContextPath which is hardcoded. How can i get dynamically.
i am using as but image is not displaying. Is there any option.

A: First of all, "Context path" is a term which is typically used in JSP/Servlet web applications, but you didn't mention anything about it. Your question history however confirms that you're using JSP/Servlet. In the future, you should be telling and tagging what server side language you're using, because "plain HTML" doesn't have a concept of "variables" and "dynamic generation" at all. It are server side languages like JSP which have the capability of maintaining and accessing variables and dyamically generating HTML. JavaScript can be used, but it has its limitations as it runs in webbrowser, not in webserver.
The question as you initially have will only confuse answerers and yield completly unexpected answers. With question tags you reach a specific target group. If you use alone the [html] tag, you will get answers which assume that you're using pure/plain HTML without any server side language.

Back to your question: you can use ${pageContext.request.contextPath} for this.

See also:

*

*How to use relative paths without including the context root name?

*Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

A: You can't write JavaScript in the src attribute. To do what you want, try some code like this:
var img = new Image();
img.src = contextPath + "/images/pageSetup.gif";
document.getElementById('display').appendChild(img);

Here the target; the place where you want to display the image, is a div or span, with the id display.
Demo
With HTML, you'll have to take some extra traffic of producing an error, so you can replace the image, or you can send some traffic Google's way. Please do not use this:

Demo
Do not use this.

A: You must use JavaScript for this.
First, have all images point to some dummy empty image on your domain while putting the real path as custom attribute:

Now have such JavaScript code in place to iterate over all the images and change their source to use the context path:
var contextPath = "/MyRealWeb";
window.onload = function() {
    var images = document.getElementByTagName("img");
    for (var i = 0; i < images.length; i++) {
        var image = images[i];
        var realSource = image.getAttribute("real_src") || "";
        if (realSource.length > 0)
            image.src = contextPath + realSource;
    }
};


text:
Q: Rails - Display a different form for the same action based on the url I have a simple Client model with some fields and a basic form. The url to access it is /clients/new, that leads to clients#new method. What I need to do is create a new route to resellers, that will lead to the same method and the same form, but with some new fields, like the reseller's name.
Example: url /reseller/clients/new leads to the method clients#new and display a new cell with new inputs for the new form.
I created a method that checks the url and sets a session if the route has "reseller" in it, so my cell can handle if the new fields will be displayed or not. But this is leading me to problems regarding model validations, since if the new fields are displayed in the view, theire presence is true. I would have to access my sessions inside the model in order to create a proper validation, and that does not sound as the right path.
I wonder how can I achieve my goal within a proper way?
Thanks in advance.

A: Solved.
For this I created a new model called Reseller. With that, the model Client has accepts_nested_attributes_for :reseller. This way I can render the form in my cell for the Reseller model and set all the fields inside it with :presence => true, with no need of a conditional statement. If the url has "reseller", the cell will render the form and the validation will happen.


text:
Q: How to achieve a simplified interface for C++ function template? I have function templates with two arguments, but the second argument is dictated by the first, and I would like to avoid writing both arguments when I call the function - that will help prevent mistakes and also be cleaner. I am looking for design advice or language features that will let me do this.
Given:
/* E1 and E2 always correspond to T1, and E3 always corresponds to T2 */
enum class MyEnum { E1,E2,E3 };
struct T1 { };
struct T2 { };

/* definition */
template <MyEnum E, typename T>
T* Function() { /* do something */ }

/* explicit specializations */
template T1* Function<MyEnum::E1, T1>();
template T1* Function<MyEnum::E2, T1>();
template T2* Function<MyEnum::E3, T2>();

How can I achieve a calling convention that does not require the caller to specify argument 2?
// I want to avoid this:
T1 * t1 = Function<MyEnum::E1, T1> ();

// I *do* (ideally) want this:
// I thought template argument deduction might work, but compilation fails
T1* t1 = Function<MyEnum::E1>();

A: auto might be a good way:
template <MyEnum E>
auto Function()
{
    if constexpr (E == MyEnum::E3) {
        /* do something and return a T2* */
    } else {
        /* do something and return a T1* */
    }
}

Else, you can create custom "traits":
#if 1 // In your case a simple `std::conditional` does the job

template <MyEnum E>
using ret_type_t = std::conditional_t<MyEnum::E3 == E, T2*, T1*>;

#else // The more classical way

template <MyEnum E>
struct ret_type
{
    using type = T1*;
};
template <>
struct ret_type<MyEnum::E3>
{
    using type = T2*;
};
template <MyEnum E> using ret_type_t = typename ret_type<E>::type;

#endif

And then
template <MyEnum E>
ret_type_t<E> Function() { /* do something */ }


text:
Q: Suspicious Traffic Find IP on Azure Web App I have noticed in my app insights log some suspicious traffic and I would like to block the IP. However, all I find is 0.0.0.0 for the IP on all requests. Is there a way to find in a log the exact IP to block future requests from the IP? I am using an Azure Web App with App Insights turned on for .Net Core application.

A: You can enabled Azure Monitor for AppServiceHTTPLogs and AppServiceIPSecAuditLogs. These logs should contain the source IP address.


text:
Q: Error 1009, it is impossible to access the property or method of a null object reference I have the following action script class and when I instantiate the class by calling the constructor in a mxml file I have get "error 1009 it is impossible to access the property or method of a null object reference". Why do I receive this error?
package com.esprit.immocr.DTO
{
   import mx.collections.ArrayCollection;
   [Bindable]
   [RemoteClass(alias="com.esprit.immocr.DTO.TypePieceDto")]
   public class Typ
   {
       public var code_type_piec:  String;
       public var Libelle_t_piec: String;
       //Association
       public var clientsdto: ArrayCollection;
       public function Typ(o:Object):void
       {
            this.code_type_piec = o.code_type_piec;
            this.Libelle_t_piec = o.Libelle_t_piec;
            this.clientsdto = o.clientsdto;
       }
    }
}

and the following mxml file using this class
protected function tpvalider(event:MouseEvent):void
{
    //ro.removeEventListener(Event.ADDED_TO_STAGE, tpvalider);
    tp.code_type_piec=codetp.text;
    tp.Libelle_t_piec=libtp.text;
    ro.createTppiece(tp); // ro is a reference to remote object
}
private  var tp: Typ = new Typ(obj);


text:
Q: Android Webview Google Charts not working I have been searching the internet and SO for a solution embedding a WebView displaying a webpage with google-charts. This far i have found nothing. I do not want use the image API nor building the html, as I can't access the needed data for rendering the chart.
Any suggestions?
Stacktrace:
    09-29 12:26:34.158  29906-29906/xxxxxxxxxxxxxxx E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at xxxxxxxxxxxxxxx.MMStatisticsActivity.onCreateView(MMStatisticsActivity.java:32)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:870)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:420)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4895)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
            at dalvik.system.NativeStart.main(Native Method)

Code:
public class MMScheduleActivity extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState){

        View view = inflater.inflate(R.layout.activity_schedule, container, false);
        WebView browser = (WebView) view.findViewById(R.id.schedule_webview);

        browser.getSettings().setJavaScriptEnabled(true);

        SharedPreferences sharedPref = getActivity().getSharedPreferences("preferences", Context.MODE_MULTI_PROCESS);
        int event_id = Integer.parseInt(sharedPref.getString(getString(R.string.event_id), "0"));

        if(event_id!=0){
            String url = "http://xxxxxx/page/stats/" + event_id + '/';
            Log.i("URL", url);
            browser.loadUrl(url);
        }
        return view;
    }
}

Worth mentioning is that I load the WebView within a Fragment.

A: I have shown a google chart in WebView, and didn't find it that difficult.
Snippets for your html file:
//include google api js file
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

//a div for chart
<div id="my-chart">
</div>

Snippets from js file:
// In case there is no network
// the google jsapi is not loaded causing the screen to go white and break the application
// Check if google object is not null
if(typeof(google) !== 'undefined')
{
    google.load('visualization', '1.0', {'packages':['corechart']});
}

//a separate function for drawing data. Just call it wherever you need to redraw the chart
function drawChart(chartData){
    data = new google.visualization.DataTable();
    data.addColumn('string', 'Col1');
    data.addColumn('number', 'Col2');

    for (var i = 0; i < 5; i++)
    {
        ideasChart.data.addRow("data1", "data2");
    }

    chart = new google.visualization.ComboChart(document.getElementById('my-chart'));
    chart.draw(data, chartOptions);
}

//chartOptions to customize your chart, its text color, etc.

chartOptions = {
    chartType:"ComboChart",
    containerId:"visualization",
    stackSeries: true,
    isStacked : true,
    backgroundColor: '#242424',
    legend: 'none',
    tooltip:{
        trigger:'none'
    },
    enableInteractivity: false,
    colors : ['#6DB1E2','#FDCB34'],
    chartArea: {
        backgroundColor: {
            stroke: '#fff',
            strokeWidth: 1
        }
    },
    seriesDefaults: {

        rendererOptions: {
            barPadding: 0,
            barMargin: 10
        },
    },

    seriesType: "bars",
    bar:
    {
        groupWidth:"80%"
    },

    viewWindowMode : {
        max: 'pretty'
    }
};

And in your android WebView,
you would need to load your html file as:
myWebView.loadUrl("file:///android_asset/www/index.html");

Hope it helps. You would need to customize your chartOptions as per your requirement. And refer examples to start it.
EDIT:
If you have a URL which shows google charts, then you would simply need to add
myWebView.loadUrl(strLink);

in your Activity.


text:
Q: Can't access JD-Eclipse site: http://java.decompiler.free.fr/?q=jdeclipse I can't access java decompiler site: http://java.decompiler.free.fr/?q=jdeclipse.
It shows 403 error :

Erreur 403 - Refus de traitement de la requête (Interdit - Forbidden)**.

I'm accessing it from China. Is anyone out of China can access it properly? Or it's the server issue?
EDIT:
The eclipse update site is hosted on jd.benow.ca.

A: I'm getting the same 403 error.
You can see a previous version of the site from archive.org.
If you want to install the Eclipse plugin you can download and unzip the update site from archive.org as well.
The eclipse update site is also hosted on jd.benow.ca.

A: Sorry for the inconvenience: my Webhost detects a virus in JD-Eclipse !

Votre page personnelle a été suspendue pour la/les raisons suivantes:
==> Your personal page has been suspended for/because:
Virus: http://java.decompiler.free.fr/jd-eclipse/update/plugins/jd.ide.eclipse.win32.x86_0.1.3.jar

This file has not changed since two years ! It contains an DLL library compressed with UPX and modified. Hackers and anti virus have some probems to decompress it.
Well, this situation is really uncomfortable. I will try to restore my website.
Emmanuel Dupuy, JD Projects.


text:
Q: Change Log4J2 Output File During Runtime I'm trying to integrate Log4J2 with a bit of custom logging functionality in a project of mine and running into some issues getting Log4J2 to behave similarly to my own implementation. I'd like to be able to change the log file being written to (make if doesn't exist, cease writing to old file, only write to new file) based on events that occur in execution.
I'll give an example that hopefully illustrates what I'm looking for. We start the application and write to some predetermined log file name but we're just recording preliminary logs because nothing of interest has really happened yet. Once environmental conditions are correct and we've received user input the software is engaged and we'd like to begin logging for both debugging information and data capture. To separate the preliminary data from the interesting data we'd like to change our log file to a new log file who's name contains more information about the state of the environment when the system was engaged, to make it easier to sort through which log files we want to analyze and post-process.
I've seen posts on how to accomplish similar things, but they seem to either require the new filename to be known before Log4J2 is initialized (i.e. setting a system property) or using a RoutingAppender which seems to be closer but appears to require knowing all possible values (to define the routes) that we might want to put in our file name. We'd have to define one route per each environment state (or worse yet, each state combination) we want to put in the file name.
Any ideas?

A: You use the RoutingAppender to dynamically create new files based on a ThreadContext key/value.
Here is an example of how to do this:
https://logging.apache.org/log4j/2.x/faq.html#separate_log_files
In the example, the value of ROUTINGKEY in the ThreadContext map determines the new file name.


text:
Q: remove readonly in inpput of form with tree Jquery How do I fix this error , using tree in jquery . I can get the specific button using ( form> .button ) used his class and only change the button with the "this" . however I can not change the attributes only of inputs in the form parent, I caught up with the $ (this ) .closest ( 'form' ) . attr ( 'id' ).
<form name='bolovo' id='bolovo' method="post">

 <input type='text' name='nome' readonly id='nome' value='nome' </input>
<input type='button' readonly name='editarBotao' id='edit' class='button' value='Edit'/>
    </form>

             <form name='queijo' id='queijo' method="post">

 <input type='text' name='nome1' id='nome1' readonly value='nome1' </input>
     <input type='button' readonly name='editarBotao' id='edit' class='button' value='Edit'/>
                 </form>


text:
Q: Terraform - create cloudwatch scheduled expression based on variable - expected expression but found "*" I'm trying to create AWS Clouwatch event rule via terraform
variable "schedule_expression" {
  default = "cron(5 * * * ? *)"
  description = "the aws cloudwatch event rule scheule expression that specifies when the scheduler runs. Default is 5 minuts past the hour. for debugging use 'rate(5 minutes)'. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html"
}

I want to specify variable instead of 5
variable "AutoStopSchedule" {
   default = "5"
}

variable "schedule_expression" {
  default = "cron(${var.AutoStopSchedule} * * * ? *)"
  description = "the aws cloudwatch event rule scheule expression that specifies when the scheduler runs. Default is 5 minuts past the hour. for debugging use 'rate(5 minutes)'. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html"
}

but getting:
Error: variable "schedule_expression": default may not contain interpolations

main.tf
# Cloudwatch event rule
resource "aws_cloudwatch_event_rule" "check-scheduler-event" {
    name = "check-scheduler-event"
    description = "check-scheduler-event"
    schedule_expression = "${var.schedule_expression}"
    depends_on = ["aws_lambda_function.demo_lambda"]
}

i want to create schedule_expression based on AutoStopSchedule variable, how to do it ?
Tried following:
resource "aws_cloudwatch_event_rule" "check-scheduler-event" {
    name = "check-scheduler-event"
    description = "check-scheduler-event"

    #schedule_expression = "cron(15 * * * ? *)"
    schedule_expression = "${var.AutoStopSchedule == "5" ? cron(5 * * * ? *) : cron(15 * * * ? *)}"
    depends_on = ["aws_lambda_function.demo_lambda"]
}

getting expected expression but found "*"

A: Thanks for the link @ydaetskcoR, it was helpful !!
variables.tf:
variable "schedule_expression" {
  default = "5"
  description = "the aws cloudwatch event rule scheule expression that specifies when the scheduler runs. Default is 5 minuts past the hour. for debugging use 'rate(5 minutes)'. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html"
}

variable "AutoStopSchedule" {
   default = {
    "1" = "cron(30 * * * ? *)"
    "2" = "cron(0 */1 * * ? *)"
    "3" = "cron(0 */1 * * ? *)"
    "4" = "cron(0 */12 * * ? *)"
    "5" = "cron(0 10 * * ? *)"
  }
}

main.tf
# Cloudwatch event rule
resource "aws_cloudwatch_event_rule" "check-scheduler-event" {
    name = "check-scheduler-event"
    description = "check-scheduler-event"
    schedule_expression = "${lookup(var.AutoStopSchedule, var.schedule_expression)}"
    depends_on = ["aws_lambda_function.demo_lambda"]
}

PS. Can't acept my own answer in next 2 days

A: You don't need to do that. What you need to do is use a local instead, like:
variable "AutoStopSchedule" {
   default = "5"
}

locals{
schedule_expression= "cron(${var.AutoStopSchedule} * * * ? *)"
}

output "schedule_expression" {
  value = "${local.schedule_expression}"
}

If you terraform apply that you get:
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

schedule_expression = cron(5 * * * ? *)

To use it
${local.sschedule_expression} where you had ${var.schedule_expression} before.


text:
Q: bash 4: Generic access to substring (n) of string by arbitrary delimiter? Let's assume I have the following string: x="number 1;number 2;number 3".
Access to the first substring is successfull via ${x%%";"*}, access to the last substring is via ${x##*";"}:
$ x="number 1;number 2;number 3"
$ echo "front : ${x%%";"*}"  #front-most-part
number 1
$ echo "back  : ${x##*";"}"  #back-most-part
number 3
$

How do I access the middle part: (eg. number 2)?
Is there a better way to do this if I have (many...) more parts then just three?
In other words: Is there a generic way of accessing substring No. n of string yyy, delimited by string xxx where xxx is an arbitraty string/delimiter?

I have read How do I split a string on a delimiter in Bash?, but I specifically do not want to iterate over the string but rather directly access a given substring.
This specifically does not ask or a split into arrays, but into sub-strings.

A: With a fixed index:
x="number 1;number 2;number 3"

# Split input into fields by ';' and read the 2nd field into $f2
# Note the need for the *2nd* `unused`, otherwise f2 would
# receive the 2nd field *plus the remainder of the line*.
IFS=';' read -r unused f2 unused <<<"$x"

echo "$f2"

Generically, using an array:
x="number 1;number 2;number 3"

# Split input int fields by ';' and read all resulting fields
# into an *array* (-a).
IFS=';' read -r -a fields <<<"$x"

# Access the desired field.
ndx=1
echo "${fields[ndx]}"

Constraints:
Using IFS, the special variable specifying the Internal Field Separator characters, invariably means:

*

*Only single, literal characters can act as field separators.

*

*However, you can specify multiple characters, in which case any of them is treated as a separator.

*The default separator characters are $' \t\n' - i.e., space, tab, and newline, and runs of them (multiple contiguious instances) are always considered a single separator; e.g., 'a   b' has 2 fields - the multiple space count as a single separator.

*By contrast, with any other character, characters in a run are considered separately, and thus separate empty fields; e.g., 'a;;b' has 3 fields - each ; is its own separator, so there's an empty field between ;;.
The read -r -a ... <<<... technique generally works well, as long as:

*

*the input is single-line

*you're not concerned about a trailing empty field getting discarded
If you need a fully generic, robust solution that addresses the issues above,
use the following variation, which is explained in @gniourf_gniourf answer here:
sep=';'
IFS="$sep" read -r -d '' -a fields < <(printf "%s${sep}\0" "$x")

Note the need to use -d '' to read multi-line input all at once, and the need to terminate the input with another separator instance to preserve a trailing empty field; the trailing \0 is needed to ensure that read's exit code is 0.

A: Don't use:
Create an array with a delimiter of ;:
x="number 1;number 2;number 3"
_IFS=$IFS; IFS=';'
arr=($x)
IFS=$_IFS

echo ${arr[0]} # number 1
echo ${arr[1]} # number 2
echo ${arr[2]} # number 3


text:
Q: Is there any eclipse plugin for Cherrypy? Can anybody suggest me IDE for CherryPy ? Is there plugin for Eclipse ? I have installed PyDev and I have option Django but not CherryPy.

A: Once you've have PyDev configured your almost there.  So far there is not a cherrypy plugin for eclipse.
Download the version of cherrypy you would like to use.  Using the command line navigate to the directory cherrypy downloaded to and execute the following command:
python setup.py install

http://www.cherrypy.org/wiki/CherryPyInstall
Andrew


text:
Q: Positioning Google maps v2 zoom in controls in Android I've created a transparent actionbar but the zoom controls and the word 'Google' are behind it. I have no clue how to adjust their location. The default Google Map app on Android phones has them raised above the bottom action bar. Is it possible to reposition the zoom controls and the word 'Google'?
I know you can enable/disable the controls with:
 map.getUiSettings().setZoomControlsEnabled(true);

A: I think this would be helpful for you. I am attempting to implement a similar layout, my solution has been to try and hide the controls on a timed interval like 3 seconds on camera updates.
I think this is the best solution without having to implement custom controls.
mapFragment.setOnCameraChangeListener(new OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition position) {
                mapFragment.getUiSettings().setZoomControlsEnabled(true);
                Timer t = new Timer();
                TimerTask tt = new TimerTask() {

                    @Override
                    public void run() {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                mapFragment.getUiSettings().setZoomControlsEnabled(false);

                            }
                        });

                    }
                };

                t.schedule(tt, 3000);

            }

        });

This was mostly a proof of concept. But it does work.

A: You can accomplish this with the GoogleMap.setPadding() method (added in September 2013):
map.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);

From the API docs:

This method allows you to define a visible region on the map, to signal to the map that portions of the map around the edges may be obscured, by setting padding on each of the four edges of the map. Map functions will be adapted to the padding. For example, the zoom controls, compass, copyright notices and Google logo will be moved to fit inside the defined region, camera movements will be relative to the center of the visible region, etc.

Also see the description of how padding works in GoogleMap.

A: Unfortunately there is no way to move the zoom controls provided with Google Maps you could disable them and create your own custom zoom controls and place them on the top of the map.

A: It can be done.  Perhaps there have been changes since this was asked and answered.
Please see the answer I submitted to a similar question here:
How to move google map zoom control position in android?
In a nutshell, you can get the parent layout of the zoom control buttons and change it's RelativeLayout LayoutParams.  In my answer I also include how to move the compass and toolbar as well.

A: If you are doing this for map adjustment then use margin or padding on bottom only about 36dp to 40dp. Otherwise if you are using location on Map in center then use a property of camera such like:
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

It make focus on location at meddium of page.
This:  mMap.getUiSettings().setZoomControlsEnabled(true); gives you only Zoom level but not focus on location at meddium.


text:
Q: predict(....,type="prob"), without type="prob" is fine, type="prob" with two classes is fine. but type="prob" with multiple classes is wrong My code for the predict function is as following:
predict(Flaw.rf, newdata = newtest[-grep("Product", colnames(newtest))],
        type="prob")

When I get rid of the type="prob" there is no problem. And if I change the product to just 2, there is also no problem. However, when the product is multi-classes and I apply type="prob", there is something wrong. It says undefined columns selected


text:
Q: OutOfMemoryError: Java heap space and CPU-Usage 100% I recently updated my eclipse to:
Version: 2019-12 (4.14.0)
Build id: 20191212-1212
I am now facing the problem in one of my projects (Which I did not before):
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
I already changed my elipse.ini parameters to:
-Xms2048m
-Xmx6144m
But the heap space is not fully used during the run:

My CPU-Usage is at 100% during the run and the RAM is not really in usage.
Can someone tell me why the cpu is used to this extent and not the ram?
I have an Intel Core i7-9700 and 16GB of DDR4 RAM.
As for my code, I am loading a .csv file with 2 million lines into different HashMaps.
I do not know how to add the class which is responsible for the error, as it has 1776 lines of code.
Thanks for any help in advance.


text:
Q: MSVC generating unnecessary complicated instructions While benchmarking code involving std::optional<double>, I noticed that the code MSVC generates runs at roughly half the speed compared to the one produced by clang or gcc. After spending some time reducing the code, I noticed that MSVC apparently has issues generating code for std::optional::operator=. Using std::optional::emplace() does not exhibit the slow down.
The following function
void test_assign(std::optional<double> & f){
    f = std::optional{42.0};
}

produces
sub     rsp, 24
vmovsd  xmm0, QWORD PTR __real@4045000000000000
mov     BYTE PTR $T1[rsp+8], 1
vmovups xmm1, XMMWORD PTR $T1[rsp]
vmovsd  xmm1, xmm1, xmm0
vmovups XMMWORD PTR [rcx], xmm1
add     rsp, 24
ret     0

Notice the unaligned mov operations.
On the contrary, the function
void test_emplace(std::optional<double> & f){
    f.emplace(42.0);
}

compiles to
mov     rax, 4631107791820423168      ; 4045000000000000H
mov     BYTE PTR [rcx+8], 1
mov     QWORD PTR [rcx], rax
ret     0

This version is much simpler and faster.
These were generated using MSVC 19.32 with /O2 /std:c++17 /DNDEBUG /arch:AVX.
clang 14 with -O3 -std=c++17 -DNDEBUG -mavx produces
movabs  rax, 4631107791820423168
mov     qword ptr [rdi], rax
mov     byte ptr [rdi + 8], 1
ret

in both cases.
Replacing std::optional<double> with
struct MyOptional {
    double d;
    bool hasValue; // Required to reproduce the problem

    MyOptional(double v) {
        d = v;
    }

    void emplace(double v){
        d = v;
    }
};

exhibits the same issue. Apparently MSVC has some troubles with the additional bool member.
See godbolt for a live example.
Why is MSVC producing these unaligned moves? I.e. the question is not why they are unaligned rather than aligned (which wouldn't improve things according to this post). But why does MSVC produce a considerably more expensive set of instructions in the assignment case?
Is this simply a bug (or missed optimization opportunity) by MSVC? Or am I missing something?


text:
Q: Rails 4.2 save value in a session before going to new veiw Let's say I have an index page listed the customer orders and have a button to create a new order as in the image 1.
When I clicked "create new order button" I want Rails to show a message that requests to choose the order type from a list of items before going to the new view (from). When the user chooses the item from the drop down list, he/she can click a button to start filling the new order data, as in image 2.
But before doing that, the value of the selected item has to be saved in a session, so when the "new view/form" opened the system will restore the value from the session and put it in the form. (image 3)
My example more complicated and I really need that message box for different situations.
The problem: I did a lot of tries, but it seems that rails doesn't save the selected item before going to the new view only!!. surprisingly, when I play with the code, so when the user choose the item from the drop down list and click the button to go to another view in the order controller, it will save the selected item value in the session with no issues.
Your kind help, please
The Image description

A: In order to save value in session you can use session[:your_session_variable_name] = params[:item]

A: The following worked for me, in the controller:
def new
    session[:type_id]  =  params[:type][:id]
    @order= Order.new
end

in the view, using bootstrap Modal

Choose Order Type

    <%= form_tag(new_order_path , method: :get) do %>

        <%= collection_select(:type, :id, @types_list, :id, :name , class: "form-control") %>

        <%= button_to "choose", {action: "new"}, {form_class: 'form', class: 'btn btn-md btn-primary'} %>
        <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Cancel</button>

   <% end %>

A: How about passing the value as a variable in the URL? something like the following:
http://something.com/object/new?variable_name=value

Then in your controller you could do the following
value = params[:variable_name]

I'm not sure though how you are handling routing to the form page when a user chooses from the modal. I'll show you how in both Ruby and Javascript:
In Rails (Ruby)
new_object_path({ 'variable_name' => 'value' })
# would result in something like /objects/new?variable_name=value

In Javascript, you could just concatenate in before redirecting to said url
Hope this helps!


text:
Q: How to get the first node that has no parent from a node in a self-referencing table I'm using MySQL / MariaDB database. I can't use the procedure because I don't have the right and I want to select the top parent that have not upper parent from one of the child.
Examples :
Familly > CMP > ACC
I select the ACC child and I want the top parent that is Familly in this case.
.
Familly > CMP > Numeric > CFRA
I select the CFRA child and I want the top parent that is Familly in this case.
Here is my table :
create table llx_categorie
(
    rowid       int auto_increment primary key,
    entity      int     default 1 not null,
    fk_parent   int     default 0 not null,
    label       varchar(255)      not null,
    type        tinyint default 1 not null,
    description text              null,
);

Here is what I want to see :
child_label    top_parrent_label
ACC            Familly

and that is what I have try :
  SELECT rowid, label
  FROM llx_categorie m
  WHERE rowid=170
  UNION ALL
  SELECT m.rowid, m.label
  FROM llx_categorie m
  INNER JOIN llx_categorie p
    ON p.rowid = m.fk_parent

But that return every brother node.

A: You are looking for all child records connected to any parent record from a self join. Use a where clause to limit down the results from the self join for one side to only be parents:
SELECT c.*, parent.*
FROM llx_categorie c
INNER JOIN llx_categorie parent on c.fk_parent = parent.rowid
WHERE parent.fk_parent is null

For your instance, you will need to change the condition to equal 0 instead of null because your column is not null. I am not stating that in the SQL above because any visitors referencing this article should not connect to a 0 record by default. That schema paradigm is strongly not recommended. The foreign key constraint will try and enforce that 0 value within your foreign key. This can make the self join less performant, it could result in foreign key errors when a 0-record doesn't exist, and it will confuse new devs that would expect a null for a foreign key that doesn't have an associated row.


text:
Q: How to call API class in a ASP.NET CORE WEB APP (MVC) Project I created an ASP.NET Core MVC web app project in VS19, I created an API controller that has a function that I typically would be able to access when its in an ASP.NET Core Web API (swagger).
However, I tried to go to http:localhost:5001/api/GetAll/RLsOpHkBucbHZrU6lGk6 but it did not work so I removed the id and just left it as GetAll and it says page not found.
Is there a way to call an API controller in an ASP.NET Core MVC project since swagger isn't being used?
namespace CustomerSimulatorApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ESController : ControllerBase
    {
        private readonly IElasticClient _elasticClient;

        public ESController(IElasticClient elasticClient)
        {
            _elasticClient = elasticClient;
        }

        [HttpGet("GetAll/{_id}")]
        public async Task<EsSource> GetAll(String _id) // this will return everything within the source
        {
            var response = await _elasticClient.SearchAsync<EsSource>(s => s
                                               .Source(true)
                                               .Index("customer-simulation-es-app-logs*")
                                               .Query(q => q.Match(m => m.Field("_id").Query(_id))));

           return response?.Documents?.FirstOrDefault();
        }
    }


text:
Q: THREE.ExtrudeBufferGeometry has very few polygons I have an SVG with a simple rectangle (as a path though), which I load it on my app using THREE.SVGLoader like this : https://threejs.org/examples/#webgl_loader_svg, and using this code :
            const paths = paths_.paths
            const geometry = new THREE.Geometry()

            for (let i = 0; i < paths.length; i++) {

                const path = paths[i]

                const shapes = path.toShapes(false)

                for (let j = 0; j < shapes.length; j++) {
                    const shape = shapes[j]

                    const shape3d = new THREE.ExtrudeBufferGeometry(shape, {
                        depth: 0.1,
                        bevelThickness: 2,
                        bevelSize: 1.5,
                        bevelSegments: 5,
                        bevelEnabled: true
                    });

                    const edgeGeometry = new THREE.Geometry().fromBufferGeometry(shape3d)

                    geometry.merge(edgeGeometry)
                }
            }

            geometry.computeFaceNormals()
            geometry.mergeVertices()
            geometry.computeVertexNormals()

            geometry.center()

            return geometry

I create a geometry and create a 3d mesh out of it.
The problem is that the ExtrudeBufferGeometry uses (I think) Earcut triangulation in order to create the polygons that will make up the shape of the paths, and because of this there are not many triangles ont he top and bottom faces of my mesh.
And I need many faces there because I want to bend the mesh using this library https://github.com/drawcall/threejs-mesh-modifiers but that is not going to be nice without the many faces as you can see in the image below :

I tried SubdivisionModifier to add polygons but it didn't work because it created strange holes and artifacts (there is a comment inside this lib that the modifier will not work well with sharp edges).
I tried even using a CSG lib with which I was intersecting this extruded mesh with a BoxGeometry mesh with many segments and it worked but it was too creating holes and artifacts.
It seems that the THREE.ExtrudeBufferGeometry creates a geometry that doesn't have 100% proper normals.
In general I tried many things such as : flags, computing vertex normals, face normals, flat shading, smooth shading, changed all of the parameters of the ExtrudeBufferGeometry and nothing seems to be working.
Any help will be very  much appreciated!

A: Using this solution : intersecting meshes results to mesh with wholes I managed to use the manthrax version CSG library in order to intersect a specific box with my object and get back an object with added polygons on top and bottom :