text:
Q: plot LAT/LON coordinates on geotiff in R I have a sea ice map as a "geotiff". The eventual goal is to extract sea-ice concentrations at specific lat/lon coordinates.
The geotiff can be found at: http://www.iup.uni-bremen.de:8084/amsr2data/asi_daygrid_swath/n6250/2015/jan/asi-AMSR2-n6250-20150101-v5.tif
What i am trying to do is load the geotiff using raster() and then overlay it by my locations and then using the extract() function to acquire values from the raster file at the specific location.
However my lat/lon points accumulate in the centre of the map. Where do I go wrong? Any help or input is greatly appreciated!
library(raster)
library(sp)

r1 = raster("test.tif")

##check plot
plot(r1)

## check projection
projection(r1)

mydf <- structure(list(longitude = rep(22,7), latitude = seq(60,90,5)),.Names = c("longitude","latitude"), class = "data.frame", row.names = c(NA, -7L))

### Get long and lat from data.frame.
xy <- mydf[,c(1,2)]
spdf <- SpatialPointsDataFrame(coords = xy, data = mydf,
                           proj4string = CRS("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"))

 points(spdf, col="red", lwd=2)

 ##extract RGB values as reference for sea-ice concentration
 seaice_conc = extract(r1, spdf)

A: Geo-sp's solution would work, but is sub-optimal (slow and imprecise). You should always (re-)project  your vector (points in this case) data and not your raster data. Projecting raster data changes values, while this is not the case with vector data. Projecting raster data is also much more computationally intensive.
Thus, you should do something like this:
library(raster)

r <- raster("asi-AMSR2-n6250-20150101-v5.tif")
crs(r)
# CRS arguments:
# +proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0

df <- data.frame(longitude = rep(22,7), latitude = seq(60,90,5), ID=1:7)

spdf <- SpatialPointsDataFrame(coords = df[,1:2], data = df,
         proj4string = CRS("+proj=longlat +datum=WGS84"))

library(rgdal)
p <- spTransform(spdf, crs(r))

extract(r, p)

It is important to note that you made a very common mistake:
spdf <- SpatialPointsDataFrame(coords = xy, data = mydf, proj4string =
          CRS("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m"))

You create a SpatialPointsDataFrame and assign the wrong coordinate reference system (crs). You must assign the crs that actually matches your data, which is "+proj=longlat +datum=WGS84". After that, you can transform the data to the crs that you would like to have (using spTransform).

A: You can use projectRaster to reproject your raster file. Then you can overlay the points and extract the values.
newproj <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
p <- projectRaster(r1, newproj)


text:
Q: Why does 'transform:rotate(Xdeg)' cause the animation to stop? I tried to rotate an animated font arrow when the window reached a min/max size, but when the rotate takes place the animation stops, also just for testing I tried replacing transform: rotate(90deg) to transform: rotate(0deg) which maintains the same arrow's direction but it causes to stop the animation too. The issue is with transform: rotate() and it can be easily tested by inspecting the element and activating/deactivating it in the browsers developer tools.
An easy way to bypass this can be using two
 each one with an arrow in different direction and with vertical and horizontal animation each, and using display: none; to alternate between them when the min/max size switches, but what I want is to know why this is happening and how to solve this using this approach

.text-center {
  text-align: center;
}

.lnr-x3 {
  font-size: 2.4rem;
}

@media (max-width: 991px) {
  #catalogArrow_h {
    transform: rotate(90deg) !important;
    transform-origin: center !important;
  }
}

.animated-h {
  text-decoration: none;
  outline-style: none;
  -webkit-animation: movingHorizontally 1.7s ease-in-out infinite;
  animation: movingHorizontally 1.7s ease-in-out infinite;
}

@keyframes movingHorizontally {
  0% {
    transform: translateX(0px);
    -webkit-transform: translateX(0px);
  }
  50% {
    transform: translateX(-10px);
    -webkit-transform: translateX(-10px);
  }
  100% {
    transform: translateX(0px);
    -webkit-transform: translateX(0px);
  }
}

@-webkit-keyframes movingHorizontally {
  0% {
    transform: translateX(0px);
    -webkit-transform: translateX(0px);
  }
  50% {
    transform: translateX(-10px);
    -webkit-transform: translateX(-10px);
  }
  100% {
    transform: translateX(0px);
    -webkit-transform: translateX(0px);
  }
}

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" type="text/css">
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">

A: Why does this happen
The transform property is "shared" for many transform functions and css doesn't combine any property's values.
Because your animation is made with transform: translateX(..), adding transform: rotate(..) will overwrite the property's value, not combine them. I.e. the resulting style is transform: rotate(..), not transform: translateX(..) rotate(..).
It would be the same if you were animating the box-shadow and then wanted an inset box-shadow too, it would overwrite one with the other. Or more simply - if you have .box { color: red; color: blue; } css will choose the last value (blue) to apply to the color property.
If there were css properties rotate: 90deg and translate: 4px (there are but not widely supported), then your animation would work, because the translate animation would be applying to a different property than the rotation, not overwriting one that is essentially shared amongst many transform functions.
Ways around it
There are many ways around this problem.

*

*You can set the translate or rotate on the parent element

*

*You can add the rotate to your translate animation properties:

@keyframes movingHorizontallyRotated {
  0%, 100% { transform: translateX(0px)   rotate(90deg); }
  50%      { transform: translateX(-10px) rotate(90deg); }
}

*

*You can animate a different property to translate the element:

@keyframes movingHorizontally {
  0%, 100% { padding: 5px 10px 5px 0px; }
  50%      { padding: 5px 0px 5px 10px; }
}

*

*You can use/make an already rotated arrow if your framework/ assets provides one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery UI Touch Punch draggable() In my application I use drag&drop which I aslo want to implement on mobile devices. I was thinking about using JQuery Ui touch punch like this:
  var thumb = document.createElement("img");
  $(thumb).draggable({containment: "html"});

The problem is that my image is dragged only in the scope of its parent (see attached image) not on the whole page. I've tried changing containment options but the problem seems to be elsewhere.

CSS:
html, body {
   height: 100%;
   background: black;
   margin:0; padding:0;
   overflow:hidden;
}
//one parent
.dhThumbOuter {
    float: left;
    width: 64px;
    height: 64px;
    -webkit-box-shadow: 0px 0px 5px #4d4d4d;
    -moz-box-shadow: 0px 0px 5px #4d4d4d;
    box-shadow: 0px 0px 5px #4d4d4d;
    border:solid gray 1px;
    overflow: hidden;
    padding: 3px;
    margin-left: 3px;
    font-size: smaller;
    position:relative;
    border : solid gray 2px;

}
//other parrent
.dhThumbImage {
    background: lightgray;
    padding: 0;
    width: 64px;
    height: 64px;
    overflow: hidden;
    position:absolute;
}

Javascript:
   var thout = createElement("div", "dhThumbOuter dhRounded");
            container.appendChild(thout);
            var thinner = createElement("div", "dhThumbImage dhRounded");
            thout.appendChild(thinner);
            thinner.appendChild(thumb); //my image

A: Use the helper: clone property on draggable() so that the image "breaks out" of it's container when dragged.
See the official jQuery UI draggable docs here: http://api.jqueryui.com/draggable/#option-helper

A: You can also add custom helper
$('#draggable').draggable({
  zIndex: 20,
  drag: function(event){...},
  helper: function(){
    $("#outerElement").append($("#draggable").clone().attr('id', 'itWorks'))
    return $("#itWorks");
  },
})

where outerElement is the element which contains your draggable and drop element as well


text:
Q: Find selected data in excel formula I'm seeking a solution below scenario.
C1 contains:
['abc': 'v1','cde':'v2']
C2 contains:
['abc': 'v1','cde':'v2','efg':'v3']
What I expect to get in D1:
abc,cde
and in D2 abc,cde,efg
I was trying to get the formula as below
=LEFT(C1,FIND(",",C1)-1)
but its coming like "['abc':'v1'

A: When using Office 365 you can use REDUCE to iterate SUBSTITUTE with multiple characters over multiple cells in one go.
Using REDUCE once more to spill the joined text of the first indexed column of the TEXTSPLIT result per row (this will work regardless the number of seaparators (up untill the string would exceed 255 characters, I guess):
=LET(a,C1:C3,
     replace,{"[";"]";" ";"'"},
     rdc,REDUCE(a,replace,LAMBDA(x,y,SUBSTITUTE(x,y,""))),
DROP(REDUCE(0,rdc,LAMBDA(x,y,VSTACK(x,TEXTJOIN(",",1,INDEX(TEXTSPLIT(y,":",","),,1))))),1))


text:
Q: Table per hierarchy mapping to an existing database using Fluent NHibernate without discriminator column I have a problem with table per hierarchy mapping to an existing database using Fluent NHibernate (1.2.0.712).
Here is the simplified case.
My class structure:

Database structure:

So basically, we have 1 table (Entities) which contains some specific data (Id and Name) + several foreign keys (to ReferencedObject1 OR ReferencedObject2).
Abstract class AbstractEntity contains Id and Name. ConcreteEntity1 and ConcreteEntity2 are derived classes.
I would like to map these derived instances depending on references in database, so
If there is a reference to ReferencedObject1 -> it is an instance of ConcreteEntity1.
If there is a reference to ReferencedObject2 -> it is an instance of ConcreteEntity2.
Some code:
public class AbstractEntity
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
}
public class ConcreteEntity1 : AbstractEntity
{
    public virtual ReferencedObject1 ReferencedObject1 { get; set; }
}
public class ConcreteEntity2 : AbstractEntity
{
    public virtual ReferencedObject2 ReferencedObject2 { get; set; }
}

public class AbstractEntityMap : ClassMap<AbstractEntity>
{
    public AbstractEntityMap()
    {
        Table("Entities");
        Id(e => e.Id);
        Map(e => e.Name);
    }
}

So actually my question is how should I map derived classes?
I've looked through fluent nhibernate wiki and found that

If you wanted to do a table-per-class-hierarchy strategy, then you just need to specify the discriminator column in your ClassMap.

but, as far as I understand, I do not have a discriminator column. My case is to determine subclass depending on foreign key references.

Note: For multiple discriminator columns use a DiscriminateSubClassesOnColumn("").Formula([insert custom sql here])

I can't find a good example of formula usage. Can it be helpful in my case? And I'm a little bit confused, maybe I am doing something wrong?
Could anyone help me?
Thanks in advance :)

A: DiscriminateSubClassesOnColumn("")
    .Formula(case when ReferencedObject1id > 0 then 1 else case when ReferencedObject2id > 0 then 2 else ... end)

ConcreteEntity1Map()
{
    DiscriminatorValue(1);
}


text:
Q: politely asked if we would like to upgrade RE Kubuntu:
We used to get notified that a new release was available, and were politely asked if we would like to upgrade. I haven't seen that in a long time--like years. Did someone decide to stop that? Are we now forced to manually start a release upgrade from the command line?
Is Discover supposed to handle that?
Still using Kubuntu 20.04, waiting to be offered an upgrade.
I know I can manually start an upgrade, that's not what I'm asking. And yes, I have preferred "Normal" releases, not LTS. I'm trying to learn if a KDE release upgrader has gone missing.
Thanks,
Lance


text:
Q: localStorage обновляется. Как запретить if (localStorage.getItem('todo')!=undefined){
        var tasks = [];
        tasks = JSON.parse(localStorage.getItem('todo'));
        for (var key in tasks) {
            $('#list').append("
" + tasks[key] + "
");
        }
    }

        function SaveTask(){
            var tasks = [];
            $('li.task').each(function(i, el){
                var val = $(el).text();
                    tasks.push(val);
            });
            console.log(tasks);
            localStorage.setItem('todo', JSON.stringify(tasks));

        }

        function AddTask(){
            var val = $('#new-todo').val();
            var del = $('').text('×');
            var li = $('
').html(val).append(del);
            if (val) {
                li.appendTo($('#list'));
                $('#new-todo').val('');
            }

            del.click(function () {
                li.remove();
            });
        }

        $('#btn-enter').click(function () {
            AddTask();
            SaveTask();
        });

При перезагрузке страницы отображаются только последнедобавленные, вместо всех. Если var tasks = []; сделать глобальной, идет некорректное сохранение в массив.
Тут 2 варианта - скорректировать  SaveTask() или localStorage. Рассмотрю все...
http://jsfiddle.net/Nata_Hamster/6vhas75k/

A: Вы при сохранении делаете выборку по li.task в то время, как класс task добавляете только новым записям, поэтому старые записи не входят в выборку для сохранения.
Не меняя оформление страницы можно сделать выборку #list > li - в нее входят и старые и новые записи.
Такой селектор css читается как "выбрать все элементы li - прямые потомки элемента с id list"
http://jsfiddle.net/6vhas75k/2/


text:
Q: Running Tests on multiple iOS Real-Device using Appium I am trying to run tests on several iOS real devices via Appium. I know that an extra session has to be created for each device. But when I create a session for my second device, the session from my first device breaks.
I use:
Mac OS Ventura
Appium version 2 beta (Launched in terminal as there is no desktop version for 2 beta yet).
Xcode 14.2
Appium Inspector (For creating sessions)
iOS 16.3
I have started Appium Server(0.0.0.0:4723 and 0.0.0.0:4725) in Terminal. WDA is installed on both devices. In Appium Inspector I have entered the capabilities for both devices in 2 extra session and when starting second session the first one breaks. This is mainly because when both sessions try to run with wdaLocalPort on 8100. I can start the WDA in Xcode only to one device, so I can find out the wdaLocalPort! The WDA on the devices I also have to start directly on the devices but then no longer know which device uses which wdaLocalPort!
Does anyone have experience with this and can tell me the steps or know what exactly I'm doing wrong?


text:
Q: Automate Data Extension Deletion in Salesforce marketing cloud We have multiple Data extension which are no longer required for use. I want to delete all the data extension inside a folder in SFMC. is there any way to achieve this using automation or SSJS? I don't want to delete manually as we have many data extensions and it is time consuming.
Thanks,

A: There is no function inside of SSJS that will let you do this. The Core functions do not have a 'Delete' option for DataExtensions, but you CAN do this via WSProxy.

*

*You would first retrieve each of the DE Object IDs via a retrieve request.

*You then would use deleteBatch() to remove each of these data
extensions.

In order to run this though, you would need to place the script inside of a 'Script Activity' in Automation Studio and then schedule the automation to run at your set intervals.
Here is a sample function for retrieving the DE objectIds via WSProxy:
function retrieveDEsbyFolder(folder) {
  var cols = ["ObjectID"];
  var filter = {
      "Property": "CategoryID",
      "SimpleOperator": "equals",
      "Value": folder
  }
  var res = prox.retrieve("DataExtension", cols, filter);

  return res;
}

and here is the function to batch delete the DEs:
function deleteDEsbyFolder(folder) {
  var ret = retrieveDEsbyFolder(folder);
  var deArr = [];
  var results = ret.Results

  for(i=0;i<results.length;i++) {
    var deObj = {};
    var objectID = results[i].ObjectID;
    deObj.ObjectID = objectID;
    deArr.push(deObj);
  }

  var res = prox.deleteBatch("DataExtension",deArr)
  return res;

}

And here is a sample with everything pushed together:
<script runat="server">

var folder = 12345;
var prox = new Script.Util.WSProxy();

var deDelete = deleteDEsbyFolder(folder);

function deleteDEsbyFolder(folder) {
  var ret = retrieveDEsbyFolder(folder);
  var deArr = [];
  var results = ret.Results

  for(i=0;i<results.length;i++) {
    var deObj = {};
    var objectID = results[i].ObjectID;
    deObj.ObjectID = objectID;
    deArr.push(deObj);
  }

  var res = prox.deleteBatch("DataExtension",deArr)
  return res;

}

function retrieveDEsbyFolder(folder) {
  var cols = ["ObjectID"];
  var filter = {
      "Property": "CategoryID",
      "SimpleOperator": "equals",
      "Value": folder
  }
  var res = prox.retrieve("DataExtension", cols, filter);

  return res;
}
</script>

as a note, if you have more than 2500 records, you will need to use Pagination for WSProxy to retrieve these as max return from a retrieve is 2500 records.

A: Unfortunately, there is not a way to use SSJS to automate deletion as requested, there is an alternative way to accomplish this so that that desired specific data gets deleted from All Contacts and such, as well as do it in a manner where you do not have to individually delete each one.
If you create a sendable Data Extension with only a Contact Key field, then import the data that needs to be deleted (only keeping the Contact Key), you can delete just the intended data by doing the following:
(from the Parent BU)

*

*Select the Contact Builder app (Audience Builder > Contact Builder)

*Select the All Contacts tab at the top

*Select All Contacts from the left sidebar

*Select the delete dropdown (trashcan symbol)

*Select Delete contacts from the data extension

From there, you can initiate the deletion process. Note that you can choose that same delete dropdown to View Pending Deletions to check the status of that deletion request.
Please note that this will remove all contacts that match the Contact Key listed on the created DE across all provisioned channels, so please make sure that only contacts intended to be removed in that manner are in the Data Extension.
Also please note the following, from the earlier attached documentation concerning Contact Deletion in Contact Builder:
This functionality includes a 14-day default period where Contact Builder suppresses contact information from showing in channel apps such as Email or MobileConnect. You can change the length of this time period in your account. The information remains in your account, but you cannot view contact records or access it to send activities. Once the period elapses, we delete contact information for deleted contacts from lists and sendable data extensions. This process does not apply to any non-sendable data extensions not included in a population via Data Designer, and you are responsible for deleting applicable information from those sources on your own.

*

*Deletion process initiated

*Suppression period - contact information remains in your account, but you cannot view or access it

*Final deletion - Marketing Cloud removes deleted contact information from your account

I do recommend you to follow best practices to delete contacts:
https://help.salesforce.com/articleView?id=mc_cab_best_practices.htm&type=5
This can be achieved as well by REST API call:
https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/ContactsDeleteConfigStatus.htm
As additional information, "All Contacts" refer to the contact within Mobile Connect. "All Subscribers" are subscribers within the All Subscribers list in Email Studio. The count for "All Contacts" in mobile connect does not count toward the "All Subscribers" list. However, if you send an email to a contact in "All Contact", that contact will be added to the "All Subscribers" list and therefore adding to the All Subscriber list count.
To have automated deletion for "All Contacts" considered for future deployment, you could go to the Idea Exchange page, and post an idea to have the ability to the custom setting within the Managed package. Our product team monitors these ideas, and the more votes they get, the higher priority they take for future upgrades on releases.
If you would like to do this, you can go to the Idea Exchange by following this link:
https://success.salesforce.com/ideaSearch
Thanks.


text:
Q: Understand Angular 8 routing Trying to get familiar with Angular I adapted a sample (cornflourblue) I found in the internet.
It consists of a controlling AppComponent, a LoginComponent and a HomeComponent.
The routing is defined this way:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';

import { HomeComponent } from './home';
import { LoginComponent } from './login';

const routes: Routes = [
  { path: 'home',  component: HomeComponent },
  { path: 'login', component: LoginComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes),
    HttpClientModule
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

But it makes no difference whether I use the URL: localhost:4200, localhost:4200/home or localhost:4200/login - I always see the page defined with login.component.html.
The AppCpmponent is this:
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {}

The LoginComponent is this (I have removed all logic to keep it simple):
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Credentials } from '@app/_models';

@Component({
    selector: 'app-login',
    templateUrl: 'login.component.html'
})

export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
error = '';

constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
) {     }

ngOnInit() {
    this.loginForm = this.formBuilder.group({
        username: ['', Validators.required],
        password: ['', Validators.required]
    });

    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}

// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }

onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.loginForm.invalid) {
        return;
    }
    this.loading = true;
}

getCredentials(aUsername: string, aPassword: string) {
    let credentials: Credentials = {username :aUsername, password : aPassword};
    console.log("Entered credentials: User=" + credentials.username + " User=" + credentials.password);
    return credentials;

}

}
This is the HomeComponent:
import { Component } from '@angular/core';
import { first } from 'rxjs/operators';

import { User } from '@app/_models';
import { UserService } from '@app/services';

@Component({ templateUrl: 'home.component.html' })
export class HomeComponent {
    loading = true;
    users: User[];
}

And this are the used htmls:
app.component.html

      Authentication

        Home
        Logout

  <app-login>
      <router-outlet></router-outlet>
  </app-login>

home.component.html

You're logged in with Angular 8 & Basic HTTP Authentication!!

Users from secure api end point

login.component.html

Angular 8 Basic Auth Login Example

            <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">

                    Username
                    <input type="text" formControlName="username" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.username.errors }" />

Username is required

                    Password
                    <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />

Password is required

                <button [disabled]="loading" class="btn btn-primary">

                    Login
                </button>

{{error}}

            </form>

the basic index.html is:
<!doctype html>

  <meta charset="utf-8">
  <title>Authentication</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.1/material.indigo-orange.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

  <app-root>Loading...</app-root>

I spent already many hours trying to reduce the code, change it an read docs - but could not manage to get a see the HomeComponent - but could not get any further. Appreciate your help

A: You have in app.component.html wrong code.

      Authentication

        Home
        Login
        Logout

  <router-outlet></router-outlet>

Coppy and paste this code.
If You want your HomeComponent to be on main page like www.sadaasd.com/ in router:
const routes: Routes = [
  { path: '',  component: HomeComponent }, // empty path
  { path: 'login', component: LoginComponent }
];

And when You have a component declared as a route do not use anywhere <app-login> tag <router-outlet> decide when to display it.
Example bobo.com/home in app.component.html in place of <router-outlet> angular will display home.component.html when bobo.com/login there will be login.component.html. This is acording to path: 'home' and path: 'login'


text:
Q: Python Matplotlib Multi-color Legend Entry I would like to make a legend entry in a matplotlib look something like this:

It has multiple colors for a given legend item. Code is shown below which outputs a red rectangle. I'm wondering what I need to do to overlay one color ontop of another? Or is there a better solution?
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='Foo')
plt.legend(handles=[red_patch])

plt.show()

A: The solution I am proposing is to combine two different proxy-artists for one entry legend, as described here: Combine two Pyplot patches for legend.
The strategy is then to set the fillstyle of the first square marker to left while the other one is set to right (see http://matplotlib.org/1.3.0/examples/pylab_examples/filledmarker_demo.html). Two different colours can then be attributed to each marker in order to produce the desired two-colour legend entry.
The code below show how this can be done. Note that the numpoints=1 argument in plt.legend is important in order to display only one marker for each entry.
import matplotlib.pyplot as plt

plt.close('all')

#---- Generate a Figure ----

fig = plt.figure(figsize=(4, 4))
ax = fig.add_axes([0.15, 0.15, 0.75, 0.75])
ax.axis([0, 1, 0, 1])

#---- Define First Legend Entry ----

m1, = ax.plot([], [], c='red' , marker='s', markersize=20,
              fillstyle='left', linestyle='none')

m2, = ax.plot([], [], c='blue' , marker='s', markersize=20,
              fillstyle='right', linestyle='none')

#---- Define Second Legend Entry ----

m3, = ax.plot([], [], c='cyan' , marker='s', markersize=20,
              fillstyle='left', linestyle='none')

m4, = ax.plot([], [], c='magenta' , marker='s', markersize=20,
              fillstyle='right', linestyle='none')

#---- Plot Legend ----

ax.legend(((m2, m1), (m3, m4)), ('Foo', 'Foo2'), numpoints=1, labelspacing=2,
          loc='center', fontsize=16)

plt.show(block=False)

Which results in:

Disclaimer: This will only work for a two-colors legend entry. If more than two colours is desired, I cannot think of any other way to do this other than the approach described by @jwinterm (Python Matplotlib Multi-color Legend Entry)

A: Perhaps another hack to handle more than two patches. Make sure you order the handles/labels according to the number of columns:
from matplotlib.patches import Patch
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

pa1 = Patch(facecolor='red', edgecolor='black')
pa2 = Patch(facecolor='blue', edgecolor='black')
pa3 = Patch(facecolor='green', edgecolor='black')
#
pb1 = Patch(facecolor='pink', edgecolor='black')
pb2 = Patch(facecolor='orange', edgecolor='black')
pb3 = Patch(facecolor='purple', edgecolor='black')

ax.legend(handles=[pa1, pb1, pa2, pb2, pa3, pb3],
          labels=['', '', '', '', 'First', 'Second'],
          ncol=3, handletextpad=0.5, handlelength=1.0, columnspacing=-0.5,
          loc='center', fontsize=16)

plt.show()

which results in:

A: There is in fact a proper way to do this by implementing a custom
legend handler as explained in the matplotlib-doc under "implementing a custom legend handler" (here):
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection

# define an object that will be used by the legend
class MulticolorPatch(object):
    def __init__(self, colors):
        self.colors = colors

# define a handler for the MulticolorPatch object
class MulticolorPatchHandler(object):
    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        width, height = handlebox.width, handlebox.height
        patches = []
        for i, c in enumerate(orig_handle.colors):
            patches.append(plt.Rectangle([width/len(orig_handle.colors) * i - handlebox.xdescent,
                                          -handlebox.ydescent],
                           width / len(orig_handle.colors),
                           height,
                           facecolor=c,
                           edgecolor='none'))

        patch = PatchCollection(patches,match_original=True)

        handlebox.add_artist(patch)
        return patch

# ------ choose some colors
colors1 = ['g', 'b', 'c', 'm', 'y']
colors2 = ['k', 'r', 'k', 'r', 'k', 'r']

# ------ create a dummy-plot (just to show that it works)
f, ax = plt.subplots()
ax.plot([1,2,3,4,5], [1,4.5,2,5.5,3], c='g', lw=0.5, ls='--',
        label='... just a line')
ax.scatter(range(len(colors1)), range(len(colors1)), c=colors1)
ax.scatter([range(len(colors2))], [.5]*len(colors2), c=colors2, s=50)

# ------ get the legend-entries that are already attached to the axis
h, l = ax.get_legend_handles_labels()

# ------ append the multicolor legend patches
h.append(MulticolorPatch(colors1))
l.append("a nice multicolor legend patch")

h.append(MulticolorPatch(colors2))
l.append("and another one")

# ------ create the legend
f.legend(h, l, loc='upper left',
         handler_map={MulticolorPatch: MulticolorPatchHandler()},
         bbox_to_anchor=(.125,.875))

A: I absolutely loved @raphael's answer.
Here is a version with circles. Furthermore, I've refactored and trimmed the code a bit to make it more modular.
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

class MulticolorCircles:
    """
    For different shapes, override the ``get_patch`` method, and add the new
    class to the handler map, e.g. via

    ax_r.legend(ax_r_handles, ax_r_labels, handlelength=CONF.LEGEND_ICON_SIZE,
            borderpad=1.2, labelspacing=1.2,
            handler_map={MulticolorCircles: MulticolorHandler})
    """

    def __init__(self, face_colors, edge_colors=None, face_alpha=1,
                 radius_factor=1):
        """
        """
        assert 0 <= face_alpha <= 1, f"Invalid face_alpha: {face_alpha}"
        assert radius_factor > 0, "radius_factor must be positive"
        self.rad_factor = radius_factor
        self.fc = [mcolors.colorConverter.to_rgba(fc, alpha=face_alpha)
                   for fc in face_colors]
        self.ec = edge_colors
        if edge_colors is None:
            self.ec = ["none" for _ in self.fc]
        self.N = len(self.fc)

    def get_patch(self, width, height, idx, fc, ec):
        """
        """
        w_chunk = width / self.N
        radius = min(w_chunk / 2, height) * self.rad_factor
        xy = (w_chunk * idx + radius, radius)
        patch = plt.Circle(xy, radius, facecolor=fc, edgecolor=ec)
        return patch

    def __call__(self, width, height):
        """
        """
        patches = []
        for i, (fc, ec) in enumerate(zip(self.fc, self.ec)):
            patch = self.get_patch(width, height, i, fc, ec)
            patches.append(patch)
        result = PatchCollection(patches, match_original=True)
        #
        return result

class MulticolorHandler:
    """
    """
    @staticmethod
    def legend_artist(legend, orig_handle, fontsize, handlebox):
        """
        """
        width, height = handlebox.width, handlebox.height
        patch = orig_handle(width, height)
        handlebox.add_artist(patch)
        return patch

Sample usage and image, note that some of the legend handles have radius_factor=0.5 because the true size would be too small.
ax_handles, ax_labels = ax.get_legend_handles_labels()
ax_labels.append(AUDIOSET_LABEL)
ax_handles.append(MulticolorCircles([AUDIOSET_COLOR],
                                    face_alpha=LEGEND_SHADOW_ALPHA))
ax_labels.append(FRAUNHOFER_LABEL)
ax_handles.append(MulticolorCircles([FRAUNHOFER_COLOR],
                                    face_alpha=LEGEND_SHADOW_ALPHA))
ax_labels.append(TRAIN_SOURCE_NORMAL_LABEL)
ax_handles.append(MulticolorCircles(SHADOW_COLORS["source"],
                                    face_alpha=LEGEND_SHADOW_ALPHA))
ax_labels.append(TRAIN_TARGET_NORMAL_LABEL)
ax_handles.append(MulticolorCircles(SHADOW_COLORS["target"],
                                    face_alpha=LEGEND_SHADOW_ALPHA))
ax_labels.append(TEST_SOURCE_ANOMALY_LABEL)
ax_handles.append(MulticolorCircles(DOT_COLORS["anomaly_source"],
                                    radius_factor=LEGEND_DOT_RATIO))
ax_labels.append(TEST_TARGET_ANOMALY_LABEL)
ax_handles.append(MulticolorCircles(DOT_COLORS["anomaly_target"],
                                    radius_factor=LEGEND_DOT_RATIO))
#
ax.legend(ax_handles, ax_labels, handlelength=LEGEND_ICON_SIZE,
            borderpad=1.1, labelspacing=1.1,
            handler_map={MulticolorCircles: MulticolorHandler})

A: Probably not exactly what you're looking for, but you can do it (very) manually by placing patches and text yourself on the plot. For instance:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

red_patch = mpatches.Patch(color='red', label='Foo')
plt.legend(handles=[red_patch])

r1 = mpatches.Rectangle((0.1, 0.1), 0.18, 0.1, fill=False)
r2 = mpatches.Rectangle((0.12, 0.12), 0.03, 0.06, fill=True, color='red')
r3 = mpatches.Rectangle((0.15, 0.12), 0.03, 0.06, fill=True, color='blue')
ax.add_patch(r1)
ax.add_patch(r2)
ax.add_patch(r3)
ax.annotate('Foo', (0.2, 0.13), fontsize='x-large')

plt.show()


text:
Q: Guzzle Symfony scrape iframes inside multiple Servers I am building a scraper to scrape content using guzzle and symfony dom crawler But I run into an issue.
The page I am scraping has multiple Iframe servers They default iframe is shown when the scraper loads the page but in order to get the other servers it needs to click there buttons and so it reflects the server iframe.
How do I do that?

A: Guzzle can't render Javascript websites so it doesn't support that
There are two ways around this either check for network tabs and send the request to the ajax link they get the iframes from, or use symfony Panther as headless browser library they support javascript websites and even Bypass Cloudflare Protection


text:
Q: Performance: Calculations inside query, ES vs Mysql Calculation in select query which is faster, mysql or elastic search? Why?
{
"query" : {
  ...
  },
    "script_fields" : {
         "gross_profit" : {
                 script: "((((doc['price_in_cents'].value * 100)/(100 +#{location.gst_rate})) - doc['cost_in_cents'].value)*(doc['quantity'].value)) "
                          }
           }
       }

or
   SELECT ((price_in_cents*100)/100/(100+#{location.gst_rate})) - cost_in_cents * quantity) as gross_profit FROM ...

   location.gst_rate is a dynamic variable (Note: Using ruby on rails syntax)

Following is my mysql schema (it have many other columns and relations, not including since they are irrelevant here):
 Table Name: Sales
 Columns:
 sales_id : integer
 price_in_cents : double
 cost_in_cents : double
 quantity : tiny int

Elastic search Index:
Name: Sales
id: integer
price_in_cents : double
cost_in_cents : double
quantity : tiny int


text:
Q: React native alert shows error when having an onPress on the OK button I am trying to show an alert when using a switch (atm only on Ios), but it shows an error:
JSON value '({text = OK;})' of type NSMutableArray cannot be converted to NSString

This is an example of the code I am using:
import React, { Component } from 'react';
import { StyleSheet,Text,View,Button,TouchableOpacity,TextInput,AsyncStorage,ScrollView, Alert,Switch } from 'react-native';
import RNRestart from 'react-native-restart';

export default class ProfileScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            colorPattern: false
        }
    }

    saveThemeColour(color) {
        if(color) {
            AsyncStorage.setItem('themeColour', 'default');
            this.setState({colorPattern: true});
            Alert.alert(
                I18n.t('restart theme change'),
                [
                    {text: 'OK', onPress: () => RNRestart.Restart()}
                ],
                { cancelable: false }
            )
        }else{
            AsyncStorage.setItem('themeColour', 'white');
            this.setState({colorPattern: false});
        }
    }
    <Switch value={this.state.colorPattern} onValueChange={ (value) => this.saveThemeColour(value)}/>
}

It works fine when I just leave the title of the alert.

A: You are missing the message parameter:
Alert.alert(
  I18n.t('restart theme change'),
  <here-comes-the-message-as-string>,
  [
    {text: 'OK', onPress: () => RNRestart.Restart()}
  ],
  { cancelable: false }
)


text:
Q: Proof of generalized Siegel's mean value formula in geometry of numbers Let $\mu$ be the Haar measure defined on the space of unimodular lattices, identified with $\text{SL}(d,\mathbb R)/\text{SL}(d,\mathbb Z)$.
The classical Siegel's formula in geometry of numbers states that for $f\in L^1(\mathbb R^d)$, let $\Lambda$ be a unimodular lattice, and let
$$\hat{f}(\Lambda):= \sum_{v\in \Lambda\setminus 0} f(v).$$
Then $$\int_X \hat{f} d\mu = \int_{\mathbb R^d} f dv.$$
I wonder if there is such a generalization to this result:
For $g\in L^1((\mathbb R^d)^k)$, $1 \le k \le d$ and unimodular lattice $\Lambda$, let $\hat{g}^k(\Lambda):=\sum_{(v_1,\dots,v_k)\in \Lambda^k \setminus 0} g(v_1,\dots, v_k)$. I speculate there might be such a generalization of Siegel's mean value formula:
$$\int_X \hat{g}^k d\mu = \int_{\mathbb R^d} \dots \int_{\mathbb R^d} g(v_1,\cdots,v_k) dv_1 \cdots dv_k$$
Is this correct and proved somewhere in the literature? Or can anyone suggest a proof for it below if not too complicated from the classical Siegel's formula?

A: Such a generalization (roughly) exists, known as Rodger's Integration Formula.
See Section 1.2 of Seungki Kim's Dissertation for a reference.
Theorems 1.2 and 1.3 are of interest.

Theorem 1.2: (Rogers). Let $k < n$, and $\rho : (\mathbb{R}^n)^kk \to \mathbb{R}$ be a compactly supported,
bounded, and Borel measurable function. Then
$$
\int_{X}\sum_{\substack{v_1,\dots,v_k\in L\setminus\{0\}\\\mathsf{rank}(\langle v_1,\dots,v_k\rangle) = k}}\rho(v_1,\dots,v_k)d\mu = \int_{\mathbb{R}^n}\dots \int_{\mathbb{R}^n}\rho(x_1,\dots,x_k)dx_1\dots dx_k.
$$

Up to the requirement that one sums over rank $k$ collections of vectors $(v_1,\dots,v_k)$, this is what you want.
One can remove this restriction (to get the generalization that you want), but the formula becomes more complex --- there is an additional (additive) term on the right-hand side.
See Theorem 1.3 of the dissertation for details.


text:
Q: Sharepoint REST API with Azure AD oauth2 authentication for simple users I  am trying  to access from  my  server to  files  on sharepoint  sites with  Azure  AD   oauth2, i  created  multi-tenant Azure  AD   app  with  such permissions

after this  i am going  through standard  oauth2  process  to  obtain tokens:
i  redirect user to https://login.windows.net/common/oauth2/authorize?client_id=123XXXXXXXXf4d5d4512&response_type=code&redirect_uri=https%3A%2F%2FdXXXXXXX%2Foffice365_oauthcallback.html
and  when  admin  user  log  in then  everything  is  going  smoothly, but  ordinary  user  can not  log in, he  is  getting:

Additional technical information:
Correlation ID: d81a1cca-1c4f-4da1-9162-88ba74d57775
Timestamp: 2015-07-01 09:49:53Z
AADSTS90093: This operation can only be performed by an administrator.
  Sign out and sign in as an administrator or contact one of your
  organization's administrators.

i  assume  that  he  is  getting  this  because  can not  use  some  permissions
may  same  one  help  me  to  choose   correct  permissions  which  will  allow  to  me  to  authorize  with  Azure  AD  oauth2  ordinary  user,  not  admin  only.
I  was  trying  to remove  access to Azure permission  from  app  and  leave  access  to  sharepoint  only, but  as  result  I   am getting

AADSTS65005: The client application has requested access to resource "00000002-0000-0000-c000-000000000000". This request has failed because the client has not specified this resource in its requiredResourceAccess list.%0d%0aTrace ID%3a 97d7ddff-0eaf-487c-83be-e277970f9339%0d%0aCorrelation ID%3a dcf33c54-fb51-46d9-9ee5-09db8d425b0d%0d%0aTimestamp%3a 2015-07-01 09%3a58%3a05Z

i  was  trying  to  follow  https://social.msdn.microsoft.com/Forums/en-US/088c7f00-70ae-47ac-abe6-bdf6b5778468/aadsts65005-the-request-has-failed-because-the-client-has-not-specified-this-resource-in-its?forum=WindowsAzureAD  and  put  &resorce=  param  as  sharepoint  site
https://login.microsoftonline.com/common/oauth2/authorize?client_id=123ae4***5d4512&response_type=code&redirect_uri=https%3A%2F%2FdXXXXXXX%2Foffice365_oauthcallback.html&resource=https://SITE.sharepoint.com/DP/
and  as  result i  got this

AADSTS50001: Resource https://SITE.sharepoint.com/DP/ is not
  registered for the account. Trace ID:
  b30da866-5a89-4962-9617-92a7cfe649b9 Correlation ID:
  48a5ef84-8211-4588-8339-05ba7154fbc6

I put   &resorce=  param  as  sharepoint  site DOmain
https://login.microsoftonline.com/common/oauth2/authorize?client_id=123ae4***5d4512&response_type=code&redirect_uri=https%3A%2F%2FdXXXXXXX%2Foffice365_oauthcallback.html&resource=https://SITE.sharepoint.com
and  got

Additional technical information: Correlation ID:
  7f006d85-a72a-480f-b92e-0c706190f73e Timestamp: 2015-07-01 10:13:17Z
  AADSTS90093: This operation can only be performed by an administrator.
  Sign out and sign in as an administrator or contact one of your
  organization's administrators.

what i  am  doing  wrong?  is  there  are  any  way to  make  oauth2  through Azure AD   for  ordinary  user,  not  just  for  admin?

A: I  found  answer on this   page http://blog.beecomedigital.com/2015/06/08/aadsts90093-calling-principal-cannot-consent-due-to-lack-of-permissions/  it  contains  all  permissions  you   may  set  for  AD  App which  do not  require  admin  permissions  to  been  accepted.


text:
Q: Excel VBA - Move rows if time/date in column is more than 6 hours ago I'm not sure if this is possible? I'm trying to move items from my list that haven't been touched in the last six hours to a new sheet to be worked. How do I copy/move rows using a formula instead of just a match text scenario?
My code so far:
With Sheets("Scheduled")
    .Select
    Firstrow = .UsedRange.Cells(2).Offset(1, 0).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
    For Lrow = Lastrow To Firstrow Step -1
       With .Cells(Lrow, "C")
            If Not IsError(.Value) Then
                If .Value <> "Scheduled" Then
                    'Copy all "Not Scheduled" reports to the "Tracker" sheet and remove them from "Scheduled".
                    .EntireRow.Copy Sheets("Tracker").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                    .EntireRow.Delete
                End If
            End If
        End With
    Next Lrow
End With

This code isn't exactly the section I'm talking about, but this is how I'm moving rows around other parts of the workbook.

A: *

*Change the C column letter in,
With .Cells(Lrow, "C")

...to the column letter with the datetime value you want to check.

*Change,
  If Not IsError(.Value) Then

... to,
  If IsNumeric(.Value) Then   'this also moves blanks

*Change the comparison from,
     If .Value <> "Scheduled" Then

... to,
     If .Value2 < (Now - TimeSerial(6, 0, 0)) Then

*Change the Tracker worksheet name in,
      .EntireRow.Copy Sheets("Tracker").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)

... to whatever the destination worksheet's name is.


text:
Q: yii2 creating custom based Rest API I am creating my own custom based action for some calculation, which has to be send by restful api in json. The problem is when i create the controller inherited from activecontroller, then for the index action it asks a model class.
I must need to use index action with my own custom based calculation which does not need to be store in the database so i actually do not need to create model class at all. This is first time i am using activecontroller so i am not sure how to make the index page act as according to my needs.
I am able to create my own custom based action with any name i want  e.g.
 public function actionFast()
    {
        echo "XXX";
    }

and inside the config/ web.php
'urlManager' => [
            'showScriptName' => false,
            'enablePrettyUrl' => true
            ,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => ['Apprest/Fast'], 'extraPatterns' => ['GET dast' => 'fast']],
            ],
        ],

but instead of my custom "Fast" action i need to use index action for all kinds of calculations. Is there a way to do that?
Secondly i want to make this url restricted for GET only url , is there a way to make send the user to 404 error incase he tries to post on this page?

A: If you don't have model, you can extends right from yii\rest\Controller and add actions that you need
Here you can see example:
namespace api\controllers;
use yii\rest\Controller;
class MyController extends Controller
{
public function actionFast()
    {
        echo "XXX";
    }
}


text:
Q: Google Maps search box with dragable marker and input box I'm using google maps api and need to show a marker with a search box, this marker will use the lat and long I have on my database but will change if dragged or someone uses the search box. I managed to load the map and center it on the coordinates but it doesn't shows the marker, after I use the search box all works.
I tried adding a marker in the beginning of the code but without success, it creates a new marker when I used the functions:
var mapOptions = {
        zoom: zoom,
        center: LatLng,
        panControl: false,
        zoomControl: false,
        scaleControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById('map'),mapOptions);
    var latitude = ;
    var longitude = ;
    var zoom = "+MapZoom+";

    var LatLng = new google.maps.LatLng(51.501476, -0.140634);
    var marker = new google.maps.Marker({
        position: LatLng,
        map: map,
        title: '"+Latitude+"',
        draggable: true
    });

This is my current code, I'm sure I'm just missing something any help would be much appreciated
function initialize() {

var markers = [];
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
  new google.maps.LatLng(51.501476, -0.140634));
    map.fitBounds(defaultBounds);
var input = (document.getElementById('pacinput')
);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox((input));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
  return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
  marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {

  var marker = new google.maps.Marker({
    draggable: true,
    map: map,

    title: place.name,
    position: place.geometry.location
  });
  // drag response
  google.maps.event.addListener(marker, 'dragend', function(e) {
    displayPosition(this.getPosition());
  });
  // click response
  google.maps.event.addListener(marker, 'click', function(e) {
    displayPosition(this.getPosition());
  });
  markers.push(marker);
  bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
// displays a position on two <input> elements
function displayPosition(pos) {
document.getElementById('Latitude').value = pos.lat();
document.getElementById('Longitude').value = pos.lng();
}
}
google.maps.event.addDomListener(window, 'load', initialize);
initialize();
</script>"

A: as per my understanding you want marker on load of page to the same location where your map is centered try using this
var map;
var marker;
$(document).ready(function(){
    initialize();
    drawmarker();
    darggable();
});

function initialize() {
  var mapProp = {
    center:new google.maps.LatLng(51.508742,-0.120850),
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

}
function drawmarker(){
    marker = new google.maps.Marker({
        position : new google.maps.LatLng(51.508742,-0.120850),
        title:"this s it",
        map : map,
        draggable:true,
    })
}

make your marker as global now use method on dragend
function darggable(){
 google.maps.event.addListener(marker, 'dragend', function(e) {
                console.log(e.latLng.lat(),e.latLng.lng())

              });
}

now you get the latlng now use it to display in the text box


text:
Q: A Record or Hosts File on a Windows 2003 DNS Server I have a Windows 2003 DNS server that forwards on to OpenDNS. I want to set it up so that when someone requests dev.mydomain.com instead of requesting the IP from OpenDNS it returns a local IP address.
The reason I want to do this is because I have a local dev server called dev locally and dev.mydomain externally. I'd like it if I'm in the office and I type in dev.mydomain, I don't have to go through the internet, because I believe although I'm not sure that that is slower.
Thoughts?

A: You should be able to add an entry on your server's hosts file like this:
192.168.0.2       dev.mydomain.com
I don't know about Server 2003, but in Vista, the hosts file is in:
c:\Windows\System32\drivers\etc\hosts
You'll probably need to take off the read-only protection in order to modify it.

A: I found the solution. I created a forward lookup zone for dev.mydomain.com and created a blank a record pointing at the IP I wanted.


text:
Q: Sanitize and send checkbox results in a form I have a WordPress based website that includes a booking <form> on a 'Page Template'.
As I am unfamiliar with PHP, I'm not too sure exactly where I am going wrong.
I need to include some checkboxes for the services offered by the website in a <form> and have the following file to work with:
<?php
/*
 * Template Name: Booking Page
 */
?>

<?php
    // Sanitize data, or initialize if they don't exist.
    $clientname = isset($_POST['ci_name']) ? esc_html(trim($_POST['ci_name'])) : '';
    $email = isset($_POST['ci_email']) ? esc_html(trim($_POST['ci_email'])) : '';
            $services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : ''; // My Edit
    $message = isset($_POST['ci_comments']) ? sanitize_text_field(stripslashes($_POST['ci_comments'])) : '';

    $errorString = '';
    $emailSent = false;

    if(isset($_POST['send_booking']))
    {
        // We are here because the form was submitted. Let's validate!

        if(empty($clientname) or mb_strlen($clientname) < 2)
            $errorString .= '
 '.__('Your name is required.', 'ci_theme').'
';

        if(empty($email) or !is_email($email))
            $errorString .= '
 '.__('A valid email is required.', 'ci_theme').'
';

                // Services is optional, so, no check.  // My Edit
        // Message is optional, so, no check.

        // Alright, lets send the email already!
        if(empty($errorString))
        {
            $mailbody  = __("Name:", 'ci_theme') . " " . $clientname . "\n";
            $mailbody .= __("Email:", 'ci_theme') . " " . $email . "\n";
                    $mailbody .= __("Services Selected:", 'ci_theme') . " " . $services . "\n"; // My Edit
            $mailbody .= __("Message:", 'ci_theme') . " " . $message . "\n";

            // If you want to receive the email using the address of the sender, comment the next $emailSent = ... line
            // and uncomment the one after it.
            // Keep in mind the following comment from the wp_mail() function source:
            /* If we don't have an email from the input headers default to wordpress@$sitename
            * Some hosts will block outgoing mail from this address if it doesn't exist but
            * there's no easy alternative. Defaulting to admin_email might appear to be another
            * option but some hosts may refuse to relay mail from an unknown domain. See
            * http://trac.wordpress.org/ticket/5007.
            */
            $emailSent = wp_mail(ci_setting('booking_form_email'), get_option('blogname').' - '. __('Booking form', 'ci_theme'), $mailbody);
            //$emailSent = wp_mail(ci_setting('contact_form_email'), get_option('blogname').' - '. __('Contact form', 'ci_theme'), $mailbody, 'From: "'.$clientname.'" <'.$email.'>');
        }

    }
?>

<?php get_header(); ?>

                    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

                            <article <?php post_class('entry'); ?>>
                                <?php if(!empty($errorString)): ?>

                                        <?php echo $errorString; ?>

                                <?php endif; ?>

                                <?php if($emailSent===true): ?>

 <?php _e('Your booking request has been sent. We will contact you as soon as possible.', 'ci_theme'); ?>

                                <?php elseif($emailSent===false and isset($_POST['send_booking']) and $errorString==''): ?>

<?php _e('There was a problem while sending the email. Please try again later.', 'ci_theme'); ?>

                                <?php endif; ?>

                                <?php the_content(); ?>

                                <?php if(  !isset($_POST['send_booking'])  or  (isset($_POST['send_booking']) and !empty($errorString))  ): ?>

                                <form class="booking" action="<?php the_permalink(); ?>" method="post">

                                            <input type="text" name="ci_name" id="ci_name" placeholder="<?php _e('your name', 'ci_theme'); ?>" value="<?php echo esc_attr($clientname); ?>">

                                            <input type="email" name="ci_email" id="ci_email" class="datepicker" placeholder="<?php _e('Your Email', 'ci_theme'); ?>" value="<?php echo esc_attr($email); ?>">

Please tick any of the following services if you would like to include them in your package:

<input type="checkbox" name="services[]" <?php checked($services, 'Reiki'); ?> value="Reiki"> Reiki

<input type="checkbox" name="services[]" <?php checked($services, 'Private Personal Training'); ?> value="Private Personal Training"> Private Personal Training

<input type="checkbox" name="services[]" <?php checked($services, 'Walking'); ?> value="Walking"> Walking

<input type="checkbox" name="services[]" <?php checked($services, 'Boot Camp'); ?> value="Boot Camp"> Boot Camp

<input type="checkbox" name="services[]" <?php checked($services, 'Relaxation Massage'); ?> value="Relaxation Massage"> Relaxation Massage

<input type="checkbox" name="services[]" <?php checked($services, 'Meditation Circle'); ?> value="Meditation Circle"> Meditation Circle

<input type="checkbox" name="services[]" <?php checked($services, 'Colour Workshop'); ?> value="Colour Workshop"> Colour Workshop

                                            <textarea name="ci_comments" id="ci_comments" cols="30" rows="10" placeholder="<?php _e('Message', 'ci_theme'); ?>"></textarea>

                                            <button type="submit" name="send_booking"><?php _e('Submit', 'ci_theme'); ?></button>

                                </form>
                                <?php endif; ?>

                        <?php endwhile; endif; ?>
                        <?php get_sidebar(); ?>

<?php get_footer(); ?>

In the code above, I have placed the HTML markup for the checkboxes in, and it appears something similar to this on the front-end of the website:

However, it doesn't seem to include the checkbox information in the email that is sent off.  The email for this simply reads Services Selected: without the names of the services ticked:

My edits which can be found in the code above are:
Sanitize:
$services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : '';

Message to be sent:
$mailbody .= __("Services Selected:", 'ci_theme') . " " . $services . "\n";

Checkboxes:
<input type="checkbox" name="services[]" <?php checked($services, 'Relaxation Massage'); ?> value="Relaxation Massage"> Relaxation Massage

How do I implement, sanitize, send and receive the results of the checkboxes using the <form> I currently have?
Any help would be greatly appreciated,
Thanks.

A: You didn't store any value in your $service variable.
Just put this code
    $clientname = isset($_POST['ci_name']) ? esc_html(trim($_POST['ci_name'])) : '';
    $email = isset($_POST['ci_email']) ? esc_html(trim($_POST['ci_email'])) : '';
    $services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : ''; // My Edit
    $message = isset($_POST['ci_comments']) ? sanitize_text_field(stripslashes($_POST['ci_comments'])) : '';

    $errorString = '';
    $emailSent = false;

    if(isset($_POST['send_booking']))
    {
         print_r($_POST);exit; // You can see here your post variable value in array.
    }

Instead of
$services = isset($_POST['services']); // My Edit

Read more about the ternary operator: http://php.net/ma...operators.comparison.php


text:
Q: getting error while declaring vector of vector Is this wrong method of declaring vector of vector
vector<vector<bool>> visited(100, vector<bool>(100,false));

getting error as:
 Line 5: Char 34: error: expected identifier before numeric constant
 vector<vector<bool>> visited(100, vector<bool>(100,false));

i declared it in starting of solution class
in below program
#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    int nr,nc;
    //vector<vector<bool>> visited(1000,vector<bool>(1000,false)) ;
    vector<vector<bool>> visited(100, vector<bool>(100,false));
    bool dfs(vector<vector<char>>& board,string word,int i,int j,int cr){
        visited[i][j]=true;
        if(cr==word.length())
            return true;
        if(cr>word.length())
            return false;
        if(j+1<nc && board[i][j+1]==word[cr] && !visted[i][j+1])
            return dfs(board,word,i,j+1,cr+1);
        if(j-1>=0 && board[i][j-1]==word[cr] && !visited[i][j-1])
            return dfs(board,word,i,j-1,cr+1);
        if(i+1<nr && board[i+1][j]==word[cr] && !visited[i+1][j])
            return dfs(board,word,i+1,j,cr+1);
        if(i-1>=0 && board[i-1][j]==word[cr] && !visited[i-1][j])
            return dfs(board,word,i-1,j,cr+1);
        return false;
    }
   bool dfs_help(vector<vector<char>> &board,string word){
       for(int i=0;i<board.size();i++){
            for(int j=0;j<board[0].size();j++){
                    visited[i][j]=false;
                }
            }
        }

       for(int i=0;i<board.size();i++){
            for(int j=0;j<board[0].size();j++){
                if(board[i][j]==word[0]){
                    visited[i][j]=true;
                    if(dfs(board,word,i,j,1))
                        return true;
                }
            }
        }
    return false;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        nr = board.size();
        nc = board[0].size();
        vector<string> ans;
        for(string v : words){
            if(dfs_help(board,v))
                ans.push_back(v);
        }
        sort(ans.begin(),ans.end());
        return ans;
    }
};
int main(){

}

A: If you want to construct a member variable such as std::vector with sizing arguments, the way you do that is to use the member initialization list of the Solution constructor.
To do this, you should remove the line that is giving the error, and instead add a default constructor to Solution so that the member(s) can be initialized:
class Solution
{
   //...
   Solution() : visited(100, std::vector<bool>(100,false)), nr(0), nc(0) {}
   //...
};


text:
Q: Spring MVC file not found exception when creating bean I have the following directory structure:

I am creating a bean the following way:
@Configuration
public class Create {
public static String path = new File("src/main/webapp/resources/nodes.txt").getAbsolutePath();
@Bean
public static Graph returnGraph() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
[rest of the code]
    return graph;
}
}

I want to read the file nodes.txt located in DeployedResources/webapp/resources
However I get a java.io.FileNotFoundException. Now this works if I specify the absolute path if my file is located in Desktop for example. But I cannot do this as then it wont work on another machine.
I am trying to specify a relative path, so it will work on all machines,but when I run it as a Spring MVC application, the working directory changes. What can I do so the file can be read from any machine?

A: Try to replace this path:
 new File("src/main/webapp/resources/nodes.txt").getAbsolutePath();

With removing getAbsolutePath():
  new File("src/main/webapp/resources/nodes.txt");


text:
Q: Regex Regular Expression 2.7 I'm tinkering with Regex and I'm trying to edit a string so that it will do the following...
Original text
Mr. Bob had 1.3 pounds, he didn't have much. Did he care? Joe Bloggs, Esq. thinks he does. However, he paused... But, what will you do with the .7?

Actual Outcome
Mr.
Bob had 1.3 pounds, he didn't have much.
Did he care?
Joe Bloggs, Esq. thinks he does.
However, he paused... But, what will you do with the .7?

Expected Outcome
Mr. Bob had 1.3 pounds, he didn't have much.
Did he care?
Joe Bloggs, Esq. thinks he does.
However, he paused...
But, what will you do with the .7?

so far my statement is..
print re.sub(r'(?<!..\.|.Mr|Esq|Mrs|.Ms)[.?]\s+', '\\g<0>\n', s)

A: You can separate out the Negative look-behinds to overcome the fixed-width pattern requirement like this -
r'(?<!Mr)(?<!Mrs)(?<!Ms)(?<!Esq)(?<!e.g)(?<!i.e)[.?]\s+'

This works -
>>> print re.sub(r'(?<!Mr)(?<!Mrs)(?<!Ms)(?<!Esq)(?<!e.g)(?<!i.e)[.?]\s+', '\\g<0>\n', s)
Mr. Bob had 1.3 pounds, he didn't have much.
Did he care?
Joe Bloggs, Esq. thinks he does.
However, he paused...
But, what will you do with the .7?

>>>

A: Your regex has .Mr, which requires Mr to be preceded by another character.  But your Mr appears at the beginning of the string, so there's no character before it.
I don't see any obvious way around this using the builtin re module.  It requires lookbehinds to have a fixed length, so there's no way to have one lookbehind for both Esq and Mr-not-preceded-by-anything.  However, the regex library doesn't have this limitation, so you could do it with that library, using a simpler regex to boot:
>>> print regex.sub(r'(?<!\.|Mr|Esq|Mrs|Ms)[.?]\s+', '\\g<0>\n', s)
Mr. Bob had 1.3 pounds, he didn't have much.
Did he care?
Joe Bloggs, Esq. thinks he does.
However, he paused... But, what will you do with the .7?

(Edit: Other answers have now shown that it can be done with re by using separate lookbehinds.  Still might be worth looking at regex, though, it has some useful differences from `re.)

A: I have changed your negative lookbehind from the regex. It works for the provided input. Not sure how it will react for your others.
print re.sub(r'(?<!Mr)(?<!Esq)(?<!Mrs)(?<!Ms)[.?!]\s+', '\\g<0>\n', s)


text:
Q: System.Net.WebExeption CR must be followed by LF I am using this code for read content from URL:
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(urlAddress);
        req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";
        using (var resp = req.GetResponse())
        {
            var html = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            return html;
        }

+ In app.config I have:
  <system.net>
    <settings>
      <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
  </system.net>

In my pc - where I code the program it work nice, but when I make exe file and try to run on my webserver I am getting error:
The server commited a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF

How can I fix this error.
Thank you for your help!

A: USE This
if (res.Headers.AllKeys.Contains("Vary"))
    {
        res.Headers["Vary"] = "Accept";
    }
    else
    {
        res.Headers.Add("Vary", "Accept");
    }


text:
Q: Why don't Python sets preserve insertion order? I was surprised to discover recently that while dicts are guaranteed to preserve insertion order in Python 3.7+, sets are not:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> d
{'a': 1, 'b': 2, 'c': 3}
>>> d['d'] = 4
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

>>> s = {'a', 'b', 'c'}
>>> s
{'b', 'a', 'c'}
>>> s.add('d')
>>> s
{'d', 'b', 'a', 'c'}

What is the rationale for this difference?  Do the same efficiency improvements that led the Python team to change the dict implementation not apply to sets as well?
I'm not looking for pointers to ordered-set implementations or ways to use dicts as stand-ins for sets.  I'm just wondering why the Python team didn't make built-in sets preserve order at the same time they did so for dicts.

A: Discussions
Your question is germane and has already been heavily discussed on python-devs.  R. Hettinger shared a list of rationales in that thread.  The state of the issue appeared open-ended, shortly after this detailed reply from T. Peters.  Some time later (c. 2022), the discussion reignited elsewhere on python-ideas.
In short, the implementation of modern dicts that preserves insertion order is unique and not considered appropriate with sets.  In particular, dicts are used everywhere to run Python (e.g. __dict__ in namespaces of objects).   A major motivation behind the modern dict was to reduce size, making Python more memory-efficient overall.  In contrast, sets are less prevalent than dicts within Python's core and thus dissuade such a refactoring.  See also R. Hettinger's talk on the modern dict implementation.

Perspectives
The unordered nature of sets in Python parallels the behavior of mathematical sets.  Order is not guaranteed.

The corresponding mathematical concept is unordered and it would be weird to impose
such as order - R. Hettinger

If order of any kind were introduced to sets in Python, then this behavior would comply with a completely separate mathematical structure, namely an ordered set (or Oset).  Osets play a separate roll in mathematics, particularly in combinatorics. One practical application of Osets is observed in changing of bells.
Having unordered sets are consistent with a very generic and ubiquitous data structure that unpins most modern math, i.e. Set Theory.  I submit, unordered sets in Python are good to have.
See also related posts that expand on this topic:

*

*Converting a list to a set changes element order

*Get unique values from a list in python

*Does Python have an ordered set

A: Sets and dicts are optimized for different use-cases. The primary use of a set is fast membership testing, which is order agnostic. For dicts, cost of the lookup is the most critical operation, and the key is more likely to be present. With sets, the presence or absence of an element is not known in advance, and so the set implementation needs to optimize for both the found and not-found case. Also, some optimizations for common set operations such as union and intersection make it difficult to retain set ordering without degrading performance.
While both data structures are hash based, it's a common misconception that sets are just implemented as dicts with null values. Even before the compact dict implementation in CPython 3.6, the set and dict implementations already differed significantly, with little code reuse. For example, dicts use randomized probing, but sets use a combination of linear probing and open addressing, to improve cache locality. The initial linear probe (default 9 steps in CPython) will check a series of adjacent key/hash pairs, improving performance by reducing the cost of hash collision handling - consecutive memory access is cheaper than scattered probes.

*

*dictobject.c - master, v3.5.9

*setobject.c - master, v3.5.9

*issue18771 - changeset to reduce the cost of hash collisions for set objects in Python 3.4.

It would be possible in theory to change CPython's set implementation to be similar to the compact dict, but in practice there are drawbacks, and notable core developers were opposed to making such a change.

Sets remain unordered. (Why? The usage patterns are different. Also, different implementation.)

– Guido van Rossum

Sets use a different algorithm that isn't as amendable to retaining insertion order.
Set-to-set operations lose their flexibility and optimizations if order is required. Set mathematics are defined in terms of unordered sets. In short, set ordering isn't in the immediate future.

– Raymond Hettinger
A detailed discussion about whether to compactify sets for 3.7, and why it was decided against, can be found in the python-dev mailing lists.
In summary, the main points are: different usage patterns (insertion ordering dicts such as **kwargs is useful, less so for sets), space savings for compacting sets are less significant (because there are only key + hash arrays to densify, as opposed to key + hash + value arrays), and the aforementioned linear probing optimization which sets currently use is incompatible with a compact implementation.
I will reproduce Raymond's post below which covers the most important points.

On Sep 14, 2016, at 3:50 PM, Eric Snow  wrote:

Then, I'll do same to sets.

Unless I've misunderstood, Raymond was opposed to making a similar
change to set.

That's right.  Here are a few thoughts on the subject before people
starting running wild.

*

*For the compact dict, the space savings was a net win with the additional space consumed by the indices and the overallocation for
the key/value/hash arrays being more than offset by the improved
density of key/value/hash arrays.   However for sets, the net was much
less favorable because we still need the indices and overallocation
but can only offset the space cost by densifying only two of the three
arrays.  In other words, compacting makes more sense when you have
wasted space for keys, values, and hashes.  If you lose one of those
three, it stops being compelling.

*The use pattern for sets is different from dicts.  The former has more hit or miss lookups.  The latter tends to have fewer missing key
lookups. Also, some of the optimizations for the set-to-set operations
make it difficult to retain set ordering without impacting
performance.

*I pursued alternative path to improve set performance.  Instead of compacting (which wasn't much of space win and incurred the cost of an
additional indirection), I added linear probing to reduce the cost of
collisions and improve cache performance.  This improvement is
incompatible with the compacting approach I advocated for
dictionaries.

*For now, the ordering side-effect on dictionaries is non-guaranteed, so it is premature to start insisting the sets become ordered as well.
The docs already link to a recipe for creating an OrderedSet (
https://code.activestate.com/recipes/576694/ ) but it seems like the
uptake has been nearly zero.  Also, now that Eric Snow has given us a
fast OrderedDict, it is easier than ever to   build an OrderedSet from
MutableSet and OrderedDict, but again I haven't observed any real
interest because typical set-to-set data analytics don't really need
or care about ordering.  Likewise, the primary use of fast membership
testings is order agnostic.

*That said, I do think there is room to add alternative set implementations to PyPI.  In particular, there are some interesting
special cases for orderable data where set-to-set operations can be
sped-up by comparing entire ranges of keys (see
https://code.activestate.com/recipes/230113-implementation-of-sets-using-sorted-lists
for a starting point).  IIRC, PyPI already has code for set-like bloom
filters and cuckoo hashing.

*I understanding that it is exciting to have a major block of code accepted into the Python core but that shouldn't open to floodgates to
engaging in more major rewrites of other datatypes unless we're sure
that it is warranted.

– Raymond Hettinger

From [Python-Dev] Python 3.6 dict becomes compact and gets a private version; and keywords become ordered, Sept 2016.


text:
Q: Can a laser class be lowered by lowering the input duty cycle? According to this description, class II lasers have a power output of less than 1mW, class IIIa lasers have a power output of 1-5mW, and class IIIb have a power output of 5-500mW.
Can a class IIIb 25mW 5V laser be turned into a class II 0.5mW laser simply by powering it with a PWM signal at a 2% duty cycle?

A:
Can a class IIIb 25mW 5V laser be turned into a class II 0.5mW laser simply by powering it with a PWM signal at a 2% duty cycle?

One of the requirements for laser safety is that the power output must be limited under foreseeable single fault conditions.
One foreseeable fault condition would be if the PWM signal were somehow stuck at the high level. For example, this could happen due to a software fault causing the PWM to stop switching while in the high state; or due to a physical fault like a bit of wire falling between the pwm signal wire and a power supply wire.
If you added sufficient safeguards (maybe fuses or clamp circuits) to ensure that such faults couldn't result in an unsafe laser output power, you could probably get your system certified as class 2.
(Note that current practice uses "class 1", "class 2", etc. The old ratings in "class I", "class II", "class III" are obsolete).


text:
Q: PathParam value null in Jersey web service I'm new to web services and writing code to call Jersey web service in Android. But I'm getting null as parameter values of PathParam.
Please help me out in getting what's wrong with my code.
Here is the code for web service call in Android:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

httpPost.setHeader("content-type", "application/json");
JSONObject data = new JSONObject();

try {
   data.put("email_id", strEmailId);
   data.put("password", strPassword);
   Log.d("1", data.toString());
   HttpEntity entity;
   StringEntity s = new StringEntity(data.toString());
   entity = s;
   httpPost.setEntity(entity);
   HttpResponse response = httpClient.execute(httpPost);
}

This is the web service code:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/dbconnect")
public String connectToDbTest(@PathParam("email_id") String email_id,@PathParam("password") String password) {
   System.out.println(email_id+" "+password);
}

A: I am not sure about the use of
    StringEntity
class, but on the server code, if you are using Path parameters, the parameters should be declared in the template before they are used. e.g.
    @Path("/dbconnect/{email_id}/{password}")

and the URL received on server should be
    protocol://server/context/dbconnect/email@id.com/password

Though it is a very bad idea to pass password through url, but functionally, it will work.


text:
Q: Atlassian JavaScript load error We tried to load scripts but something went wrong We tried to load scripts but something went wrong.
Please make sure that your network settings allow you to download scripts from the following domain:
https://aid-frontend.prod.atl-paas.net/atlassian-id/front-end/4.5.0
Tried Google Chrome, Firefox, Internet explorer also tried with different PC.
Not able to login into bitbucket

A: I'm using Chrome Version 77.0.3865.120 (Official Build) (64-bit). I got the same error trying to log in to my group's Atlassian site, and I was able to fix it by specifically allowing JavaScript from Atlassian:

*

*Open Chrome settings

*Click on Advanced

*Click on Privacy and Security

*Click on Site Settings

*Click on JavaScript

*Make sure JavaScript is set to allowed

*Next to Allow, click Add

*Paste the URL from the error message in and click Add

A: I've faced a similar problem recently while traveling and trying to work from a new location.
First I've tried the steps from the previous answer which unfortunately didn't help  me (but they definitely may be useful in a different case scenario).
I'm renting a house with an existing pre-configured WIFI router which I could get an access to manage it over the web UI.
I'm not sure which of the following helped me. I did the following changes to the router configuration:

*

*Added the 8.8.8.8 as a primary DNS Server

*Enabled IPV6

*Disabled the built-in firewall (this one is the more likely one which fixed the issue)


text:
Q: How standard C++ input output streams have to handle intXX_t types? According to answers to this questions Is overloading on all of the fundamental integer types is sufficient to capture all integers? overloading of all fundamental types may not be able to handle types like int8_t int64_t etc. On another side according to documentation std::ostream formatted output and std::istream formatted input is implemented exactly by overloading all fundamental types. So on platform where int8_t and others could not be handled by such overloading how C++ streams would have to handle them? Would it fail to compile? Would standard library implementors have to provide additional undocumented methods? Something else?

A: For integer types, [istream] defines:
basic_istream<charT,traits>& operator>>(bool& n);
basic_istream<charT,traits>& operator>>(short& n);
basic_istream<charT,traits>& operator>>(unsigned short& n);
basic_istream<charT,traits>& operator>>(int& n);
basic_istream<charT,traits>& operator>>(unsigned int& n);
basic_istream<charT,traits>& operator>>(long& n);
basic_istream<charT,traits>& operator>>(unsigned long& n);
basic_istream<charT,traits>& operator>>(long long& n);
basic_istream<charT,traits>& operator>>(unsigned long long& n);

Any code of the form is >> x may fail to compile if x is an integer type that's not in that list.
As a quality of implementation issue, an implementation which offers extended integer types could add operator>> overloads for those types. This is permitted by [member.functions]/2 (as noted by hvd in comments), talking about classes in the standard library:

An implementation may declare additional non-virtual member function signatures within a class:
[...]

*

*by adding a member function signature for a member function name.

A call to a member function signature described in the C ++ standard library behaves as if the implementation declares no additional member function signatures.

This is a stronger guarantee than the general rule that implementations may add extensions that don't break conforming programs.  The behaviour of conforming programs using SFINAE might be affected by the presence of the extra overloads.

For output, integer types not in the list will be implicitly convertible to another integer type which is in the list.

A:
So on platform where int8_t and others could not be handled by such overloading how C++ streams would have to handle them?

As far as integer insertion is concerned (operator<<), it would handle them in accord with standard C++ overload resolution. Extended integer types are still integer types and follow the rules of implicit conversion for the purpose of overload resolution.
For example, int8_t can be upconverted to any signed integer type large enough to hold it. So if int8_t is an extended integer type rather than an alias of the standard integer types, it can be upconverted to one of the standard ones, in accord with overload resolution rules.
For integer extraction (operator>>), this requires a non-const reference to a live integer, so conversion is not possible. Therefore, if you do not provide one of the explicit types that operator>> is overloaded for, your code should fail to compile.
The best you might get is if an implementation adds overloads specifically for those types, but you can't rely on that.
It should be noted that C++17's new to_chars and from_chars are explicitly stated by the standard to have overloads for all signed&unsigned integer types (and char). So that includes extended integer types.

Would it fail to compile?

For insertion, that depends on the types used. int8_t is safe because there are standard integer types that are larger than it. It may have different behavior than you expect, but it will work.
By contrast, there is no guarantee that int_least64_t or intmax_t is not larger than long long. And implicit conversion can't go from larger to smaller. In those cases, you get a compile error.
For extraction, you get compilation failures if you don't match the types.

Would standard library implementors have to provide additional undocumented methods?

No. They are permitted to do so, but that's not something you can rely on.

int8_t is a special case because of the treatment of how it can be implemented.
char serves double duty as a byte-sized type and a character type. Because it's a character type, iostream operations will treat uses of char differently from how it treats integer types. With integers, it will parse/generate integer strings. With a character, it assumes you mean to read a character.
A valid implementation of int8_t could be as an alias of signed char or just char if it is signed. As such, use of it with stream operations will treat it as a character.
A valid implementation of int8_t could be as an extended integer type, a type which is distinct from char. As such, the value will be upconverted to a larger integer type that matches one of the standard ones, in accord with overload resolution rules. And therefore, it will call one of these.


text:
Q: Stomp over socket using sockjs can't connect with Spring 4 WebSocket Trying to use Spring 4 WebSocket with STOMP over socket using sockjs.
And i faced a problem.
My configuration:
websocket.xml - part of spring context
<websocket:message-broker application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/ws">
        <websocket:sockjs/>
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>

Controller code:
@MessageMapping("/ws")
@SendTo("/topic/ws")
public AjaxResponse hello() throws Exception {
    AjaxResponse ajaxResponse = new AjaxResponse();
    ajaxResponse.setSuccess(true);
    ajaxResponse.addSuccessMessage("WEB SOCKET!!! HELL YEAH!");
    return ajaxResponse;
}

Client side:
var socket = new SockJS("<c:url value='/ws'/>");
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
    alert('Connected: ' + frame);
    stompClient.send("/app/ws", {}, {});
    stompClient.subscribe('/topic/ws', function(response){
        alert(response.success);
    });
});

Output:
Opening Web Socket... stomp.js:130
GET http://localhost:8080/ws/info 404 (Not Found) sockjs-0.3.js:807
Whoops! Lost connection to undefined stomp.js:130

What i do wrong?
I've found examples in google (TickerStocks or something like that, greeting applications (example of Spring)) and all of them give me the same error. I trying use WebSocket with handshake (without sockjs) - same result).
ADDITION INFORMATION:
Method public AjaxResponse hello(); placed in IndexController on root context "/". So i can provide full path: http://localhost:8080/ws.
To deploy tested tomcat7 and tomcat8.

A: I follow Boris The Spider advice and i started use Java Configuration (AppConfig and WebInit files) instead of XML configuration files. When i finished migration - i tried websockets - and it is works! I thought that the main problem was in XML configuration for WebSocket.

A: I think your issue can be the same of this one and its accepted answer can apply.
In short: check how you mapped your DispatcherServlet.  For your endpoint URL to be http://localhost:8080/ws the DispatcherServlet and your application contexte root should be set as "/".
It should be something like this, in your web.xml:
<servlet>
  <servlet-name>WebSocketDispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
  <async-supported>true</async-supported>
</servlet>
<servlet-mapping>
  <servlet-name>WebSocketDispatcher</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

This or you need to include context-root and dispatcher mapping in your end-point URL:
http://<server>:<port>/<context-root>/<dispatcher-mapping>/ws

I hope it can help you.
Regards.
Heleno

A: firstly, you have set destination prefix with app, so you must add 'app' into your request url. e.g. if i wanted to request for '/ws', i should create SockJS with path '/server/app/ws', also you can code with
var socket = new SockJS("<c:url value='/server/app/ws'/>") and you know the 'server' is your project name over springmvc.
secondly, you must add the path '/app/*' to org.springframework.web.servlet.DispatcherServlet so as to avoid the path with prefix '/app' intercepted by interceptor defined in web.xml.

A: I arrived on this page and - thanks to Boris Accepted Answer  was motivated to reconsider the java approach as opposed to the xml approach which was causing the - /info=34424  with 404 error...whoops lost connection - I have Spring 4.2 in my project and many SockJS Stomp implementations usually work well with Spring Boot implementations. This implementation from Baeldung worked(for me without changing from Spring 4.2 to 5 or Boot). After Using the dependencies mentioned in his blog, it still gave me ClassNotFoundError. I added the below dependency to fix it.
<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.2.3.RELEASE</version>
    </dependency>

Baeldung's implementation curiously does not make any such calls
flow/websocket/add/info?t=1540813753999

What it does (on send and receive) is below. I am only pasting it in case people well-versed with these libraries can further add insights on this forum.
 >>> SEND
destination:/app/chat
content-length:38

{"from":"nicholas","text":"try again"}

<<< MESSAGE
destination:/topic/messages
content-type:application/json;charset=UTF-8
subscription:sub-0
message-id:m3p096zk-11
content-length:53

{"from":"nicholas","text":"try again","time":"13:46"}


text:
Q: How to add a toolbox to the MATLAB path Downloaded a library of functions from the internet. Drag and dropped it into the matlab directory (which is my default directory). I try to call these functions and nothing happens. They are several subfolders deep (matlab/fieldtrip/etc/etc). How do I access these functions from my workspace?

A: You should read the documentation that came with the toolbox since it may have toolbox-specific installation instructions. In your case it looks like you just need to add the fieldtrip directory to your path.
addpath('matlab/fieldtrip')

Then you'll have to run the ft_defaults install script that they provide which will theoretically handle all of those nested directories for you.
ft_defaults


text:
Q: Show changed lines only I have a text file and I need the difference of that text file and show the only two lines before and two lines after the changes are made. iS it possible If diff can't do it, what tool can?

A: Depending on the options (e.g. -u for unified of -c for context), you can eliminate lines that do not differ with the option:
--suppress-common-lines

Also look at the -C NUM --context[=NUM] and -U NUM --unified=[NUM] options to control the number of context lines.


text:
Q: RedirectToaction and method calls This is the default index function of my home controller
public ActionResult Index()
{
    if (User.Identity.IsAuthenticated)
    {
        return NewPosts();
    }
    else
    {
        ViewBag.Message = "Welcome!";
        return View();
    }
}

and this is the newposts function in the same home controller file
public ActionResult NewPosts()
{
    return View();
}

I have log onto my account and I close my browser. Then I reopen it visiting the same index page, I see my identity (Welcome myusername) but the newposts function is not called and thus it doesnot display the newposts view as expected.
Why is that ? How can I fix this ?
Thank you.

A: I think a better way of getting this to work would be setting up a default page as 'NewPosts' for the site via the web.config. Then in your web.config, you can set the failed login page as 'Index'. This will cause users once they are log in to be sent to the 'NewPosts' page. If they close the browser (and their authentication cookie has not expired) then they will be sent to the 'NewPosts' page as well. If they are not logged in, then they will be kicked to the 'Index' page. Your if statement in your Index action method would no longer be required, as the web config forms authentication takes care of this for you in a more robust way. Here is an example of what the web config could look like:
<authentication mode="Forms">
      <forms loginUrl="~/Home/Index" timeout="2880" defaultUrl="~/Home/NewPosts" >
      </forms>
</authentication>

See here for more web.config info concerning forms authentication.

A: The problem is not about the controller, it's about caching of your browser.
If you hit Ctrl+F5 on the first page, it should recognize you as unauthorized.
I know this is not a real solution to force website visitors to hit Ctrl+F5 to refresh their browsers. There are many article in internet to tackle this kind of caching behavior, serach for them.
Two important points about your code:
1- Change return NewPosts(); to:
 RedirectToAction("NewPost");

2- Decoreacte NewPosts method with [Authorize] attribute:
[Authorize]
public ActionResult NewPosts()
{
    return View();
}


text:
Q: Nodejs + rails + Angular I am using Rails as my API server and nodejs for serverside rendering with angular js. when I make some post request to API or PUT , Delete request to API, do I need to call it from Nodejs or from frontend?. Which is the correct approach?

A: Both approaches are correct; its just a matter of your architecture design.
I would typically not call my APIs through NodeJS due to added complexity, unless it is really necessary.


text:
Q: Adjacency lists in Java I have an adjacency table. See above:
e1.p1.x     e1.p1.y     e1.p2.x     e1.p2.y
x1 46       y1 280      x2 346      y2 339
x1 331      y1 229      x2 46       y2 280
x1 1        y1 74       x2 207      y2 325
x1 388      y1 29       x2 1        y2 74
x1 237      y1 72       x2 46       y2 280
x1 346      y1 339      x2 331      y2 229
x1 46       y1 280      x2 331      y2 229
x1 207      y1 325      x2 101      y2 152
x1 132      y1 55       x2 46       y2 280
x1 101      y1 152      x2 1        y2 74
x1 331      y1 229      x2 346      y2 339
x1 346      y1 339      x2 101      y2 152
x1 101      y1 152      x2 132      y2 55
x1 346      y1 339      x2 1        y2 74
x1 237      y1 72       x2 132      y2 55
x1 331      y1 229      x2 207      y2 325

There are 2 points in each row, which are neighbours. I would like to make lists like this, with all the neighbors of each point. But I get also fake adjacencies, I get more adjacencies in list above, than represented in the table.
    Output:
    [207, 325, 0, 1, 74, 0, 101, 152, 0, 331, 229, 0]
    [331, 229, 0, 46, 280, 0, 346, 339, 0, 207, 325, 0]
    [46, 280, 0, 346, 339, 0, 331, 229, 0, 237, 72, 0, 132, 55, 0]
    [346, 339, 0, 46, 280, 0, 331, 229, 0, 101, 152, 0, 1, 74, 0]
    [101, 152, 0, 207, 325, 0, 1, 74, 0, 346, 339, 0, 132, 55, 0]
    [132, 55, 0, 46, 280, 0, 101, 152, 0, 237, 72, 0]
    [237, 72, 0, 46, 280, 0, 132, 55, 0]
    [1, 74, 0, 207, 325, 0, 388, 29, 0, 101, 152, 0, 346, 339, 0]
    [388, 29, 0, 1, 74, 0]

This is Java code:
for (j = 0; j < size; j++) {
    ArrayList < Integer > aList = adjLists.get(j);
    for (Edge e: edges) {
        if ((points[j][0] == e.p1.x && points[j][1] == e.p1.y)) {
            aList.add(e.p1.x);
            aList.add(e.p1.y);
            aList.add(0);

            for (Edge e1: edges) {
                if (e1.p1.x == e.p1.x && e1.p1.y == e.p1.y && !aList.contains(e1.p2.x) && !aList.contains(e1.p2.y)) {
                    aList.add(e1.p2.x);
                    aList.add(e1.p2.y);
                    aList.add(0);

                }
            }
            break;
        }

        if ((points[j][0] == e.p2.x && points[j][1] == e.p2.y)) {

            aList.add(e.p2.x);
            aList.add(e.p2.y);
            aList.add(0);
            for (Edge e1: edges) {
                if (e1.p2.x == e.p1.x && e1.p2.y == e.p1.y && !aList.contains(e1.p1.x) && !aList.contains(e1.p1.y)) {
                    aList.add(e1.p1.x);
                    aList.add(e1.p1.y);
                    aList.add(0);
                }
            }
            break;
        }
    }
}

Size is the number of vertices, aList should store adjacencies.

A: I think the correct way to do this is to define a class Point instead of using raw integers:
 class Point {
   private final int x;
   private final int y;
   Point(int x, int y) {this.x = x; this.y = y;}
   int getX() {return x;}
   int getY() {return y;}
 }

Then an adjacency list is:
Map<Point, Set<Point>> adjacencies;

Then to use it you just write;
for (/* rows */) {
  Point pt1 = new Point(x1, y1); // Extract from the table.
  Point pt2 = new Point(x2, y2); // Extract from the table.
  Set<Point> adjs = adjacencies.find(pt1);
  if (adjs == null) {
    adjs = new HashSet<Point>();
    adjacencies.put(pt1, adjs);
  }
  adjs.put(pt2);
  // Same for pt2
}

This way you can get the adjacencies of a point as follows:
Set<Point> adjs = asjacencies.get(point);

Much easier than searching an array of arrays and parsing every two into a point.
If some other module needs the data in the form of an array of arrays you can do as follows:
List<List<Integer>> toLists(Map<Set<Point>> adjacencies) {
  List<List<Integer>> result = new ArrayList<List<Integer>>();
  for (Point pt : adjacencies.getKeys()) {
    List<Integer> adjs = new ArrayList<Integer>();
    adjs.add(pt.getX());
    adjs.add(pt.getY());
    adjs.add(0);
    for (Point adjPt : adjacencies.get(pt)) {
      adjs.add(adjPt.getX());
      adjs.add(adjPt.getY());
      adjs.add(0);
    }
    result.add(adjs);
  }
  return result;
}