text:
Q: Django admin limit model from foreign key I have the following model setup:
The problem is that when I try to pull the object up in the admin page, computer_names links to several hundred thousand rows that aren't relevant and the page never loads. How can I filter computer_names to only the user selected objects for the ManyToMany field?
class ScoringException(models.Model):
    class Meta:
        ordering = ['date_modified']
    requester = models.CharField('Requester',max_length=50,null=False,blank=False)
    computer_names = models.ManyToManyField(Computer)
    domain = models.ForeignKey(Domain)
    exception_kpi_types = models.ManyToManyField(ScoringType)
    expiration_date = models.DateField('Expiration Date')
    reason = models.CharField('Reason',max_length=1000,null=False,blank=False)
    approved = models.BooleanField('Approved')
    date_modified = models.DateTimeField('Date Updated',auto_now=True)

A: You can use raw_id_fields in the admin so that Django doesn't render the hundred thousand rows of data:
@admin.register(ScoringException)
class ScoringExceptionAdmin(admin.ModelAdmin):
    ....
    raw_id_fields = ['computer_names']

With raw_id_fields, Django will display the list of ids for selected m2m objects. A search button is also added to make adding new objects for the m2m relationship easier.
See the documentation for more information.


text:
Q: PyQt QTabWidget Multiple Corner WIdgets I want to remove the actual Close, minimize and maximize buttons of a window and create my own custom buttons, just like in chrome. I therefore want to add corner widgets to my tabwidget. Is there a way so that I can add three buttons as corner widgets of a QTabWidget?
Is it somehow possible to achieve using the QHBoxLayout ?
The setCornerWidget function just takes one widget as its input.

A: *

*Add a generic QWidget as the corner widget.

*Give it a QHBoxLayout.

*Add your buttons to the layout.

I use this frequently, often by subclassing QTabWidget and creating accessor functions that return the individual buttons. Adding signals like buttonClicked(int) with the index and buttonClicked(QAbstractButton) with the button itself are helpful, too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a makefile from a C program? Hiya, as part of an assessment I have to hand in a code which requires a few non-standard libraries.  In order to save submitting the header files and the code I would like to form a 'makefile' with the code and required add-ons sort of 'bundled' together.  I have absolutely no idea idea how to go about doing this though and any suggestions would be greatly appreciated!

A: A makefile does not look to be what you are looking for. You cannot bundle things into a makefile. Think of a makefile as a file accompanying your source and header files that will contain the recipe. It will tell how to build your program using all the other files.

A: Without knowing specifics, I can only point you in the right direction. This site, although not very pleasing to the eye, is fairly easy to understand:
Makefile Tutorial
This is the GNU manual page for 'make'

A: Just package your source code and list the requirements in a description somewhere.
For example:

To use my program you need the curses library.

Let the responsability of getting/installing/configuring the required libraries be with the user of your source.


text:
Q: Take second word in input I'm trying to make a calculator to help me with physics homework. For this, I'm trying to make it separate input into two parts, so typing "wavelength 18" would split it into "wavelength" and "18" as a numeric value.
I understand to get the first word that I can use
   String variable = input.next();

But is there a way to read what comes after the space?
Thanks.

A: String[] parts = variable.split(" ");
string first = parts[0];
string second = parts[1];

A: String entireLine = input.nextLine();
String [] splitEntireLine = entireLine.split(" ");
String secondString = splitEntireLine[1];

A: Assuming that you also might have three words or just one, it is better not to rely on arrays. So, I suggest to use List here:
final String inputData = input.next();
//Allows to split input by white space regardless whether you have
//"first   second" or "first second"
final Pattern whiteSpacePattern = Pattern.compile("\\s+");
final List<String> currentLine = whiteSpacePattern.splitAsStream(inputData)
.collect(Collectors.toList());

Then you can do a variety of checks to ensure you have correct number of values in the list and get your data:
//for example, only two args
if(currentLine.size() > 1){
   //do get(index) on your currentLine list
 }


text:
Q: Can i generate a class automatically on method call? I have created an extended method for DataTable. I want to generate a class automatically in my solution when i call that method while writing a code as Visual studio does when it doesnt find the method.
e.g mytable.mymethod(); Generate a class
Is there any way i can achieve this?

A: There are two ways to dynamically create a class:
Reflection.Emit and CodeDom.
Second one is not recommended because it will create a new assembly and load it which can cause Memory-Leak-like problems.
You can also achieve some of the features using dymanic.

A: You'd have to write a Visual Studio plugin, detect when you've used a method that doesn't exist and generated it. Or use an existing plugin like ReSharper which will make it easier to generate the method you're calling.


text:
Q: asp.net Core MVC 2 - configure CORS to accept NULL origin I need to configure a web api implemented using asp.net core 2.2 to accept a "null" origin ('Origin' header missing or empty).
Before you jump down my throat: I know that having a null origin is bad. But there's unfortunately nothing I can do about it, because the call is made by a third party server that passes a null origin and I have no control over it, so I need to make my api accept a null origin.
I tried doing this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHsts();
    app.UseMvc();
    app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
}

...

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    //Configuring CORS
    services.AddCors();
}

but it doesn't make any difference. When I make a POST request (using jQuery's ajax method), I get the following error:

I have the suspicion that a null/missing origin is just discarded before even checking it... am I right? Is there any way to accept a null origin?

A: The CORS middleware must be placed before the MVC middleware, or the MVC middleware (and your controller) will send the response without allowing the CORS middleware a chance to run.
Change your configure method to this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHsts();
    app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
    app.UseMvc(); // Add this middleware last.
}

The order of AddMvc and AddCors in the ConfigureServices method does not matter.

A: Ok, I solved it. The problem was very simple: the UseCors() and AddCors() methods in the Startup class must be called BEFORE the UseMvc() and AddMvc() methods.


text:
Q: Accessing Firebase with 'user authentication' active using Powershell I have created a client side app using JavaScript connected to a Firebase database where a user can login and save/edit some data stored Firebase. 'Email and Password' authentication is used as https://www.firebase.com/docs/web/guide/login/password.html
I subsequently wanted to write a Powershell script which would be setup with 'Task Scheduler' to run 1x per day, read each users data and execute some business logic.
I incorrectly expected to be able to whitelist my Server IP to get full access rights to the DB.
If I understood it correctly I need to use 'Custom authentication' using 'JSON Web Tokens (JWTs)', but there are no helper libraries available for Powershell. Had a look at this section https://www.firebase.com/docs/web/guide/login/custom.html#section-tokens-without-helpers but it's not clear to me what needs to be done to get the token.
Can someone give me some pointers or sample code on how to get JWT to work with Firebase/Powershell, or some alternate ways I can get full access to the BD using Powershell?
Thanks in advance
Quintus

A: I did something that might help you ...
#region TokenGenerator

function TokenGeneretor($secret){

$asm = [Reflection.Assembly]::LoadFile("D:\Firebase\FirebaseTokenGenerator.dll")
$tokenGenerator =  [Firebase.TokenGenerator]::new("$secret")
$authPayload = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.Object]"
$authPayload.Add('uid', '1')
$authPayload.Add('some', 'arbitrary')
$authPayload.Add('data', 'here')
$Option = [Firebase.TokenOptions]::new(((Get-Date).AddHours(1)),$null,$true)
$token = $tokenGenerator.CreateToken($authPayload, $Option)

return $token

}

#endregion

TokenGeneretor -secret "123"
The DLL mentioned is the code compiled from https://github.com/firebase/firebase-token-generator-dotNet. Just open the project in Visual Studio and have it compiled. It will play the DLL in the project's DEBUG folder.


text:
Q: PHPUnit × Mockery | add @runInSeparateProcess @preserveGlobalState disabled , but the class already exists error is still not resolved I would like to mock static method.
Here is the method to be tested.
Use App\Model\MyModel

class User extends Model
{
    public static function search($id)
    {
        try {

            User::toDo($id);
        } catch (\Exception $e) {

            MyModel::staticMethod('test', ['foo' => 'bar']);
        }
    }

I would like to mock MyModel and test that staticMethod() is called once.
So I mocked the following.
    public function search_test($id)
    {
        $mock = \Mockery::mock('overload:'. \App\Model\MyModel::class);
        $mock->shouldReceive('staticMethod')->once();

        User::search($id);
    }

The result was
 Mockery\Exception\RuntimeException: Could not load mock App\Model\MyModel , class already exists
So I added
  * @runInSeparateProcess
  * @preserveGlobalState disabled

, but still the class already exists error is not resolved.
There is no place in the UserModel where the new MyModel, but where should I check?
Thank you in advance.


text:
Q: Is it possible (and how) to load SVG string in Phaser 3 instead of loading it from path/url? I have several SVGs in my code which I would like to use with Phaser (specifically for particles) without saving them into separate SVG files.
const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M24 10h-10v-10h-4v10h-10v4h10v10h4v-10h10z"/></svg>`;

function preload()
{
    // Usual way
    this.load.svg('plus', 'assets/svg/plus.svg');

    // What I would like to do
    this.load.svg('plus', svgString)
}

Is there a way to achieve this (and how)?

A: Question was answered on Phaser 3 forum - https://phaser.discourse.group/t/is-it-possible-and-how-to-load-svg-string-in-phaser-3-instead-of-loading-it-from-path-url/9668
const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M24 10h-10v-10h-4v10h-10v4h10v10h4v-10h10z"/></svg>`;

function preload()
{
    const blob = new Blob([svgString], { type: 'image/svg+xml' });
    const url = URL.createObjectURL(blob);

    this.load.svg('plus', url)
}


text:
Q: PyAudio. How to record while playing sound I used PyAudio for recording and sounding.
Both can work respectively, but I couldn't record while sounding.
It always first sound and record or record and sound.
I tried thread but did not work.

A: You could try the playrec() function from http://python-sounddevice.rtfd.org/.
import sounddevice as sd
myrecording = sd.playrec(myarray, samplerate, channels=2)


text:
Q: Many - To - Many field changes - Too many api calls Using Django, I'm encountering the known issue with the Many-to-Many field. In the post_save_event signal/hook, the value in the Event instance for the many-to-many field: categories does not get updated with the most recent values submitted on the admin form. It always shows the old values.
This is my save hook where I have a parent "Event" and each event has a field for 0 or many categories. However, the instance.categories value is not updated with most recent value.
@receiver(post_save, sender=Event)
def post_save_event(sender, instance, **kwargs):
 success = events_api.create_or_update_event(instance)

I'm aware of why this happens. Basically, the many-to-many field needs to save after the parent model because the many-to-many table needs to have the primary key of events.
I did the fix that i found online below. This is the signal that gets sent after the many-to-many table transaction is committed.
This sort of works as a workaround but obviously this means that if the categories change on the event, the api gets called multiple times, even worse the m2m_changed signal seems to fire twice when it happens. So I end up calling the api 3 times for one update.
Any work around/ hook i can use to maybe just do this after a successful form save instead of the post_save event?
def category_has_changed(sender, **kwargs):
 logger.error("Inside: Inside category has changed")
 instance = kwargs.pop('instance')
 success = events_api.create_or_update_event(instance)

m2m_changed.connect(category_has_changed, sender=Event.categories.through)

Relevant part of the events_api:
def _create_or_update_event(event, mode):
    response = None
    try:
        headers = get_api_headers(event.cms_event_id)

        categories = []
        for cat in event.categories.all():
            categories.append(cat.id)
        # ISSUE: event.categories.all() does not contain the most recent updated array of categories

        # Basic event details.
        body = {
            'cms_event_id': str(event.cms_event_id),
            'categories': categories,
        }
        requests.post(ENDPOINT_CREATE_EVENT, json=body, headers=headers)

Models:
class Category(models.Model):
    name_en = models.CharField(
        _('Category name (English)'),
        blank=True, null=True, max_length=200,
        help_text=_('''
        Helpful details (for English language customers) about where the workshop is taking
         place, such as the location inside the store (ex. 2nd floor cafeteria).
        '''))
    name_fr = models.CharField(
        _('Category name (French)'),
        blank=True, null=True, max_length=200,
        help_text=_('''
        Helpful details (for English language customers) about where the workshop is taking
         place, such as the location inside the store (ex. 2nd floor cafeteria).
        '''))

    def __str__(self):
        return self.name_en

    class Meta:
        ordering = ('name_en',)
        verbose_name_plural = _('Categories')

class Event(Page):
    formfield_overrides = {
        models.ManyToManyField: {'widget': CheckboxSelectMultiple},
    }
    super_manager = models.Manager()

    ...

    categories = models.ManyToManyField(blank=True, null=True, to='Category')

A: I was able to modify my save_model in my modelAdmin like so
class EventAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
    obj.new_categories = form.cleaned_data.get('categories')
    obj.save()

    super().save_model(request, obj, form, change)

Then in signals.py i have it as part of the instance:
instance.new_category


text:
Q: interpolate data to triangular mesh There are a lot of questions (and answers) available for people interpolating unstructured data to structured output. solutions to which include mesh grid or bivariate splines. However I'm looking for the inverse. How do I interpolate structured data to an unstructured (delaulany) triangular  (quickly)?
The data i have are loaded with meshio as part of the pygmsh.
import meshio as mio
data = mio.read(fname)

data.cells['vertex'].shape
Out[128]: (2906, 1)
data.cells['triangle'].shape
Out[129]: (213898, 3)

plt.figure()
plt.tripcolor(data.points[:, 0], data.points[:, 1], -data.points[:, 2])
plt.triplot(data.points[:, 0], data.points[:, 1], 'k.', ms=2)

shows the below plot .  I have new data that I'm trying to update on this triangular mesh.  I was planning on interpolating the values of the regularly structured data to the same points in space, then updating the values of the triangular mesh.

A: The closest thing I've found to this is Python: interpolating in a triangular mesh
Working off of that answer and expanding with examples.
newBathy['lon'].shape
Out[154]: (1040, 271)
newBathy['lat'].shape
Out[155]: (1040, 271)
newBathy['elevation'].shape
Out[156]: (1040, 271)
#I have to flatten so i don't get a shape error
triObj = tri.Triangulation(newBathy['lon'].flatten(), newBathy['lat'].flatten())
ftri = tri.LinearTriInterpolator(triObj, newBathy['elevation'].flatten())
newZs = ftri(data.points[:, 0], data.points[:, 1])

This leaves me with data only in a small portion of the known domain, but i can updated the non-masked values in the newZs from those of the data.points([:,3]).  Haven't quite figured out the best way, as the cubic interpolation takes a while and makes my computer sound like a spaceship.  The linear clearly works, but could be nicer looking.


text:
Q: How do I create a huxtable table caption using bookdown in rmarkdown? I have numerous huxtable tables in my rmarkdown.  I'd like to caption them using bookdown.  So far I've been unable to do this using the bookdown instructions for "other R packages to generate tables" (see URL above).
Here's an example which follows the instructions in this answer:
---
title: "huxtable-mwe"
site: bookdown::bookdown_site
output:
  bookdown::html_book
documentclass: book
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(huxtable)
library(magrittr)
```

See table \@ref(tab:bar).

Table (\#tab:foo): Foo

```{r foo, echo=FALSE}
ht <- hux(
  foo = c('foo','bar')
) %>%
  set_all_borders(1)
ht
```

See table \@ref(tab:foo).

Table (\#tab:bar): Bar

```{r bar, echo=FALSE}
ht <- hux(
  foo = c('bar', 'baz')
) %>%
  set_all_borders(1)
ht
```

References work, but I get the following table captions:
Table (#tab:foo): Foo
Table (#tab:bar): Bar
when I expected:
Table 1: Foo
Table 2: Bar
Grateful for a MWE.

A: Resolved.  Use set_caption(...) to get the caption into a <caption>...</caption> element, and don't escape the label:
---
title: "huxtable-mwe"
site: bookdown::bookdown_site
output:
  bookdown::html_book
documentclass: book
---

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

See table \@ref(tab:bar).

```{r foo, echo=FALSE}
ht <- hux(
  foo = c('foo','bar')
) %>%
  set_all_borders(1) %>%
  set_caption('(#tab:foo) Foo')
ht
```

See table \@ref(tab:foo).

```{r bar, echo=FALSE}
ht <- hux(
  foo = c('bar', 'baz')
) %>%
  set_all_borders(1) %>%
  set_caption('(#tab:bar) Bar')
ht
```


text:
Q: jQuery .slideToggle() to also close other tabs I have two sections, each with 3 divs, opening on slideToggle. How can I close the other 2 divs in each section when 1 is open?
https://jsfiddle.net/koteva/mdx20uqe/2/

Location

grjryjj

JERSEY

  ighlgkiuluil

details

fykyuk

Location2

grjryjj

JERSEY2

  ighlgkiuluil

details2

fykyuk

A: With your jsFiddle, you could replace all your js code with
$('h2').click(function(event){
    var $this = $(event.target),
        id = $this.attr('id');

    if($('#'+id+'t').is(':visible')){ // To not slide up and down if clicking an already open element.
        $this.parent().children('div').slideUp();
    } else {
        $this.parent().children('div').slideUp();
        $('#'+id+'t').slideToggle();
    }
});

as seen in this jsFiddle. This hides the content inside the same stage when you click a header, assuming you follow the same naming convention throughout your entire html code.
I would however recommend, if you can, to perhaps clean up your html a little.

Look at this jsFiddle for an example.
Unless your code has to have your current structure, I would recommend refactoring it into using similar classes and as such be able to write cleaner code.
$('.header').click(function(event){
    var $this = $(event.target);
    $this.siblings().slideToggle();
    $this.parent().siblings().children('.content').slideUp();
});

Would with the structure in the jsFiddle html provide you with the functionality you want.

A: If you want to do it in simple way. You can do it as follows. its just one function written. But it is simple and line of code will be increased
$( "#details-2" ).click(function() {
     $( "#location-2t").hide( "slow");
     $( "#jersey-2t").hide( "slow");
     $("#details-2t").show("slow");
});

For more complex div structure and the Ids are in the same format as you have specified in your sample code following code will be very useful.


text:
Q: Vue js Webpack error - Uncaught TypeError: Vue.directive is not a function Need help in fixing the below error :

Vue.directive is not a function

I am using Vue Webpack boilerplate https://github.com/vuejs-templates/webpack for my front-end project.
Here is the structure of the project:

I am getting the following error
[HMR] Waiting for update signal from WDS...
webpack-internal:///./src/helpers/directives.js:1 Uncaught TypeError: Vue.directive is not a function
    at eval (webpack-internal:///./src/helpers/directives.js:1)
    at Object../src/helpers/directives.js (app.js:4759)
    at __webpack_require__ (app.js:708)
    at fn (app.js:113)
    at Object.eval (webpack-internal:///./src/bootstrap.js:44)
    at eval (webpack-internal:///./src/bootstrap.js:142)
    at Object../src/bootstrap.js (app.js:4568)
    at __webpack_require__ (app.js:708)
    at fn (app.js:113)
    at eval (webpack-internal:///./src/main.js:22)
webpack-internal:///./node_modules/vue/dist/vue.esm.js:9075 Download the Vue Devtools extension for a better development experience:
https://github.com/vuejs/vue-devtools
webpack-internal:///./node_modules/vue/dist/vue.esm.js:9086 You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html

helper\directives.js
Vue.directive('click-outside', {
    bind: function (el, binding, vnode) {
      el.event = function (event) {
        // here I check that click was outside the el and his childrens
        if (!(el === event.target || el.contains(event.target))) {
          // and if it did, call method provided in attribute value
          vnode.context[binding.expression](event)
        }
      }
      document.body.addEventListener('click', el.event)
    },
    unbind: function (el) {
      document.body.removeEventListener('click', el.event)
    }
  })


text:
Q: Adding a space before a character in a string C++ insert function I am attempting to add space before a character in a string by using the insert function.
Can someone kindly explain why the following code does not work ?
for(int i = 0; i < line.length(); i++)
{
   if(line[i+1] == '=')
   {
      line.insert(i, " ");
   }
}

A: If you want to insert before = you can get the index of = directly and not the index of char followed by =. This could lead to out of bounds access.
Also, when you insert the space you extend your string by 1, that's ok but only if you also adjust the counter i, otherwise it will insert again and again and again before = resulting in infinite loop. Adjust your code in this manner:
for (int i = 0; i < line.length(); i++)
{
    if (line[i] == '=')
    {
        line.insert(i++, " ");
    }
}

A: The code seems fine except for one little detail:
Imagine you have a string with "test=something". When you iterate it, when i is 3 you will find the next character is an equals, so you put a space into it. Next iteration i will be 4, but you just added a space, so at i equals 5 there's the same equals sign. So you put another space and so on. TO fix this youy can try:
std::string line = "test=something";
for (int i = 0; i < line.length(); i++)
{
    if (line[i + 1] == '=')
    {
        i++;
        line.insert(i, " ");
    }
}


text:
Q: Linear programming with parameters I am trying to run LinearProgramming with a vector and a matrix that depend on some parameters, but it's not working. The message I get is that my code "contains elements that are empty matrices, invalid vectors or matrices, or not real numbers". I suppose the problem is that Mathematica doesn't know that my entries are real because of the parameters. I'd rather not specify values. Here is my code:
α := -{0, -1152  c k^3 π^2,
576  c k^3 π, -13824 k^4 π^3,
576  k^4 π^2 (12 + c π), -24  k^4 π (288 +
   c π (48 + c π)), -864 c k^3 - 72 c^2 k^3 π -
 2 c^3 k^3 π^2,
k^4 (10368 + c π (36 + c π) (72 + c π)) };

G := {{0, 0, 0, -8 k π^4 + 64 π^5 q^2,
4 k π^3 - 32 π^4 q^2, -4 k π^2 + 48 π^3 q^2, 0,
6 k π - 96 π^2 q^2}, {0, 8  π^2, -4  π,
0, -4  k π^3, 8 k π^2 - 48 π^3 q^2,
6, -18 k π + 144 π^2 q^2}, {0, 0, 0, 0,
0, -2 k π^2 + 16 π^3 q^2, -6,
9 k π - 48 π^2 q^2}, {0, 0, 0, 0, 0, 0, 2, -k π}};

$Assumptions = ({c, k, q} ∈ Reals)

LinearProgramming[α, G, {0, 0, 0, 0}, -Infinity]

I tried Refine, Assumptions, but none worked. What else can I do?


text:
Q: Why is the floor in my raycaster seemingly "misaligned"? I have been working on a doom/wolfenstein style raycaster for a while now. I implemented the "floor raycasting" to the best of my ability, roughly following a well known raycaster tutorial. It almost works, but the floor tiles seem slightly bigger than they should be, and they don't "stick", as in they don't seem to align properly and they slide slightly as the player moves/rotates. Additionally, the effect seems worsened as the FOV is increased. I cannot figure out where my floor casting is going wrong, so any help is appreciated.
Here is a (crappy) gif of the glitch happening
Here is the most relevant part of my code:
void render(PVector pos, float dir) {
    ArrayList<FloatList> dists = new ArrayList<FloatList>();

    for (int i = 0; i < numColumns; i++) {
      float curDir = atan((i - (numColumns/2.0)) / projectionDistance) + dir;

      // FloatList because it returns a few pieces of data
      FloatList curHit = cast(pos, curDir);

      // normalize distances with cos
      curHit.set(0, curHit.get(0) * cos(curDir - dir));
      dists.add(curHit);
    }

    screen.beginDraw();

    screen.background(50);
    screen.fill(0, 30, 100);
    screen.noStroke();
    screen.rect(0, 0, screen.width, screen.height/2);

    screen.loadPixels();

    PImage floor = textures.get(4);

    // DRAW FLOOR
    for (int y = screen.height/2 + 1; y < screen.height; y++) {
      float rowDistance = 0.5 * projectionDistance / ((float)y - (float)rY/2);

      // leftmost and rightmost (on screen) floor positions
      PVector left = PVector.fromAngle(dir - fov/2).mult(rowDistance).add(p.pos);
      PVector right = PVector.fromAngle(dir + fov/2).mult(rowDistance).add(p.pos);

      // current position on the floor
      PVector curPos = left.copy();
      PVector stepVec = right.sub(left).div(screen.width);

      float b = constrain(map(rowDistance, 0, maxDist, 1, 0), 0, 1);

      for (int x = 0; x < screen.width; x++) {
        color sample = floor.get(floor((curPos.x - floor(curPos.x)) * floor.width), floor((curPos.y - floor(curPos.y)) * floor.height));

        screen.pixels[x + y*screen.width] = color(red(sample) * b, green(sample) * b, blue(sample) * b);

        curPos.add(stepVec);
      }
    }
    updatePixels();
  }

If anyone wants to look at the full code or has any questions, ask away.

A: Ok, I seem to have found a "solution". I will be the first to admit that I do not understand why it works, but it does work. As per my comment above, I noticed that my rowDistance variable was off, which caused all of the problems. In desperation, I changed the FOV and then hardcoded the rowDistance until things looked right. I plotted the ratio between the projectionDistance and the numerator of the rowDistance. I noticed that it neatly conformed to a scaled cos function. So after some simplification, here is the formula I came up with:
float rowDistance = (rX / (4*sin(fov/2))) / ((float)y - (float)rY/2);

where rX is the width of the screen in pixels.
If anyone has an intuitive explanation as to why this formula makes sense, PLEASE enlighten me. I hope this helps anyone else who may have this problem.


text:
Q: Why is my Firebase Authentication function not working anymore? I wrote this Fire Auth function a couple months ago, but when I tried it today, it returned me the following error:

ERROR TypeError: Cannot read property 'uid' of null

I can't seem to figure out where I went wrong because I haven't altered any of the code.
The user is successfully signed in according to the Firebase Console.
Code:
login.ts followed by login.html

import { Component } from '@angular/core';
import { IonicPage, NavController, ToastController, NavParams } from 'ionic-angular';

//Firebase imports
import { AngularFireAuth } from 'angularfire2/auth';

//Model import
import { User } from '../../models/user.interface';

//Page import
import { HomePage } from '../home/home';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  oldUser = {} as User;

  constructor(
    private afAuth: AngularFireAuth,
    public navCtrl: NavController,
    public navParams: NavParams,
    private toast: ToastController) {
  }

  async login(oldUser: User) {
    try {
      const result = this.afAuth.auth.signInWithEmailAndPassword(oldUser.email, oldUser.password);
      if (result) {
        this.navCtrl.setRoot(HomePage);
        this.toast.create({
          message: `We're all given the same hours in a day. Are you ready to maximise yours?`,
          duration: 3000
        }).present();
      }
    }
    catch(e) {
      this.toast.create({
        message:   `Let's try again: ` + `${e}`.substr(7),
        duration: 2000
      }).present();
    }
  }
}
    <div class="list">
      <ion-item>
        <ion-input class="title" type="email" placeholder="Email Address" [(ngModel)]="oldUser.email"></ion-input>
      </ion-item>

      <ion-item>
        <ion-input class="title" placeholder="Password" clear-input type="password" [(ngModel)]="oldUser.password"></ion-input>
      </ion-item>
    </div>

    <button ion-button (click)="login(oldUser)">LOGIN</button>

Please help!! Thank you!

A: u need to check if the user exist 1 then do yourlogic
 let user = this.fireAuth.auth.currentUser;
    if (user != null) {
      currentUser.id = user.uid;
      currentUser.email = user.email;
      // login logic ...
    }

more info here


text:
Q: Report on duty or Report for duty?
I have to report on duty on 22th December 2014.

It should be on or for?
If that day I have attend, I have report to someone that I have on duty that day.

A: You "report FOR duty". Once you have done so, you may be "ON duty". For example, "I have to report for duty on 22 December. Then I will be on duty until 15 March."
Note that in "report for duty", we often, as in your example, give a date, and that date is preceded by "on". So if it wasn't necessary in context to say "for duty", you could say "report on", as in, "I have to report on 22 December."
"Report on" can also mean that you are presenting information about some subject. Like, "At the committee meeting, Jack reported on new product development and Sally reported on the results of the recent advertising campaign."
The meanings and definitions of prepositions in English can be muddled. I think in many cases you just have to memorize which prepositions are used in which context. In this case, I suppose you could say that "on" normally means either "sitting atop", as in, "The book is ON the table", or "about", as in, "This is a book on ancient history." "For" means "in favor of", as in, "Senator Jones is for the new tax bill", or "for the purpose or benefit of", as in, "I work for money" or "I quit smoking for my wife."
In this case, we say "reporting for duty" in the sense that the reason why you are reporting is to perform your duty, so it sort of makes sense.

A:
I have to report for duty on 22 DEC.

Means you have Duty scheduled for 22 DEC and have to show up.

I have to report on duty.

Implies that you have to make a report of some kind while on duty.  "I have to report the number of visitors while on duty tomorrow."


text:
Q: How to obtain same left and right margin on a card with list items I'm building  a card with some items and i need to align to the right the items with texts 3576000 (plus KG icon), 120/180, and 67%. Seems that i'm doing somethig wrong, the left margin is narrow than right margin of card,
<div id="app">
<v-app id="inspire" fluid>
    <v-card>
        <v-list>
            <v-list-item>
                <v-list-item-content>
        <v-list-item-title class="headline">UNLOADED TRUCKS</v-list-item-title>
                </v-list-item-content>
      <v-btn icon>
        <v-icon color="primary">mdi-refresh</v-icon>
      </v-btn>
            </v-list-item>
            <v-list-item>
      <v-list-item-content>
        <v-list-item-icon>
          <v-icon color="black" size=80>mdi-truck-check</v-icon>
        </v-list-item-icon>
      </v-list-item-content>
      <v-list-item-content>
        <v-list-item class="py-n5 my-n5">
          <v-list-item-title align="right" class="px-n3 mx-n3">3576000</v-list-item-title>
          <v-list-item-icon>
            <v-icon color="black">mdi-weight-kilogram</v-icon>
          </v-list-item-icon>
        </v-list-item>
        <v-list-item>
          <v-list-item-title align="right" class="display-2">120/180</v-list-item-title>
        </v-list-item>
        <v-list-item class="py-n5 my-n5">
          <v-list-item-subtitle align="right">67%</v-list-item-subtitle>
        </v-list-item>
      </v-list-item-content>
    </v-list-item>
    <v-progress-linear value=67></v-progress-linear>
            <v-list-item class="py-n2 my-n2">
      <v-list-item-icon class="px-0 mr-1">
        <v-icon>mdi-clock</v-icon>
      </v-list-item-icon>
      <v-list-item-subtitle>Updated 19 minutes ago</v-list-item-subtitle>
            </v-list-item>
    <v-divider></v-divider>
            <v-card-actions>
      <v-btn text color="primary">Full Report</v-btn>
    </v-card-actions>
        </v-list>
    </v-card>
</v-app>

sample is in https://codepen.io/wolverine4277/pen/ZEGBBze, and image show the differents margins is attached. I can't figure out how correct that, i try  between  and nothing change...
enter image description here

A: The left and right margins of the card are okay. The issue is with the padding and margins of the list items.
If you wrap the "v-list-item-icon" with v-list-item giving it the same class (py-n5 my-n5" then it would appear fine
<v-list-item class="py-n5 my-n5">
    <v-list-item-icon>
        <v-icon color="black" size=80>mdi-truck-check</v-icon>
    </v-list-item-icon>
</v-list-item>


text:
Q: Can't Reindex Catalog Search: 405 Not Allowed (Magento 2.4) My Catalog Search needs reindexing, but sudo bin/magento indexer:reindex catalogsearch_fulltext won't work and returns the following:
Catalog Search index process unknown error:

<title>405 Not Allowed</title>

405 Not Allowed

nginx/1.16.1

I've seen other questions with a similar issue to mine, but none with this particular error. My Magento is using Elasticsearch 7.
EDIT: I deleted one product and tried again, and got the following error:
Catalog Search index process unknown error:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Error</title>

Cannot PUT /magento2_product_1_v1

A: The only solution to prevent this exception from appearing in the current version of Magento 2 till the date, is to use only an officially supported version of Elasticsearch (6.x or 5.x).
Elasticsearch 7.x is not supported by magento, the exception will appear everytime you rebuild the search indexes.


text:
Q: QueueDequeue step is a significant bottleneck in Tensorflow code I've seen a few other questions regarding the dequeueing step causing a bottleneck but I have tried many of those suggestions without any success:

*

*I am using multiple threads based on cpu count

*I have tried with small batches (of 100) and larger batches (of 1000)

*I have tried switching to the shuffle_batch_join and batch_join

None of these things seem to be helping the overall time. Also the extent to which the Dequeue step is causing a bottleneck in my code seems much worse than what others have experienced. When you look at the timeline all of the other steps practically disappear in comparison. I am wondering if this is partially from using BigQuery and the BigQueryReader as my source although with other people also experiencing a slowdown I am assuming it isn't the only cause.

I'm not entirely sure how to properly interpret this chart but it doesn't seem like the the problem is being caused by a completely empty queue.

Additional info

*

*Capacity is set to batch size * 10

*min after dequeue is set to batch size * 2 + 1

*enqueue many is set to true

Does anyone have any thoughts on what else I might be able to try to speed things up while still using bigquery as the source of my data?


text:
Q: Kendo Grid Date is null for 13/06/2015 all dates after 12 My grid:
@(Html.Kendo().Grid<IBATechnologies.IBA.Web.Models.AssetTransactionDetailViewMod    el>()
    .Name("transactionGrid")
    .Pageable()
    //.Editable(editable=>editable.Mode(GridEditMode.InLine))
    .Columns(colums =>
    {
        colums.Bound(p => p.assetCode).Width(100);
        colums.Bound(p => p.assetDesc).Width(100);
        colums.Bound(p => p.remark).Width(100);
        colums.Bound(p => p.currencyCode).Width(100);
        colums.Bound(p => p.rate).Width(100);
        colums.Bound(p => p.currencyRate).Width(100);
        colums.Bound(p => p.lcyAmount).Width(100);
        colums.Bound(p => p.documentDate).Width(100);
        colums.Command(command => { command.Destroy(); }).Width(100);
    })
    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .ServerOperation(false)
        .Model(model => model.Id(p => p.assetCode))
        .Create(update => update.Action("TransactionDoc_Create", "AssetTransaction"))
        .Read(read => read.Action("TransactionDoc_Read", "AssetTransaction", new { docno = 0 }))
        .Update(update => update.Action("BrandEditingPopup_Update", "AssetTransaction"))
        .Destroy(update => update.Action("BrandEditingPopup_Destroy", "AssetTransaction"))
    )
)

My grid is shown above. When I try to edit, all the dates after 12 are returned as null. Please help me.

A: <script   src="@Url.Content("~/Scripts/kendo/2015.1.429/cultures/kendo.culture.en-GB.min.js")"></script>
<script>
   kendo.culture("en-GB");
</script>

A: This appears to be a culture issue.  Try changing your Kendo UI culture (by including one of the other culture JS files.  You may also need to change the culture on the server


text:
Q: Calculation of Confidence Interval We randomly choose 1000 people and run a survey on whether they prefer Apples or Berries. The results are $71\%$ for Apples and $29\%$ for Berries.
We want to calculate the Margin of error of the poll, with confidence level $90\%$.
My attempt, as I have just started to study probability and statistics (out of personal interest - I am not a student):
For confidence level of $90\%$, we get the value of $z = 1.645$.
So the MOE is $z*\sqrt{\frac{p(1-p)}{n}} = 1.645*\sqrt{\frac{0.71(0.29)}{1000}} = 2.36\%$?
Thank you!

A: Yes, it is correct. The Moe is $\pm 2.36\%$ in the sense that the confidence interval at $90\%$ is
$$(71 \pm 2.36) \%$$ for apples and
$$(29 \pm 2.36)\%$$ for berries
If you want to type % you have to type $\text{\%}$ otherwise the symbol will not appear.


text:
Q: What is the fastest way to get the current time in C++11? Context:
I'm writing a high performance C++11 application, one part of it is to remove inactive connections. For that, I'm storing a "last activity" timestamp in my connection object, which I update when an action is taken. I then have a timer which runs every few seconds, loops over all sessions, and removes inactive ones.
Currently I'm using this code to get the current timestamp:
timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count()

I'm wondering if there is any faster way to do it? By faster I mean the performance of getting the timestamp itself, not the resolution of the timestamp.
The resolution is not really important for my specific application, it could go as low as a second. Also, utc/local doesn't matter, I am only using the timestamp to compare it to other timestamps, accquired by the same method.
I would like to keep it cross-platform, but platform-specific optimizations with conditional compilation are also welcome.

A: If performance is really an issue, and accuracy isn't, then you might not need to use a timestamp at all. Rather just keep a counter for each connection, and whenever activity occurs for the connection, reset the counter to zero. Whenever your timer goes off, have it increment the counter for each connection, and disconnect any connection whose counter value rises above (N) (for whatever value of N you find works best)

A: You can maintain a thread local variable per thread, and add a timerfd per thread (or you can use select/epoll timeout parameter) to wake the thread every 1 millsecond, when the select/epoll_wait return, you call now() to get the timestamp, and save the timestamp to the thread local variable.
you can also use a global variable, for example, std::atomic, and update it when select/epoll (in any threads) return. If you still think it's a bottleneck, use a single thread with timerfd and update the timestamp every 1 millsecond.


text:
Q: make at lease one argument mandatory in flask restx reqparser from flask_restx import reqparse

parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('foo', type=int)
parser.add_argument('bar', type=int)

I am implementing search endpoint where user can specify /item?foo=f or /item?bar=b to serach items.
I tried raising exception but this just breaks the entire app. What is the correct exception need to raise to display bundled error to end user?
args = parser.parse_args()
if not args.foo or not args.bar:
    raise Exception ("Specify Foo or Bar in query string to search item")

A: If I get you correctly, what you need is to raise a werkzeug HTTPException with the correct status code. Flask abort helper can help you with that
Something along this lines
from flask import abort
abort(400, 'some error message')


text:
Q: Deployment Telerik.Web on IIS 6.0 When I deployment asp.net 4.0 web site on IIS 6.0 server I have error:
[TypeInitializationException: The type initializer for 'Telerik.Web.RenderModesCache' threw an exception.]
Telerik.Web.RenderModesCache.GetViewDescriptors() +0
Telerik.Web.UI.RadDataBoundControl.GetViewScriptReference() +81
Telerik.Web.UI.RadDataBoundControl.GetScriptReferences() +80
Telerik.Web.UI.RadDataBoundControl.System.Web.UI.IScriptControl.GetScriptReferences() +13
System.Web.UI.ScriptControlManager.AddScriptReferenceForScriptControl(List`1 scriptReferences, IScriptControl scriptControl) +41
System.Web.UI.ScriptControlManager.AddScriptReferencesForScriptControls(List`1 scriptReferences) +92
System.Web.UI.ScriptManager.RegisterScripts() +129
System.Web.UI.ScriptManager.OnPagePreRenderComplete(Object sender, EventArgs e) +122
System.Web.UI.Page.OnPreRenderComplete(EventArgs e) +8897866
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2716

web.config has next configuration:
<compilation debug="true" targetFramework="4.0">
  <assemblies>
    <add assembly="Telerik.Web.UI"/>
  </assemblies>
</compilation>

 <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
  <controls>
    <add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI"/>
  </controls>
</pages>

With IIS Express 7.0 the web site working correctly.
What may be cause of the problem?

A: Make sure you are not trying to use assemblies built against .NET 4.5 (Telerik provide those). If IIS6 is what your server has, it is, probably, Windows Server 2003 which does not have .NET 4.5. You should have your application(s) reference the .NET 4.0 builds of the Telerik assemblies (you can take them from the Bin40 folder of your installation).
As DanM said in the comments - make sure .NET 4.0 is installed if you are referencing the .NET 4 builds.


text:
Q: mysql select from where a condition is met My table structure is as follows
ProductID |  Image  | Default
1            1.jpg     N
1            2.jpg     Y
1            3.jpg     N
2            4.jpg     N
2            5.jpg     N
3            6.jpg     Y
3            7.jpg     N

I'm Trying to get a return of all producID where there is no default image 'N' , e.g. the above should return productID 2. Sorry no code attempt , as i'm not sure what to do at all.

A: Group by the product and select only those having none default=Y
select productID
from your_table
group by productID
having sum(`default` = 'Y') = 0

A: Try this:
SELECT t1.productID
FROM yourtable t1
WHERE NOT EXISTS(
    SELECT 'DEFAULT'
    FROM yourtable t2
    WHERE T2.productid = t1.productid
    AND T2.`default` = 'Y'
)

A: If default is a column in your database you can use:
Select * from mytabale where 'Default'='Y'

A: This SQL code does what you want:

SELECT productID FROM
    (SELECT productID, SUM(table.default = 'Y') AS Y_count
    FROM table
    GROUP BY productID) AS tbl
WHERE Y_count = 0


text:
Q: Плагин tickets не работает в MODX Revo, почему? знатокам.
Очередной вопрос по MODX Revo.
Понадобилась система комментирования на сайте и установил плагин tickets 1.9.4 последний.
Вместе с ним установился и Jevix (при установке "тикетс" был предложен выбор перезаписать Чанки тикетса, хз зачем и почему, но выбрал ничего не перезаписывать). Настроил в "контроль доступа" к группе users (ранее созданную) доступ к тикетсу. Все ок, вывожу тикетс в шаблоне так
[[!TicketComments? &allowGuest=`0` // гостям не нужно видеть форму]]

Но, появляется сама форма комментирования, оставляю коммент, нажимаю "написать" кнопку, страница перезагружается (хз должна ли или должен Ajax отрабатывать) и комента нет, в админке его тоже нет. В инете прочитал что почти у каждого такая проблема, кто-то знает как вылечить?
Ошибок никаких не заметил, jquery библиотека подключена внизу сайта, пробовал и в head, и отключать, не помогает. Сам Тикет не добавляет никакой js файл (вроде бы, по крайней мере библиотеку точно нет).

A: В общем, так и не нашел ответ на свой вопрос. Более того, куча народу имеют такие же траблы с этим плагином, но ответ никто не дал либо никто не разобрался.  Мучаться дальше не стал, удалил его к чертям собачим и появились ошибки в системе, удалились все ресурсы и еще много геморроя, спасибо Боже, что был бэкап. В общем ставьте сие компонент на свое усмотрение.
Но я не советую.

Лучше попробовать аналоги (quip, modxTalks...) Что, существуют только 3-4 плагина системы комментов для modx, серьезно?

A: Все знатоки(и создатель) сего плагина "сидят" на modx.pro, советовал бы вам там задать этот вопрос.
По комментариях кроме указанных там же можно найти: https://modstore.pro/packages/tag/%D0%BA%D0%BE%D0%BC%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%D1%80%D0%B8%D0%B8


text:
Q: 2d Kalman filter with acceleration I would like to implement a kalman filter in Python for some tracking software I'm working on. It is a 2D coordinate system using a single vector x for position, velocity and acceleration of x and y coordinates,

I am using the following update and predict method:
# UPDATE
y = Z - (H * x)
S = H * P * H.T + R  # residual convariance
K = P * H.T * S.I    # Kalman gain
x = x + K*y
I = np.matrix(np.eye(F.shape[0])) # identity matrix
P = (I - K*H)*P

# PREDICT x, P based on motion
x = F*x
P = F*P*F.T + Q

return x, P

Using other resources I have come up with the following state transition matrix and measurement matrix but am not sure how correct they are:
F = np.matrix('''
      1. 0. 1. 0. 0.5 0.;
      0. 1. 0. 1. 0. 0.5;
      0. 0. 1. 0. 1. 0.;
      0. 0. 0. 1. 0. 1.;
      0. 0. 0. 0. 1. 0.;
      0. 0. 0. 0. 0. 1.
      '''),
 H = np.matrix('''
      1. 0. 0. 0. 0. 0.;
      0. 1. 0. 0. 0. 0.;
      0. 0. 0. 0. 1. 0.;
      0. 0. 0. 0. 0. 1.'''),

Basically it doesn't work and makes my tracked path more jittery and I have no clue where I'm going wrong. Can anyone help?


text:
Q: How to deploy TensorFlow probability model I want to use structural time series models from the TensorFlow probability library to model my time series.
I'm not sure how to push the model into production so that it can run online.
My first idea is to split time series into a chunk (season) train model on this chunk, push the model into production and retrain model whenever new data arrive (same as Arima models).
Is it a good approach?
I will be very grateful for all hints.


text:
Q: Is it possible to use the WinRT from a non-metro application? Demos and articles I see online talk about Windows Runtime with Metro-style apps. Is it possible to use APIs with non-metro applications?

A: Just found a way on Jeffrey Richter's blog, Cool.

A: Real Native WinRT Development -


text:
Q: How to invalidate views for the current session in JSF? We have an application (Mojarra 2.3) where a user can change a global filter of the data it sees. When that happens, I want to keep the session, but invalidate the active views (which are server side).
I found this question which enables you to count the number of views: How do I count the number of views in a user's JSF session (JSF 2.2)?
Based on that I figured I could remove the attribute in which the views are stored. I came up with this method:
public static void invalidateViews() {
  final HttpSession session = Faces.getSession();
  List.of("com.sun.faces.application.view.activeViewContexts",
          "com.sun.faces.application.view.activeViewMaps",
          "com.sun.faces.renderkit.ServerSideStateHelper.LogicalViewMap",
          "org.jboss.weld.context.ConversationContext.conversations")
          .forEach(session::removeAttribute);
  Faces.redirect(Faces.getRequest().getRequestURL().toString());
}

The com.sun.faces.renderkit.ServerSideStateHelper.LogicalViewMap was mentioned in the linked question's answer. I kind of guessed that it would not hurt to remove the other attributes. The answer also mentions that it is Mojarra only.
It seems to work so far, but I would like to ask this: should one clear server side views like this? And, if so, how can I support MyFaces as well?

A:
It seems to work so far, but I would like to ask this: should one clear server side views like this?

Given that there is no standard API call for this, this is about the best you can do, yes. I have during the JSF 2.3 work requested for a more specific variant of this functionality to exist in the standard API because I needed to be able to destroy view scoped beans associated with a specific JSF view state (for the OmniFaces view scope unload functionality, see Hacks#removeViewState()). But this has unfortunately not yet been fleshed out because of difficulties with Portlets.

And, if so, how can I support MyFaces as well?

As seen in the OmniFaces Hacks helper class, the session attribute key for MyFaces 2.x is org.apache.myfaces.application.viewstate.ServerSideStateCacheImpl.SERIALIZED_VIEW and 4.x org.apache.myfaces.application.viewstate.StateCacheServerSide.SERIALIZED_VIEW.
By the way,

Faces.redirect(Faces.getRequest().getRequestURL().toString());

this is shorter:
Faces.refreshWithQueryString();


text:
Q: Running multiple short lived java applications from one application I have multiple monitoring applications which are cron scheduled and all these are managed through linux crontab scheduler.
I want to migrate all these to Quartz Scheduler so that it can be managed through one single application and based on their quartz cron, i will be invoking the underlying small application.
For such scenario, i want these small applications to run in a complete isolated environment so that they won't affect the other application which are scheduled by quartz.
I have found that Spring cloud task can support such thing but these apps are not spring based. They are simple java classes.
is there any other thing i can go with?


text:
Q: Let Visual Studio (2015) link headers and libraries for other computers I need a way to setup Visual Studio, in this case VS2015, to find some header files and libraries directly on a different computer. Because as it is now, I need to send a project to another person and the linking I have done on my computer won't be supported on that person's, as the include path is different. Is there a way to do this if I include a subfolder in the project with all the headers and libraries needed - something like "Include dir"?
Note: I found this thread, which seem to have a similar problem, but I couldn't get a straight answer out of it.


text:
Q: How to remove a comma in an output def calculate_average():

mylist = []

for i in range (10):
    input = int(input("Enter an integer: "))
    mylist.append(integer)

avg = sum(numbers) / len(numbers)

aboveavg = ([x for x in numbers if x > average])

print("\nThe average is:", avg)
print("Numbers greater than average:")
print(str(aboveavg).strip('[]'))

I get an output for the very last line where it has a comma. For example
Numbers greater than average:
14, 15

Instead of:
14 15

How to go about fixing the code? Do I use join? (something I haven't learned about in class yet)

A: You could use join, which concatenates a string before printing it:
print(' '.join(str(elt) for elt in aboveavg))

or a for loop where you print one element at a time on the same line:
for elt in aboveavg:
    print(str(elt), end=' ')

A: Yup, you should use str.join in this case. It is the built-in way to achieve this:
print(' '.join(map(str, aboveavg)))
# or:
print(' '.join([str(x) for x in aboveavg]))

It is important to note that you can only join str objects. You will have to convert the elements of the iterable you want to join to str. You can use either map or a comprehension to achieve that.

A: You can do this easily
print(" ".join([str(x) for x in aboveavg]))

A: Yes. Since the result is a list, you can create a string from a list by using join:
print (' '.join(map(str, your_list)))

A: No idea why everybody's joining...
print(*aboveavg)


text:
Q: changing the image src attr Looking for some direction with this.
At this current iteration, I have it where if a user clicks on an image thumbnail, the thumbnail image displays in a different div (the main div) and in doing so, it rewrites the main div img src attr *update: with the thumbnail img attr minus the "-thumbnail".  This part is good, or at least I believe it is.
With that said, after the user clicks on a thumbnail and the main div img appears, it lingers...and what I mean by lingers is that for example, if a user closes the div and re-opens it or another div just like it, the last image shows (stays) when it shouldn't in the main div.  Instead, it should be showing the first thumbnail img in the main div...
Any suggestions is appreciated and below is what I currently have (or at least a portion of it).  There is a lot more, but below is the main stuff that's giving me troubles...
*update: The HTML part is within a div class called "t_1".  I have 24 of these..."t_1", "t_2", "t_3" respectively.  And within this class, I have what is posted below in all using the same div classes.  The only difference is the folder names in the img tag.
So, when a user clicks on that thumbnail and that thumbnail image gets rewritten so that it can be displayed in the main div "t_main_screenshot", all is good...but then, if the user clicks out of the "t_1" etc. divs, and opens up another "t_2", that last image thumbnail that was clicked previously shows in the main div (t_main_screenshot) instead of the first image thumbnail for what should be in "t_2"...
Hopefully this is a bit better in clarity...It's kind of hard to explain.
HTML:

JS / JQuery:
$('.t_thumbnail').click(function() {
    $('.t_thumbnail').removeClass('active');
    $(this).addClass('active');

    var thumbNail = $(this).find('img').attr('src');

    $('.t_main_screenshot img').fadeOut(0, function() {
        $(this).fadeIn().css('animation','scale-in .75s ease-in 0s forwards')[0].src = thumbNail.replace('-thumbnail', '');
    });
});

A: Your question isn't clear, but I think you mean when the user clicks two times so quickly, you will see a flash...
That's because you're using .fadeOut() and .fadeIn()
So to fix this issue you can use .stop() method to stop the previous animation before starting the new one
More details: https://api.jquery.com/stop/

According to the question updates
Here is the problem: $('.t_main_screenshot img').fadeOut(0, function() {
You have to select the closest t_main_screenshot
Correct way:
$(this).closest('.t_thumbnail_wrapper')
       .siblings('.t_main_screenshot')
       .find('img').fadeOut(0

Let me know if this works...

A: $('.t_thumbnail').click(function() {
    $('.t_thumbnail').removeClass('active');
    $(this).addClass('active');

    var thumbNail = $(this).find('img').attr('src');
    var res = thumbNail.substring(1, thumbNail.indexOf("-"));
    res+=".jpg";

    $('.t_main_screenshot img').fadeOut(0, function() {
        $(this).fadeIn().css('animation','scale-in .75s ease-in 0s forwards')[0].src = res;
    });
});

A: Finally figured out the answer to this:
$('.t_thumbnail').click(function() {
    $('.t_thumbnail').removeClass('active');
    $(this).addClass('active');

    var thumbNail = $(this).find('img').attr('src');

    $(this).parent().parent().siblings().find('.t_main_screenshot').children('img').fadeOut(0, function() {
        $(this).fadeIn().css('animation','scale-in .75s ease-in 0s forwards')[0].src = thumbNail.replace('-thumbnail', '');
    });
});


text:
Q: cannot connect an SSL secured database to typeorm This is my first time using NestJS and I am having trouble connecting my Postgres database which is hosted on Digitalocean to NestJS.
I searched online for solutions and tried adding "ssl": "true" or "extra": { "ssl": "true" }
Heres my ormconfig.json
{
  "type": "postgres",
  "host": "host",
  "port": "port",
  "username": "username",
  "password": "password",
  "database": "database",
  "extra": {
    "ssl": "true"
  },
  "synchronize": "true",
  "logging": "true",
  "entities": ["src/**/*.entity.ts", "dist/**/*.entity.js"]
}

I expect it to connect to the server. The error I'm getting is [TypeOrmModule] Unable to connect to the database. error: no pg_hba.conf entry for host "", user "", database "", SSL off

A: This is my NestJS TypeORM config on Heroku:
TypeOrmModule.forRoot({
  type: 'postgres',
  url: process.env.DATABASE_URL,
  autoLoadEntities: true,
  ssl:
    process.env.NODE_ENV === 'production'
      ? { rejectUnauthorized: false }
      : false,
}),

The SSL option is mandatory as described here: https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js

A: If anyone has the same issue, I fixed it by adding a field for ssl and setting my ca certificate that I got from Digital Ocean.
Heres what my ormconfig looks like:
module.exports = {
  name: 'default',
  type: 'postgres',
  host: 'host',
  port: port,
  username: 'username',
  password: 'password',
  database: 'database',
  synchronize: true,
  dropSchema: false,
  logging: true,
  ssl: {
    ca: process.env.SSL_CERT,
  },
  entities: ['src/**/*.entity.ts', 'dist/**/*.entity.js'],
};

A: This works if you are connecting to postgres database on heroku from localhost using typeorm.
ormconfig.json
{
  "name": "default",
  "type": "postgres",
  "url": "postgres://username:password@host:port/database",
  "synchronize": true,
  "logging": true,
  "entities": ["src/entity/*.*"],
  "ssl": true,
  "extra": {
    "ssl": {
      "rejectUnauthorized": false
    }
  }
}

A:   ssl: {
    rejectUnauthorized: false,
    ca: fs.readFileSync('/path/to/server-certificates/root.crt').toString(),
    key: fs.readFileSync('/path/to/client-key/postgresql.key').toString(),
    cert: fs.readFileSync('/path/to/client-certificates/postgresql.crt').toString(),
  },

via https://node-postgres.com/features/ssl

A: Add this line to your config settings:
options: { encrypt: false }

Your configuration should look something like this:
TypeOrmModule.forRoot({
  type: 'mssql',
  host: 'your_db_server_address',
  port: 1433,
  username: 'user',
  password: 'pwd',
  database: 'your_db_name_here',
  entities: [Subscription],
  options: { encrypt: false }

})

A: You can set the PQSSLMODE environment variable to require - libpq will read those automatically, if not set otherwise, and establish a secure connection.
See also: https://www.postgresql.org/docs/current/libpq-envars.html


text:
Q: How to listen to postMessage messages in Puppeteer? https://github.com/GoogleChrome/puppeteer/blob/master/examples/custom-event.js shows how to define your own event, but doesn't show how to transmit event data back to the code outside Puppeteer.
For example, if I want to read event data the page postMessages in code using Puppeteer to launch the page, how would you do that?
Related: https://github.com/GoogleChrome/puppeteer/issues/2366

A: I just bumped into the same problem and below is something that worked for me.
Using the same example from the Puppeteer library with some modifications.
'use strict';

const puppeteer = require('puppeteer');

(async() => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    let msgCollection = [];

    // Define a window.onMessageReceivedEvent function on the page.
    await page.exposeFunction('onMessageReceivedEvent', e => {
        console.log(`${e.type} fired`, e.data || '');
        msgCollection.push(e.data);
    });

    /**
     * Attach an event listener to page to capture a custom event on page load/navigation.
     * @param {string} type Event name.
     * @return {!Promise}
     */
    function listenFor(type) {
        return page.evaluateOnNewDocument(type => {
            window.addEventListener(type, e => {
                window.onMessageReceivedEvent({type, data: e.data});
            });
        }, type);
    }

    await listenFor("message"); // Listen for "message" custom event on page load.

    await page.goto('https://jsfiddle.net/sa1nd0w5/', {waitUntil: 'networkidle0'});

    await browser.close();

    // Do something with the collected data
    console.log(msgCollection);

})();


text:
Q: python yumbase install not working I have a RHEL 7.2 box, here's the scenario that i have:
I have 2 use cases, one of them is working the second one is not working

*

*I have the following packages on my machine:

rocksdb.x86_64                   3.10.0-11.el7
rocksdb-devel.x86_64             3.10.0-11.el7
And i'm passing this package to the install function: rocksdb-devel-3.10.0-8.el7.x86_64 which should bring the dependencies (rocksdb-3.10.0-8.el7.x86_64)

*I don't have rocksdb installed at all

I'm passing the same package to the install function.
Here's a snippet of my code:

 class YumYum(object):
    installed_packages = None

def init(self):
            self.yb = yum.YumBase()
            self.yb.conf.assumeyes = True
            #self.yb.conf.cache =1
            #self.yb.setCacheDir()
            self.non_devel_packages = []
            self._probe_installed_packages()
def _probe_installed_packages(self):
        inst = self.yb.rpmdb.returnPackages()
        self.installed_packages = [
            Package(
                x.name,
                x.version,
                x.release,
                strict=False) for x in inst]

def _execute(self):
        message(OKGREEN, "Performing cleanup...")
        self._cleanup()
        message(OKGREEN, "After cleanup")
        self.yb.resolveDeps()
        self.yb.buildTransaction()
        self.yb.processTransaction()

    def _cleanup(self):
        self.yb.cleanRpmDB()
        self.yb.cleanExpireCache()
        self.yb.cleanMetadata()
        self.yb.cleanSqlite()
        self.yb.cleanPackages()

    def install(self, package)
        self.yb.install(
                        name=pkg.name, version=str(
                            pkg.version), release=str(
                            pkg.release), arch="x86_64")
        self._execute()

    def remove(self, package)
        self.yb.remove(name=pkg.name, version=str(pkg.version))
            self._execute()
# Main

yumyum = YumYum()
yumyum.remove(package) # In my real code the remove won't be called if i haven't found any packages to be removed (I.E if i haven't found a new newer packaged which is currently installed than needed)
yumyum.install(package)

In the first scenario The packages are being removed, but the installtion is failing with this Exception:
File "./pd-build.py", line 617, in _execute
    self.yb.processTransaction()
  File "/usr/lib/python2.7/site-packages/yum/__init__.py", line 6503, in processTransaction
    self._doTestTransaction(callback,display=rpmTestDisplay)
  File "/usr/lib/python2.7/site-packages/yum/__init__.py", line 6582, in _doTestTransaction
    raise Errors.YumRPMCheckError,retmsgs
yum.Errors.YumRPMCheckError: [u'ERROR with transaction check vs depsolve:', 'rocksdb(x86-64) = 3.10.0-8.el7 is needed by rocksdb-devel-3.10.0-8.el7.x86_64']

In the second scenarion: it's performing the installation right a way without any errors.
So in order trying to reproduce the the error(in the first scenarion) i've executed the same commands with yum cli and it managed to remove and ind install everything.
I'm wondering if i'm missing any configuration in the YumBase class or other things.


text:
Q: Applicationclass error when opening excel workbook I'm trying to open an excel workbook from a simple vb application.
Each time I press the button to open excel, I get the following error:
"Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass'   "
I have selected the Microsoft.interop.office.excel reference
I have also tried to just use .application instead of .applicationclass but that didn't make a difference either.
I searched previous asked questions about this, but those solutions didn't to anything for me.
See below for my code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal As System.EventArgs) Handles Button1.Click

    Dim oExcel As excel.ApplicationClass
    Dim oBook As excel.WorkbookClass
    Dim oBooks As excel.Workbooks

    'Start Excel and open the workbook.'
    oExcel = CreateObject("Excel.Application")
    oExcel.Visible = True
    oBooks = oExcel.Workbooks
    oBook = oBooks.Open("c:\book1.xls")

    End sub

Any suggestions for this?
Thanks in advance


text:
Q: C# new Task clarification After reading multiple articles issued at different years I got more confused then before.
I wanted to know how to make sure the tasks I create will run on multiple cores ??
The function below has to handle lots of files being uploaded to the server :
private void FileSystemWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {

        var SyncTask = new Task(() =>
        {

            //DO A LOT OF WORK HERE
        });

        SyncTask.Start();

    }

I just couldn't find a straight answer if this is the way to go on 4.7.2 .NET framework or not ?

A: The task itself will run on a single core.  If you want "//DO A LOT OF WORK HERE" to run on multiple cores, you need to parallelize that work either by spawning tasks from this task (see also Child tasks, or by using the simpler Parallel.
Otherwise, whether you use your approach or just Task.Run(..) it doesn't quite matter in your case.
EDIT  See this article, it explains nicely the difference.


text:
Q: d3 click event handle(object) I need click event handle in D3.js i.e the event object on click.
My code
 node.enter().append("svg:circle")
      .on('click', function(data,index){

       });

But I want event object like this in jquery
$('element').on('click',function(event){
    //Like the 'event' object here
});

A: node.enter().append("svg:circle")
    .on('click', function(data,index){
         d3.event; // => Original DOM Event
     });

» More info about d3.event.


text:
Q: nil pointer dereference error while trying to initialize a struct with pointer fields Defined struct type:
type ValidateTemplateQuery struct {
    TemplateURL  *string `json:"template_url" valid:"optional"`
    TemplateBody *string `json:"template_body" valid:"optional"`
}

Trying to initiate with mock values:
action := &ValidateTemplateQuery{
    TemplateURL:  *("TemplateURLValue"),
    TemplateBody: *("TemplateBodyValue"),
}

Error

getting "panic: runtime error: invalid memory address or nil pointer dereference"

A:
trying to initiate with mock values

Use the address of variables. For example,
package main

import (
    "fmt"
)

func main() {

    type ValidateTemplateQuery struct {
        TemplateURL  *string `json:"template_url" valid:"optional"`
        TemplateBody *string `json:"template_body" valid:"optional"`
    }

    url := "TemplateURLValue"
    body := "TemplateBodyValue"
    action := &ValidateTemplateQuery{
        TemplateURL:  &url,
        TemplateBody: &body,
    }

    fmt.Println(action, *action.TemplateURL, *action.TemplateBody)
}

Playground: https://play.golang.org/p/LZKV2LZ4KiE
Output:
&{0x40c138 0x40c140} TemplateURLValue TemplateBodyValue

The Go Programming Language Specification
Address operators
For an operand x of type T, the address operation &x generates a
  pointer of type *T to x. The operand must be addressable, that is,
  either a variable, pointer indirection, or slice indexing operation;
  or a field selector of an addressable struct operand; or an array
  indexing operation of an addressable array. As an exception to the
  addressability requirement, x may also be a (possibly parenthesized)
  composite literal. If the evaluation of x would cause a run-time
  panic, then the evaluation of &x does too.


text:
Q: Accessing Payloads in Elasticsearch Suggestion I am currently using the Java API for Elasticsearch.
A suggestion query, returns multiple results 'Suggestion', which I want to be able to iterate over and access the variables. This is done by:
val builder = es.prepareSuggest("companies").addSuggestion(new CompletionSuggestionBuilder("companies").field("name_suggest").text(text).size(count()) )
val suggestResponse = builder.execute().actionGet()
val it = suggestResponse.getSuggest.iterator()

Now
  while (it.hasNext()){
         val info = it.next()
         info.....
  }

I need to be able to access info from the payloads from 'info'. An example of the return looks like:
{
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "companies": [
    {
      "text": "wells",
      "offset": 0,
      "length": 16,
      "options": [
        {
          "text": "Wells Fargo",
          "score": 123.0,
          "payload": {
            "industry_id": 130,
            "id": 776,
            "popularity": 123
          }
        },
        {
          "text": "Wells Real Estate Funds",
          "score": 140.0,
          "payload": {
            "industry_id": 100,
            "id": 778,
            "popularity": 123
          }
        },
        {
          "text": "Wellstar Health System",
          "score": 126.0,
          "payload": {
            "industry_id": 19,
            "id": 1964,
            "popularity": 123
          }
        }
      ]
    }
  ]
}

When iterating through each suggestion, I seem unable to get the payload. Any ideas as to how I can do this?

A: To access the payloads, you have to iterate over the Option-Objects. (Right now, you are iterating over the suggestions)
import org.elasticsearch.search.suggest.Suggest.Suggestion
import org.elasticsearch.search.suggest.completion.CompletionSuggestion.Entry

...

// Get your "companies" suggestion
val suggestions: Suggestion[Entry] = suggestResponse.getSuggest.getSuggestion("companies")
val it = suggestions.getEntries.iterator()

// Iterate over all entries in the "company" suggestion
while(it.hasNext) {
  val entry = it.next()
  val optionsIt = entry.getOptions.iterator()

  // Iterate over the options of the entry
  while (optionsIt.hasNext) {
    val option = optionsIt.next()

    // As soon as you have the option-object, you can access the payload with various methods
    val payloadAsMap = option.getPayloadAsMap
  }
}

I found the information in the tests of ElasticSearch on Github


text:
Q: How to allow http traffic on android 28 api and up in react native I'm currently new developing react native, today I encounter problem regarding inserting data into database using the api. so now when I already done setup the axios post request my debugger browser shows of this error.

Note: API is created on my localhost reactjs.

My device that i used for developing :

*

*Vivo V9

*OS: Oreo

I already read some documents or some post here in the stackoverflow I tried there suggestion, but still I encounter of that Error on my application.
Suggestion:

*

*android:networkSecurityConfig="@xml/network_security_config"

*android:usesCleartextTraffic="true"

I also tried this setup:
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">127.0.0.1</domain>
</domain-config>

Now my androidmanifest.xml is now look like this:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature android:name="android.hardware.location.gps" />
<uses-feature android:name="android.hardware.location.network" />

<application android:networkSecurityConfig="@xml/network_security_config"
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:usesCleartextTraffic="true"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
  </activity>
  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>

My Function to insert data in the database is look like this:
const data = new FormData();

    data.append('driver_id','1');
    data.append('driver_route_lat',this.state.currentLocation.latitude);
    data.append('driver_route_long',this.state.currentLocation.longitude);

    axios({
      method: 'POST',
      url: 'http://127.0.0.1:8000/api/update_driver_route_logs',
      data: data,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    })
    .then((response) =>  {
      console.log(response.data)
    })
    .catch((error) =>  {
      console.log(error)
    });

In my postman the api is work well:


text:
Q: Understanding string arrays in c I am trying to understand this particular line of code.
I'm having trouble comprehending why there are 3 assignment statements needed for this.  I figure it is the minimum necessary, I just can't seem to follow it with my mind.
If someone could take me through what each line of this does, in english, that would be fantastic.
Thanks.
void to_upper(char *word) {

  int index = 0;

  while (word[index] != '\0') {
    word[index] = toupper(word[index]);
    index++;
  }
}

int length(char *word) {

  int index=0;

  while (word[index] != '\0')
    index++;
  return index;
}

void reverse(char *word) {
  int index, len;
  char temp;
  len = length(word);
  for (index=0; index<len/2; index++) {
    temp = word[index];
    word[index] = word[len-1-index];
    word[len-1-index] = temp;
  }
}

A:   for (index=0; index<len/2; index++) {
1    temp = word[index];
2    word[index] = word[len-1-index];
3    word[len-1-index] = temp;
  }

1: store the value of word[index] (we'll need it later)
2: store the value of the word array that is equidistant from the midpoint of the array into word[index]
3: store the original value of word[index] into the position equidistant from the midpoint of the array
e.g.: if index = 0, the first word is exchanged with the last and so on.

A: I am going to assume you understand the length and to_upper parts of your code as they are basically c++ 101 stuff.
//Well, just be the title, I would assume this function reverses a string, lets continue.
void reverse(char *word) {
  int index, len;  //declares 2 integer variables
  char temp;       //creates a temporary char variable
  len = length(word); //set the length variable to the length of the word
  for (index=0; index<len/2; index++) {
    //Loop through the function, starting at
    //index 0, going half way through the length of the word
    temp = word[index]; //save the character at the index
    word[index] = word[len-1-index]; //set the character at the index in the array
                                     //to the reciprocal character.
    word[len-1-index] = temp; //Now set the reciprocal character to the saved one.
  }
}

//This essentially moves the first letter to the end, the 2nd letter to the 2nd
//to end, etc.

So if you have the word "race" it swaps the "r" with the "e" and then the "a" with the "c" to get a final string of "ecar", or race backwards.
To understand why they need 3 assignments: if you set word[index] = word[len-1-index] then in both places, the same character exists. This would be like setting "race" to "racr". If you then set word[len-1-index] = word[index], you would just be putting the same character back in the first part, so you would go from "racr" to "racr". You need a temporary variable to save the original value so you can replace the character at the front of the string.


text:
Q: Gnu Plot - ';' expected - error I have a set of *.txt files, called test0001.txt, test0002.txt, .....
I want to convert the data of these files to *.png images (Out0001.png, ...).
set xrange [0:50]
set yrange [0:50]
set size square
set nokey
set pointsize 0.5
set terminal png size 1024,1024
do for [t=1:50] {
    outfile = sprintf('Out%04.0f.png',t)
    set output outfile
    plot ('test%04.0f.txt',t) using 1:2 with points pt 7 lc rgb "black"
}

I get "';' expected in line 12" as error. Just typing in the *.txt file names works btw:
    plot 'test0001.txt' using 1:2 with points pt 7 lc rgb "black"

This just creates the first image 50 times.

A: The first thing I'd be looking at was this line:
plot ('test%04.0f.txt',t) using 1:2 with points pt 7 lc rgb "black"

Since an earlier line used sprintf to do this string formatting, shouldn't you be looking at something like:
plot sprintf('test%04.0f.txt',t) using 1:2 with points pt 7 lc rgb "black"

Or, in toto, something like:
set xrange [0:50]
set yrange [0:50]
set size square
set nokey
set pointsize 0.5
set terminal png size 1024,1024
do for [t=1:50] {
    inpfile = sprintf('Out%04.0f.txt',t)
    outfile = sprintf('Out%04.0f.png',t)
    set output outfile
    plot inpfile using 1:2 with points pt 7 lc rgb "black"
}


text:
Q: Glassfish 4 Admin cannot run on NetBeans 8.0 I have installed JDK 8.0 and installed NetBeans IDE 8.0. I can start the embedded GlassFish Server 4.0. But I cannot enter Glassfish Domain Admin Console.
I get the following messages ...
**Warning:   Context path from ServletContext:  differs from path from bundle: /
Severe:   PWC6117: File "C:\Program Files\glassfish-4.0\glassfish\lib\install\applications__admingui\common\index.jsp" not found**

A: Now I can see Glassfish Domain Admin Console by changing java.policy.
java.policy is under JAVA_HOME/jre8/lib/security
My java.policy is like this ...
// Standard extensions get all permissions by default

**grant  {
        permission java.net.Socket.Permission "localhost:1527","listen";
};**

// default permissions granted to all domains

grant {
        // Allows any thread to stop itself using the java.lang.Thread.stop()
        // method that takes no argument.
        // Note that this permission is granted by default only to remain
        // backwards compatible.
        // It is strongly recommended that you either remove this permission
        // from this policy file or further restrict it to code sources
        // that you specify, because Thread.stop() is potentially unsafe.
        // See the API specification of java.lang.Thread.stop() for more
        // information.
        permission java.lang.RuntimePermission "stopThread";

        // allows anyone to listen on dynamic ports
        permission java.net.SocketPermission "localhost:0", "listen";

        // "standard" properies that can be read by anyone

        permission java.util.PropertyPermission "java.version", "read";
        permission java.util.PropertyPermission "java.vendor", "read";
        permission java.util.PropertyPermission "java.vendor.url", "read";
        permission java.util.PropertyPermission "java.class.version", "read";
        permission java.util.PropertyPermission "os.name", "read";
        permission java.util.PropertyPermission "os.version", "read";
        permission java.util.PropertyPermission "os.arch", "read";
        permission java.util.PropertyPermission "file.separator", "read";
        permission java.util.PropertyPermission "path.separator", "read";
        permission java.util.PropertyPermission "line.separator", "read";

        permission java.util.PropertyPermission "java.specification.version", "read";
        permission java.util.PropertyPermission "java.specification.vendor", "read";
        permission java.util.PropertyPermission "java.specification.name", "read";

        permission java.util.PropertyPermission "java.vm.specification.version", "read";
        permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
        permission java.util.PropertyPermission "java.vm.specification.name", "read";
        permission java.util.PropertyPermission "java.vm.version", "read";
        permission java.util.PropertyPermission "java.vm.vendor", "read";
        permission java.util.PropertyPermission "java.vm.name", "read";
};


text:
Q: React-Native-AsyncStorage save integer item I am try to save integer variable to the AsyncStorage, however it return me the error

the bind value at index 1 is null

SET Item
This is the code that i save item
AsyncStorage.setItem(
      Common.CURRENT_CHILD,
      this.state.child.toString(), //14
      () => {
        NavigationService.navigate('Home', {
          childName: this.state.childName
        });
      }
    );

GET Item
This is the code that i retrieve item
    AsyncStorage.getItem(Common.CURRENT_CHILD, (err, result) => {
      if (result === null) {
       console.log(err);
     } else {
      this.setState(
     {
        child: result
     },
      () => {
        console.log('Result -', result);
      }
    );
  }
})

A: AsyncStorage.setItem(
  Common.CURRENT_CHILD,
 ""+ this.state.child.toString(), //14
  () => {
    NavigationService.navigate('Home', {
      childName: this.state.childName
    });
  }
);

you can write "" while set item to Asyncstorage and try to use console.log while getting Item before if statement or
write
  AsyncStorage.setItem(
      Common.CURRENT_CHILD,
     ""+ this.state.child, //14
      () => {
        NavigationService.navigate('Home', {
          childName: this.state.childName
        });
      }
    );


text:
Q: Extract Unique Values From Multiple Columns With Macro I have a list of codes in A and the image links in B and C.
What i want to do is remove the duplicates and arrange the unique links in a single column and give them a series name with incrementing no code_1 before image link 1 and code_2 before link 2 as shown in the picture.

I am trying this code to delete the duplicates but clueless about how to put the name before the link.
Sub tgr()

    Dim wb As Workbook
    Dim wsDest As Worksheet
    Dim rData As Range
    Dim rArea As Range
    Dim aData As Variant
    Dim i As Long, j As Long
    Dim hUnq As Object

    'Prompt to select range.  Uniques will be extracted from the range selected.
    'Can select a non-contiguous range by holding CTRL
    On Error Resume Next
    Set rData = Application.InputBox("Select range of names where unique names will be extracted:", "Data Selection", Selection.Address, Type:=8)
    On Error GoTo 0
    If rData Is Nothing Then Exit Sub   'Pressed cancel

    Set hUnq = CreateObject("Scripting.Dictionary")
    For Each rArea In rData.Areas
        If rArea.Cells.Count = 1 Then
            ReDim aData(1 To 1, 1 To 1)
            aData(1, 1) = rArea.Value
        Else
            aData = rArea.Value
        End If

        For i = 1 To UBound(aData, 1)
            For j = 1 To UBound(aData, 2)
                If Not hUnq.Exists(aData(i, j)) And Len(Trim(aData(i, j))) > 0 Then hUnq(Trim(aData(i, j))) = Trim(aData(i, j))
            Next j
        Next i
    Next rArea

    Set wb = rData.Parent.Parent    'First parent is the range's worksheet, second parent is the worksheet's workbook
    Set wsDest = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
    wsDest.Range("A1").Resize(hUnq.Count).Value = Application.Transpose(hUnq.Items)

End Sub

A: This custom VBA function would create the desired result of getting the SKU code. I broke it up to show how to get each position.
Function Drop_Bucks(inputText As String) As String
Dim beginSpot As Long, endSpot As Long

    'Finds last /
    beginSpot = InStrRev(inputText, "/", -1, vbTextCompare) + 1
    'Finds jpg
    endSpot = InStrRev(inputText, ".jpg", -1, vbTextCompare)

Drop_Bucks = Replace(Mid(inputText, beginSpot, endSpot - beginSpot), "-", "_")

End Function

As a followup, you could also create the sku without VBA. If you put this formula in cell c4 with a sku in d4. It should do without macro.
=SUBSTITUTE(SUBSTITUTE(LEFT(SUBSTITUTE(SUBSTITUTE(RIGHT(SUBSTITUTE(d4, "/",REPT("?", 999)), 999),"?",""), ".jpg",REPT("?", 999)), 999),"?",""),"-","_")

A: This builds a list of all the item duplicates and all.  It will then uses the function Range.RemoveDuplicates to remove duplicates of the SKU Code in combination with the URL within the range.
Option Explicit
Sub Test()

    Dim oCurSourceSheet As Worksheet
    Set oCurSourceSheet = Sheet1 ' What sheet is your Source Data on?
    Dim oSourceRow As Long    ' Which Row/Column does your data start on?
    oSourceRow = 2           ' First Row of First "Link"
    Dim oSourceCol As Long
    oSourceCol = 2           ' First Column of First "Link"

    Dim oOutputRange As Range
    Set oOutputRange = Sheet1.Range("A10") ' What Sheet/Cell do you want the output to start on/in?

    Dim oCurRow As Long ' Row counter for Output
    oCurRow = 1

    Dim oCurSourceRow As Long
    Dim oCurSourceCol As Long
    For oCurSourceRow = oSourceRow To oCurSourceSheet.UsedRange.Rows.Count
        For oCurSourceCol = oSourceCol To oCurSourceSheet.UsedRange.Columns.Count
            oOutputRange.Cells(oCurRow, 1) = oCurSourceSheet.Cells(oCurSourceRow, 1) & "_" & oCurSourceCol - 1
            oOutputRange.Cells(oCurRow, 2) = oCurSourceSheet.Cells(oCurSourceRow, oCurSourceCol)
            oCurRow = oCurRow + 1
        Next
    Next

    'Reize range from output's starting cell & remove duplicates
    Set oOutputRange = oOutputRange.Resize(oCurRow - 1, 2)
    oOutputRange.RemoveDuplicates Columns:=Array(1, 2)

End Sub

A: This may helps you:
Option Explicit

Sub TEST()

    Dim LastRow As Long, i As Long, LastRow2 As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        .Range("$A$2:$C$" & LastRow).RemoveDuplicates Columns:=Array(1, 2, 3), Header:=xlNo

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        arr = .Range("A2:C" & LastRow)

        For i = LBound(arr) To UBound(arr)

            LastRow2 = .Cells(.Rows.Count, "E").End(xlUp).Row

            .Range("E" & LastRow2 + 1).Value = arr(i, 1) & "_1"
            .Range("F" & LastRow2 + 1).Value = arr(i, 2)

        Next i

        For i = LBound(arr) To UBound(arr)

            LastRow2 = .Cells(.Rows.Count, "E").End(xlUp).Row

            .Range("E" & LastRow2 + 1).Value = arr(i, 1) & "_2"
            .Range("F" & LastRow2 + 1).Value = arr(i, 3)

        Next i

    End With

End Sub

A: Try this, please: I adapted your code. The Dictionary is used just like a tool for avoiding duplicate values (due to the fact it exists...). Everything works in memory and should be very fast:
    Option Base 1

    Sub tgr_bis()
    Dim wb As Workbook, rData As Range, wsDest As Worksheet, rArea As Range
    Dim aData As Variant, aDataSorted() As String
    Dim i As Long, hUnq As Scripting.Dictionary, nrColumns As Long

    On Error Resume Next
    Set rData = Application.InputBox("Select range of names where unique names will be extracted:", "Data Selection", Selection.Address, Type:=8)
    On Error GoTo 0
    If rData Is Nothing Then Exit Sub   'Pressed cancel

    'Debug.Print rData.Columns.Count: Stop
    If rData.Columns.Count > 6 Then MsgBox "More then 6 columns..." & vbCrLf & _
                                         "Please select only six columns and run the procedure again", vbInformation, _
                                         "Too many columns": Exit Sub
    nrColumns = rData.Columns.Count
    Set hUnq = CreateObject("Scripting.Dictionary")
    For Each rArea In rData.Areas
        If rArea.Cells.Count = 1 Then
            ReDim aData(1 To 1, 1 To 1)
            aData(1, 1) = rArea.value
        Else
            aData = rArea.value
        End If
        ReDim aDataSorted(nrColumns, 1)
        Dim k As Long
        k = 1
        For i = 1 To UBound(aData, 1)
                If Not hUnq.Exists(aData(i, 1)) And Len(Trim(aData(i, 1))) > 0 Then
                    aDataSorted(1, k) = aData(i, 1): aDataSorted(2, k) = aData(i, 2): aDataSorted(3, k) = aData(i, 3)
                    Select Case nrColumns
                        Case 4
                            If aData(i, 4) <> "" Then aDataSorted(4, k) = aData(i, 4)
                        Case 5
                            If aData(i, 4) <> "" Then aDataSorted(4, k) = aData(i, 4)
                            If aData(i, 5) <> "" Then aDataSorted(5, k) = aData(i, 5)
                        Case 6
                            If aData(i, 4) <> "" Then aDataSorted(4, k) = aData(i, 4)
                            If aData(i, 5) <> "" Then aDataSorted(5, k) = aData(i, 5)
                            If aData(i, 6) <> "" Then aDataSorted(6, k) = aData(i, 6)
                        Case > 6
                           MsgBox "Too many selected columns!": Exit Sub
                    End Select

                    k = k + 1
                    ReDim Preserve aDataSorted(nrColumns, k)
                    hUnq(Trim(aData(i, 1))) = Trim(aData(i, 1))
                End If
        Next i
    Next rArea

    'Process the new array in order to be tansformed in what is needed:
    Dim finalCol() As String
    k = k - 1: Z = 1
     ReDim finalCol(2, Z)
     Dim lngIndex As Long
     Dim totalRows As Long

    For i = 1 To k
        lngIndex = 1
        finalCol(1, Z) = aDataSorted(1, i) & "_" & lngIndex: lngIndex = lngIndex + 1: _
                                finalCol(2, Z) = aDataSorted(2, i): totalRows = totalRows + 1
        Z = Z + 1: ReDim Preserve finalCol(2, Z)
        finalCol(1, Z) = aDataSorted(1, i) & "_" & lngIndex: lngIndex = lngIndex + 1: _
                                finalCol(2, Z) = aDataSorted(3, i): totalRows = totalRows + 1
        Z = Z + 1: ReDim Preserve finalCol(2, Z)
        If nrColumns < 4 Then GoTo EndLoop
        If aDataSorted(4, i) <> "" Then finalCol(1, Z) = aDataSorted(1, i) & "_" & lngIndex: _
                    lngIndex = lngIndex + 1: finalCol(2, Z) = aDataSorted(4, i): totalRows = totalRows + 1: _
                    Z = Z + 1: ReDim Preserve finalCol(2, Z)
        If nrColumns < 5 Then GoTo EndLoop
        If aDataSorted(5, i) <> "" Then finalCol(1, Z) = aDataSorted(1, i) & "_" & lngIndex: _
                    lngIndex = lngIndex + 1: finalCol(2, Z) = aDataSorted(5, i): totalRows = totalRows + 1: _
                    Z = Z + 1: ReDim Preserve finalCol(2, Z)
        If nrColumns < 6 Then GoTo EndLoop
        If aDataSorted(6, i) <> "" Then finalCol(1, Z) = aDataSorted(1, i) & "_" & lngIndex: _
                    lngIndex = lngIndex + 1: finalCol(2, Z) = aDataSorted(6, i): totalRows = totalRows + 1: _
                    Z = Z + 1: ReDim Preserve finalCol(2, Z)
EndLoop:
    Next i

    Set wb = rData.Parent.Parent
    Set wsDest = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))

    wsDest.Range("A1:B" & totalRows) = Application.Transpose(finalCol)
End Sub

'A reference to "Microsoft Scripting Runtime" must be added. Otherwise, you can declare hUnq As Object...
And do not forget to have Option Base on tot of the module where this code exists. It is necessary to work with the way you built your initial code.
Edited: I adapted the code to accept up to six columns as you suggested. Please give it a try.
But it only check the unique SKU Code and select the first occurrence. If the other occurrences appear, the will not be considered even if they have different strings on its row. The code can be adapted to work also from this point of view, but now I think is your turn to make some tests...


text:
Q: Does mongodb master node need to be accessible from clients? In a MongoDB replica set, Does master node need to be accessible from clients? Or secondary nodes will redirect write queries to master node?

A: All your nodes must be accessible from clients. That way, if the primary goes down and a secondary is promoted to primary, your application will continue to work.

A: Secondary nodes will not proxy write requests to the primary node. To perform writes you need to be directly connected to the master node.

A: The above answers aren't 100% correct.
1) if you are in a sharded environment then the clients need to be able to communicate with the mongos process which then communicates with the PRIMARY nodes (and the config servers) there could be a scenario where the application servers and separated from the PRIMARY mongodb server in a replica set yet they where able to communicate with the mongos processes which was then able to communicate with the PRIMARY mongodb server.
2) Another user noted that "all your nodes must be accessible from clients" while generally true not always true, in a situation where you had a delayed secondary in a separate data center only members of the replica set need to be able to communicate with the delayed secondary; however the application servers never need to communicate with it.


text:
Q: How can I scale down a website without changing every single font-size, image-size, button, etc So I'm working on a website for training purposes and just expanding my skill in general. I've got a fully fleshed out site, looks fantastic, however -- a few people have noted that it seems just a little too....big. Not sure how else to put it other than this: It looks like it's SUPPOSED to look like when the browser is at 80% zoom. But at 100% zoom it looks a little too big. Is there anyway to kind of just scale down the site as a whole?
I've tried using transform: scale(x); in the body but that is just absolutely terrible and not what I wanted, and I really don't know what to look for / what to use and how to use it to really tackle this problem.
And when I say that going through the website and manually resizing all the fonts, images, buttons, and literally anything else is NOT possible, I mean that it is seriously not possible with the time given to me to do.
Anyone have any ideas?

A: Generally, manipulating the browser zoom settings or scaling a page is not considered good practice. Even if it looks awesome on your end, it does not mean it will look as good to a customer. There are multiple window sizes and devices to take into consideration.
The recommended method is to make the appropriate changes to the layout and CSS.
However, I have added a hack below that will work for most browsers. I just want to make it clear that I do not recommend this approach.
html {
   zoom: 0.8;
   -moz-transform: scale(0.8);
   -webkit-transform: scale(0.8);
   transform: scale(0.8);
}


text:
Q: How to add SSL certificate for https request while logging in iphone I have gone through all the related posts regarding this SSL certificate issue.
I dont want to bypass it by using the below methods.
 -(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
  return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

 -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    if ([trustedHosts containsObject:challenge.protectionSpace.host])
      [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

  [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

And also I dont want to add the certificate by manual in the iphone and in simulator.
Actually I need a pop up messge should indicate the user that the certificate for this server is invalid and do you need to add this certificate for your process?.... this kind of message needs to be asked to the user whenever finds some https request.....
Is there any example or how to do?....