text:
Q: Cleanly recreate 10.3 enterprise geodatabase in Oracle 12c Recently I created an enterprise geodatabase on a virgin Oracle 12c instance, using ArcCatalog. I eventually dropped the SDE schema and attempted to recreate the enterprise geodatabase. Now I get the following error:
Failed to insert a value to the geodatabase system table.GDB_ItemTypes
According to the log, the underlying Oracle exception is:
ORA-00001: unique constraint (SDE.R6_SDE_ROWID_UK) violated
I have a feeling that SDE is leaving behind bits and pieces elsewhere in my Oracle instance. Is there a reliable way to cleanly remove all traces? Or is something else going on?
Edit: I am also now seeing a lot of messages like this in sdedc_Oracle.log:
[Mon Oct 24 13:10:49 2016] [50049085] [XPLWS02] db_execute_sql OCI Execute Error (4043).
[Mon Oct 24 13:10:49 2016] [50049085] [XPLWS02] db_execute_sql OCI Execute Error (942).
[Mon Oct 24 13:10:49 2016] [50049085] [XPLWS02] db_execute_sql OCI Execute Error (2289).

Each of the OCI error codes maps to one of the Oracle "not found" error codes (e.g., https://www.techonthenet.com/oracle/errors/ora00942.php).

A: And the resolution (per Vince) is... drop all tables using the SDE.ST_GEOMETRY type before dropping the SDE user. If you forget to do that the database will become corrupt and you must uninstall and reinstall Oracle. (Having just learned a thing or two about pluggable databases, I would wager that in the world of Oracle 12c one could simply create a new PBD.)


text:
Q: Spoof an IP address to test GEOIP lookups with Sitecore 8 I am new to Sitecore. I'm trying to implement following process class to overwrite GeoIP values for testing purpose.
I can't find in which namespace the class Tracker is situated. Please note that I am using Sitecore 8 hosted on localhost. Sitecore Blog: @sitecorejohn blog
Can some one please help me to resolve this namespace issue.
Thanks.
namespace Sitecore.Sharedsource.Analytics.Pipelines.StartTracking
{
    using System.Net;

    using Sitecore.Analytics;
    using Sitecore.Analytics.Pipelines.StartTracking;

    public class OverrideIPAddress
    {
        public void Process(StartTrackingArgs args)
        {
            if (Tracker.CurrentVisit == null
              || Tracker.CurrentVisit.GeoIp == null
              || Tracker.CurrentVisit.Ip == null)
            {
                return;
            }

            string ip = new IPAddress(
              Tracker.CurrentVisit.GeoIp.Ip).ToString();

            if (ip != "0.0.0.0" && ip != "127.0.0.1")
            {
                return;
            }

            string html = Sitecore.Web.WebUtil.ExecuteWebPage(
              "http://www.whatismyip.com/automation/n09230945.asp");
            IPAddress address = IPAddress.Parse(html);
            Tracker.CurrentVisit.GeoIp =
              Tracker.Visitor.DataContext.GetGeoIp(address.GetAddressBytes());
        }
    }
}

A: Tracker class is in the Sitecore.Analytics namespace.
Make sure that your project references Sitecore.Analytics.dll.
In Sitecore 8 you should use Tracker.Current and  Tracker.Current.Interaction instead of Tracker.CurrentVisit:
Tracker.Current.Interaction.Ip = address.GetAddressBytes();
Tracker.Current.Interaction.UpdateGeoIpData(optionalTimeout);

You can consider adding another processor to CreateVisit pipeline after XForwardedFor processor and call:
args.Interaction.Ip = address.GetAddressBytes();

You won't have to call UpdateGeoIpData - it will be called automatically in the UpdateGeoIpData processor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typescript: Cast an object to other type using. How? And instanceof or typeof? Cast an object to other type using Typescript. How? And instanceof or typeof?

A: Something like this:
let object = myObject as string; // this way
let object = <string> myObject; // or this way

In addition, instanceof returns a boolean, typeof returns the instance type.

A: "Type Assertion" as this is called in Typescript can be done as follows:
interface Student {
    name: string;
    code: number;
}
let student = <Student> { }; //or { } as student
student.name = "Rohit"; // Correct
student.code = 123; // Correct

In the above example, we have created an interface Student with the properties name and code. Then, we used type assertion on the student, which is the correct way to use type assertion.
Use typeof for simple built in types:
true instanceof Boolean; // false
typeof true == 'boolean'; // true

Use instanceof for complex built in types:
[] instanceof Array; // true
typeof []; //object


text:
Q: What's that ship in the opening credits of 'Star Trek: Enterprise'? In the Star Trek: Enterprise opening credits it seems to step through starship history up to the Enterprise NX-01.
After Cochran's Phoenix, there is a ship that we see almost only from behind, and then the Enterprise. Do we know what that ship is?

A: This is the S.S. Emmette, designed by Doug Drexler.

This time for real! Here it is, one of the most mysterious of all the
Enterprise ships, the S.S Emmette. Teasingly seen in the notorious
title sequence over what appears to be a moon base.
Look at the massive rocket style motors on the back of this bucket!
These giants suggest that perhaps this ship was meant primarily for
solar exploration and testing. The reasoning being  that you would not
devote so much of the ship's resources to engines like these unless
they could made a difference.  Set up like this, if you lost warp
drive within the solar system, you were still capable of making it
home.
Fascinating similarities to the Romulan Bird of Prey, suggesting some
truth to the theory that the Romulan's had stolen intel on this ship,
and built their own version.
When the gang at Foundation Imaging were working on the title
sequence, clearly they only built as much of the Emmette as they
needed. Note the absence of detail on the front of the model.
eureka! s.s. emmette!


text:
Q: Angular assign css variable to before after class Im trying to pass variable with [ngStyle] and read it on ::before class but unfortunately cannnot do it,
could someone point me on a right direction?
CSS:
  .handle-slider__control {
    height: 7px;
    z-index:1;
    background: $colour-alto;
    position: relative;
    margin:50px auto;
    margin-bottom: 16px;

    &.handle-slider__control--markers {
      margin-bottom: 0;
    }
  }

  .handle-slider__control::before {
    position: absolute;
    z-index:-1;
    content:"";
    left: var(--left);
    right: var(--right);
    background: $colour-red;
    height:100%;
  }

HTML:

And JS method:
  getRangeColours()
  {
    return {"--left": "10%","--right": "10%"};
  }

There is no information about wrongly passed data or anything. Im trying to change css parameters left, right based on data that are in component. If there is any other way to do it I would also consider it. THANKS!

A: About css variales thare are differents insteresting links about this, Take a look here or here, e.g.
I don't check it but
document.documentElement.style.setProperty('--left', "10%");
document.documentElement.style.setProperty('--rigth', "20%");

must be work

A: I just used different class instead of pseudocode with ngStyle on it like that:
.slider-colour-control {
    position: absolute;
    z-index:-1;
    content:"";
    background: $colour-red;
    height:100%;
  }

A: Tested in Angular 9.1.11
test.component.ts
import { Component, OnInit, HostBinding } from '@angular/core';
@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  @HostBinding('style.--left.%')  left: number = 20; // Change it to any Number at any point
  @HostBinding('style.--right.%') right: number;

  constructor() {}

  ngOnInit(): void {
     this.right = 10; // Change it to any Number at any point
  }

}

test.component.html

CSS Variables in Angular

test.component.scss
.handle-slider__control {
    height: 7px;
    z-index:1;
    background: blue;
    position: relative;
    margin:50px auto;
    margin-bottom: 16px;

    &.handle-slider__control--markers {
      margin-bottom: 0;
    }
  }

  .handle-slider__control::before {
    position: absolute;
    z-index:-1;
    content:"";
    left: var(--left);
    right: var(--right);
    background: red;
    height:100%;
  }

For Lower versions, try this (couldn't test though):
  import { DomSanitizer } from '@angular/platform-browser';

  public value: string;
  @HostBinding("attr.style")
  public get leftStyle(): any {
    return this.sanitizer.bypassSecurityTrustStyle(`--left: value`);
  }

  constructor(private sanitizer: DomSanitizer) {
     this.value = '10%';
  }


text:
Q: Add markers on line plot from another vector I have made a line plot from vector1 with matplotlib
plt.plot(vector1)

I have two other vectors vector2_x and vector2_y of same length.
Can I plot dots in same plot with x values from vector2_x and dot sizes from vector2_y?

A: iHave a look at  scatterplots in matplotlib. That is a very versatile function, and you can define the marker size separately as a vector. From the example:
plt.scatter(x, y, s = area, c=colors, alpha=0.5)

Generally, best thing to do when wanting a special plot function is to peruse the gallery and select the plot which most resembles what you want. Chances are you will find what you want there.


text:
Q: What is the value of $ \int\frac{ r^2e^{-r'}}{|\vec{r}-\vec{r'}|} d^3r'$? How do I find  $ \int\frac{ r^2e^{-r'}}{|\vec{r}-\vec{r'}|} d^3r'$
For context it is to calculate the potential $\int\frac{n(\vec{r})}{|\vec{r}-\vec{r'}|}d^3r'$ When the density $n$ is an exponential function


text:
Q: Applying annotationProcessor in Gradle version 4.6 I am having a hard time building my project. I am using dagger 2, and therefore I need to use annotation processor. I use gradle wrapper version 4.6 with the following build:
plugins {
  id "java"
  id "idea"
}

group 'xyz.blackmonster'
version '0.0.1-SNAPSHOT'

sourceCompatibility = 1.8

ext {
  dropwizardVersion = "1.3.0"
  mysqlConnectorVersion = "8.0.9-rc"
  daggerVersion = "2.15"
  mockitoVersion = "2.16.0"
}

repositories {
  mavenCentral()
}

dependencies {
  compile group: 'io.dropwizard', name: 'dropwizard-core', version: dropwizardVersion
  compile group: 'io.dropwizard', name: 'dropwizard-jdbi3', version: dropwizardVersion
  compile group: 'io.dropwizard', name: 'dropwizard-auth', version: dropwizardVersion
  compile group: 'io.dropwizard', name: 'dropwizard-metrics-graphite', version: dropwizardVersion
  compile group: 'mysql', name: 'mysql-connector-java', version: mysqlConnectorVersion
  annotationProcessor group: 'com.google.dagger', name: 'dagger-compiler', version: daggerVersion
  implementation group: 'com.google.dagger', name: 'dagger', version: daggerVersion
  testCompile group: 'io.dropwizard', name: 'dropwizard-testing', version: dropwizardVersion
  testCompile group: 'org.mockito', name: 'mockito-core', version: mockitoVersion
}

Looking at the documentation, they have added annotation processor support out of the box in 4.6 (no need to use any plugins). I am trying to use the same approach. Now, since I do not set the annotationProcessorPath, it should automatically use the build path, since the value by default is null - annotationProcessorPath documentation. But it seems this is not the case. My Dagger classes are being generated properly in build/classes/java/main, but they are not being picked up. For building the classes, I have Java 8 installed locally (console output):
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

I am running gradle with the following command: ./gradlew clean build
To prove I am using the right version, I ran the command: ./gradlew -version and got this console output:
------------------------------------------------------------
Gradle 4.6
------------------------------------------------------------

Build time:   2018-02-28 13:36:36 UTC
Revision:     8fa6ce7945b640e6168488e4417f9bb96e4ab46c

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_162 (Oracle Corporation 25.162-b12)
OS:           Mac OS X 10.13.3 x86_64

So, when running the build ./gradlew build, I get the following output:
> Task :compileJava FAILED
.../src/main/java/xyz/blackmonster/resume/app/ResumeApplication.java:17: error: cannot find symbol
import xyz.blackmonster.resume.config.DaggerBeanComponent;
                                     ^
  symbol:   class DaggerBeanComponent
  location: package xyz.blackmonster.resume.config
1 error

Here is the Application file:
package xyz.blackmonster.resume.app;

import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.jdbi.v3.core.Jdbi;

import com.google.common.cache.CacheBuilderSpec;
import io.dropwizard.Application;
import io.dropwizard.auth.AuthDynamicFeature;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.auth.CachingAuthenticator;
import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
import io.dropwizard.auth.basic.BasicCredentials;
import io.dropwizard.jdbi3.JdbiFactory;
import io.dropwizard.setup.Environment;
import xyz.blackmonster.resume.config.bean.BeanComponent;
import xyz.blackmonster.resume.config.bean.BeanModule;
import xyz.blackmonster.resume.config.DaggerBeanComponent;
import xyz.blackmonster.resume.config.ResumeConfiguration;
import xyz.blackmonster.resume.security.auth.ResumeAuthorizer;
import xyz.blackmonster.resume.security.model.User;

public class ResumeApplication extends Application<ResumeConfiguration> {

    private static final String REALM = "resume";
    private static final String MYSQL = "mysql";

    private BeanComponent beanComponent;

    public static void main(String[] args) throws Exception {
        new ResumeApplication().run(args);
    }

    @Override
    public void run(ResumeConfiguration configuration, Environment environment) throws Exception {
        final JdbiFactory factory = new JdbiFactory();
        final Jdbi jdbi = factory.build(environment, configuration.getDataSourceFactory(), MYSQL);

        beanComponent = DaggerBeanComponent.builder().beanModule(new BeanModule(jdbi)).build();

        environment.jersey().register(beanComponent.getAchievementControler());

        CachingAuthenticator<BasicCredentials, User> cachingAuthenticator =
            new CachingAuthenticator<>(
                environment.metrics(),
                beanComponent.getResumeAuthenticator(),
                CacheBuilderSpec.parse(configuration.getAuthenticationCachePolicy()));

        environment.jersey().register(new AuthDynamicFeature(
            new BasicCredentialAuthFilter.Builder<User>()
                .setAuthenticator(cachingAuthenticator)
                .setAuthorizer(new ResumeAuthorizer())
                .setRealm(REALM)
                .buildAuthFilter()));
        environment.jersey().register(RolesAllowedDynamicFeature.class);
        environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
    }
}

Any ideas what am I doing wrong? I can see the dagger files being generated in xyz.blackmonster.resume.config. Gradle would need to use then those compiled files, but does not "find" those files for some reason. I would appreciate any valuable input.

A: Someone pointed out my problem. In regards to gradle, everything is perfect. The problem was java related. I moved my Dagger-related classes into another package. And because of that I had the wrong (old) import added to the Application class. So naturally, when I was building the project, I had the wrong import and the class could not be found.
The new Application file looks now like this:
package xyz.blackmonster.resume.app;

import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.jdbi.v3.core.Jdbi;

import com.google.common.cache.CacheBuilderSpec;
import io.dropwizard.Application;
import io.dropwizard.auth.AuthDynamicFeature;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.auth.CachingAuthenticator;
import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
import io.dropwizard.auth.basic.BasicCredentials;
import io.dropwizard.jdbi3.JdbiFactory;
import io.dropwizard.setup.Environment;
import xyz.blackmonster.resume.config.bean.BeanComponent;
import xyz.blackmonster.resume.config.bean.BeanModule;
// wrong import was used here
// before I had import xyz.blackmonster.resume.config.DaggerBeanComponent
import xyz.blackmonster.resume.config.bean.DaggerBeanComponent;
import xyz.blackmonster.resume.config.ResumeConfiguration;
import xyz.blackmonster.resume.security.auth.ResumeAuthorizer;
import xyz.blackmonster.resume.security.model.User;

public class ResumeApplication extends Application<ResumeConfiguration> {

    private static final String REALM = "resume";
    private static final String MYSQL = "mysql";

    private BeanComponent beanComponent;

    public static void main(String[] args) throws Exception {
        new ResumeApplication().run(args);
    }

    @Override
    public void run(ResumeConfiguration configuration, Environment environment) throws Exception {
        final JdbiFactory factory = new JdbiFactory();
        final Jdbi jdbi = factory.build(environment, configuration.getDataSourceFactory(), MYSQL);

        beanComponent = DaggerBeanComponent.builder().beanModule(new BeanModule(jdbi)).build();

        environment.jersey().register(beanComponent.getAchievementControler());

        CachingAuthenticator<BasicCredentials, User> cachingAuthenticator =
            new CachingAuthenticator<>(
                environment.metrics(),
                beanComponent.getResumeAuthenticator(),
                CacheBuilderSpec.parse(configuration.getAuthenticationCachePolicy()));

        environment.jersey().register(new AuthDynamicFeature(
            new BasicCredentialAuthFilter.Builder<User>()
                .setAuthenticator(cachingAuthenticator)
                .setAuthorizer(new ResumeAuthorizer())
                .setRealm(REALM)
                .buildAuthFilter()));
        environment.jersey().register(RolesAllowedDynamicFeature.class);
        environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
    }
}


text:
Q: Passing a array value by ajax in Wordpress I have done an ajax call by jQuery.ajax and tried like this
        jQuery.ajax({
            url: wpgiftstoreAjax.ajaxurl,
            type: 'POST',
            dataType: 'JSON',
            data: {
                action: 'addgiftTocart',
                giftData: gdata,
            },
            success: function( data ) {
                console.log(data);
            }
        })

I got the "gdata" by this
var gdata = JSON.stringify(GiftData);

But here I can't get the string data like this. I got a blank array. Just before the line, I have tried with this code and I got the array with data.
console.log(GiftData);

So I can't understand where is the problem with this. Please help me with this problem and thanks in advance.
My total code I have tried
    GiftData = [];
    GiftData['boxProduct'] = [];
    GiftData['boxName'] = jQuery('#giftbox-data .box-data').text();
    jQuery('#giftbox-data .prod-data .product').each( function(i) {
        GiftData["boxProduct"][i] = [];
        GiftData['boxProduct'][i]['id'] = jQuery(this).find('.prod-name').attr('prodid');
        GiftData['boxProduct'][i]['num'] = jQuery(this).find('.prod-num').text();
    })
    GiftData['boxSenderInfo'] = jQuery('#giftbox-data .sender-info .gift-sender').text();

A: The only problem i have done in the above code is to have the square bracket"[" instead of "{".
This should be like this
    GiftData = {};
    GiftProdData = {};
    GiftData['boxProductData'] = {};
    GiftData['boxName'] = jQuery('#giftbox-data .box-data').text();
    jQuery('#giftbox-data .prod-data .product').each( function(i) {
        GiftData["boxProductData"][i] = {};
        GiftData['boxProductData'][i]['id'] = jQuery(this).find('.prod-name').attr('prodid');
        GiftData['boxProductData'][i]['num'] = jQuery(this).find('.prod-num').text();
    })

Thank you for the cooperation.


text:
Q: Null pointer exception when attempting to parse string into java.util.date Image of step into for saveEmployee method:
I am learning Spring+JDBC, and trying to get SQL date-datatype into Java as java.util.Date or java.sql.Date object, and running into null pointer exception.
Code in the main method for inserting data into Employeetabke that causes exception:
//the following parses date string into java.util.date
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
    EmployeeDAO empDao = (EmployeeDAO)ctx.getBean("employeeDao");
    Employee employee = new Employee();
    employee.setName("Robert");
    //the following parses date string into java.util.date
    employee.setJoining_Date((new SimpleDateFormat("MM/dd/yyyy")).parse("12/30/2016"));
    employee.setSalary(200);
    employee.setsSN("837463");

Definition of the setters in Employee.java model class:
import java.sql.Date

public void setJoining_Date(java.util.Date joining_Date) {
        this.joining_Date = new java.sql.Date(joining_Date.getTime());
}
public void setJoining_Date(Date joining_Date){
        this.joining_Date = joining_Date;
}

Method:
public void saveEmployee(Employee e){
    this.jdbcTemplate.update(this.employee_insert, new Object[]{e.getName(), e.getJoining_Date(), e.getSalary(), e.getsSN()});
    }

Exception:
Exception in thread "main" java.lang.NullPointerException
    at com.springdao.EmployeeDaoImpl.saveEmployee(EmployeeDaoImpl.java:49)
    at com.springclient.EmployeeExec.main(EmployeeExec.java:28)

Please also advise about best practices regarding implementing such code.
Spring.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation ="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-
            2.0.xsd">

    <bean id ="dataSource" class
      ="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name ="driverClassName" value ="com.mysql.jdbc.Driver"/>
      <property name ="url" value ="jdbc:mysql://localhost:3306/branch_db"/>
      <property name ="username" value ="root"/>
      <property name ="password" value ="root"/>
    </bean>

    <bean id ="jdbcTemplate" class
      ="org.springframework.jdbc.core.JdbcTemplate">
      <property name ="dataSource" ref ="dataSource"/>
    </bean>

    <bean id ="employeeDao" class  ="com.springdao.EmployeeDaoImpl">
      <property name ="jdbcTemplate" ref ="jdbcTemplate"/>
    </bean>

</beans>


text:
Q: Having trouble with package.d I am having trouble with D's package.d feature. I have my package.d file:
module dew;

public
import dew.util;

I then have util.d:
module dew.util;

struct Size
{
    int width;
    int height;
}

When I try to use it in another project, it gives me this error:
I know that this should work, because projects on GitHub use it, specifically bindbc-sdl.

A: Your code is correct. By the error message I'm assuming your project layout with DUB probably looks something like this:

*

*dew/

*

*dub.sdl/dub.json

*source/

*

*package.d

*util.d

However this would be incorrect. By default DUB only uses import folders instead of specifying all input source files, so the compiler attempts to discover the files from the import paths in the filesystem. The compiler dumped the import paths it searches in in your error screenshot.
The rough compiler equivalent to what it's doing right now is (see dub -v)
dmd source/app.d -Isource -I../dew/source

You need to imagine that the path whatever is written in there is invisible to the compiler, so the dew/source/ path is just some opaque string the compiler doesn't interpret. Now all that the compiler sees is a package.d and util.d in its search paths. However for imports from folders to function, they need to correspond to the filesystem layout, i.e. you need to have a folder named dew where your files are stored in.
So a module named dew.util would correspond to dew/util.d
And your package dew would correspond to dew/package.d
So for your dub project that means essentially that you need to move all your source files into

*

*dew/

*

*dub.sdl/dub.json

*source/

*

*dew/

*

*package.d

*util.d

Alternatively it would be possible to manually specify all files one-by-one where the compiler can look them up because of the module declarations at the top of the file, however you lose the convenience of module names being mapped to filesystem paths, which might be something other community-made D source tools and IDEs are expecting. On the command line that would be equivalent to
dmd source/app.d ../dew/source/dew/package.d ../dew/source/dew/util.d


text:
Q: Rails 5: Add belongs_to association I have two tables, "users" and "friendships", I'm trying to make a relationship so that a user can have a friendship with other users, so generate this model friendships with rails g model Friendship user:references friend:references status
in the model friendship.rb:
class Friendship < ApplicationRecord
  belongs_to :user
  belongs_to :friend,class_name: "User"
end

but at the time of creating the record it shows me the following error:
Friendship.create(user_id: 1, friend_id:2, id: 1)

   (0.1ms)  begin transaction
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  SQL (0.4ms)  INSERT INTO "friendships" ("id", "user_id", "friend_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["id", 1], ["user_id", 1], ["friend_id", 2], ["created_at", "2018-02-26 19:39:57.865042"], ["updated_at", "2018-02-26 19:39:57.865042"]]
   (0.1ms)  rollback transaction
Traceback (most recent call last):
        1: from (irb):2
ActiveRecord::StatementInvalid (SQLite3::SQLException: no such table: main.friends: INSERT INTO "friendships" ("id", "user_id", "friend_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?))
irb(main):003:0>

What could it be? I have Rails 5.1.5

A: Your Friendship model is set up correctly, but perhaps your migration is not. It should look like this:
class CreateFriendships < ActiveRecord::Migration[5.1]
  def change
    create_table :friendships do |t|
      t.references :user, index: true, foreign_key: true
      t.references :friend, index: true, foreign_key: { to_table: :users }
    end
  end
end

I've set this up in a new Rails 5.1.5 project and it is working for me:
>> User.create(name: 'First User')
>> User.create(name: 'Second User')
>> Friendship.create(user_id: 1, friend_id:2, id: 1)
   (0.1ms)  begin transaction
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  SQL (0.8ms)  INSERT INTO "friendships" ("id", "user_id", "friend_id") VALUES (?, ?, ?)  [["id", 1], ["user_id", 1], ["friend_id", 2]]
   (0.8ms)  commit transaction
#<Friendship id: 1, user_id: 1, friend_id: 2>

Incidentally, you should avoid assigning id numbers to non-persisted objects. Better to let the database handle that job. I would create a Friendship simply as:
>> Friendship.create(user_id: 1, friend_id: 2)


text:
Q: Can I change settings as a Device Owner? (Android 4 Work) There are several settings (Bluetooth, uninstall block, etc) that can be changed if the application is registered as device owner. However, like in normal applications, it's not possbile to change the global settings (Airplane Mode, Developer Mode, etc).
Settings that can be changed:

*

*Secure settings

*User restrictions
Is there a way to change global settings as a device owner? Or can I set the settings during the set up of the device?


text:
Q: How to set language when generating pdf in Laravel Is there a way to force the language when generating a pdf in laravel?
I'm using the package barryvdh/laravel-dompdf and creating the pdf with a blade view like so:
 $pdf = PDF::loadView('businesssummary::report.pdf', [
            "vm" => $result,
            'locale' => Cache::get('locale', 'default')
        ]);

When streaming the pdf directly into a page, like so
'
<embed src="{{ Loc::route('directory.report') }}" width="100%" height="1120" type="application/pdf" scrolling="yes"></embed>
'

it works great and uses the current locale.
But when creating the pdf to be used as an attachement in an email sent to the user, the language used is the app default one.
Can I set the locale for this, just like I do so for the email sent?
I can't seem to find documentation on how (or if possible) to do so.
Thanks

A: So I finally figured out a simple way to do it.
Just before loading the view with PDF::loadView(...), just set the locale using the value stored in the Cache like so:
App::setLocale(Cache::get('locale', 'default'));


text:
Q: How does Uploadify work? I'm trying to figure out how Uploadify works.
I'm trying to see the POST in FireBug on the demos page, but can't see anything.
I thought even requests that originate from Flash still appear in Firebug.
LiveHTTPHeaders didn't tell me anything either.
When I try it on my site, the file can be selected OK and the progress bar moves, but I can't see any activity.
So, how do I check to make sure there is activity coming from the plugin?
Thanks
Update
OK, if I can't see the requests, what is the best way to make sure it is working? Make logs from the uploadify.php file?

A: I believe that it uses an invisible flash file and interfaces with the flash through a Javascript interface.  And since flash doesn't go through Firefox, firebug can't see it.
For logging that the requests are working (assuming you are looking for a way to log that it is happening when programming, and not after you have gotten it working), I would use FirePHP.  FirePHP allows you to log information to Firebug.  If you are just trying to keep a log of uploaded files, I would just write out to a file whenever you receive an upload.

A: At the beginning of a file that is processing the actual uploads, add few lines, something like this:
$requestDataToLog = print_r($_POST, true)."\n\n";
$fp = fopen('log.txt', 'a');
fwrite($fp, requestDataToLog);
fclose($fp);

And check that you have correct values in POST by looking at the log file.
It would also be a good idea to secure the upload script a little so hackers cannot upload stuff to your website by just calling the PHP script with POST request.
Add a hash to the form (in a hidden field) and save it to a session once the form has been submitted (via AJAX I assume). On the top of the upload script check that the hash in session is correct and continue upload only then.
You might also want to make sure that the request is comming only from your website by checking $_SERVER['HTTP_REFERER'].


text:
Q: Can Java optimize "mutating" BigInteger operations in loops? I need to deal with a lot of big numbers much larger than a long (>10^200), so I'm using BigIntegers. The most common operation I perform is adding them to an accumulator, ex:
BigInteger A = new BigInteger("0");
for(BigInteger n : nums) {
    A = A.add(n);
}

Of course making copies for destructive actions is quite a waste (well, as long as there's a large enough buffer available), so I was wondering if Java can optimize this somehow (I heard there was a MutableBigInteger class not exposed by math.java) or whether I should just write my own BigInteger class.

A: Yes, there is a java.math.MutableBigInteger class that is used by BigInteger for compute-intensive operations.  Unfortunately, it is declared as package private, so you cannot use it.   There is also a "MutableBigInteger" class in the Apache Commons library, but it is just a mutable wrapper for BigInteger and that is no help for you.

I was wondering if Java can optimize this somehow ...

No ... not withstanding the above.

or whether I should just write my own BigInteger class.

That's one approach.
Another is to to download the OpenJDK sources, find the source code for java.math.MutableBigInteger, change its package name and access, and incorporate it into your code-base.  The only snag is that OpenJDK is licensed under the GPL (GPL-2 I think), and that has implications if you ever distribute code using the modified class.
See also:

*

*What is the purpose of java.math.MutableBigInteger?

A: A quicker solution is to circumvent the java package visibility. You can do that by creating a package named java.math in your own project and creating a public class that exposes the package private MutableBigInteger like so:
package java.math;

public class PublicMutableBigInteger extends MutableBigInteger {

}

Then you can just import java.math.PublicMutableBigInteger; and use it as any other class. This solution is quick and doesn't impose upon you any particular licence.

A: There's not a lot the compiler can do, because it can't know what the add method does.  Here is the generated code for the loop's body.  As you can see, it simply calls add and stores the result.
   25:  iload   5
   27:  iload   4
   29:  if_icmpge       51
   32:  aload_3
   33:  iload   5
   35:  aaload
   36:  astore  6
   38:  aload_1
   39:  aload   6
   41:  invokevirtual   #5; //Method java/math/BigInteger.add:(Ljava/math/BigInteger;)Ljava/math/BigInteger;
   44:  astore_1
   45:  iinc    5, 1
   48:  goto    25

In theory, the Java virtual machine run time system could be more clever.  For instance, it could detect that one object continuously overwrites another just allocated, and just swap two allocation buffers for them.  However, as we can see by running the following program with garbage collection logging enabled, this is sadly not the case
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Random;

class Test {
    public static void main(String[] args) {
    ArrayList <BigInteger> nums = new ArrayList<BigInteger>();
    final int NBITS = 100;
    final int NVALS = 1000000;

    System.out.println("Filling ArrayList");
    Random r = new Random();
    for (int i = 0; i < NVALS; i++)
        nums.add(new BigInteger(NBITS, r));

    System.out.println("Adding ArrayList values");
    BigInteger A = new BigInteger("0");
    for(BigInteger n : nums) {
        A = A.add(n);
    }

    System.gc();
    }
}

See the garbage collection calls during the addition process.
C:\tmp>java -verbose:gc Test
Filling ArrayList
[GC 16256K->10471K(62336K), 0.0257655 secs]
[GC 26727K->21107K(78592K), 0.0304749 secs]
[GC 53619K->42090K(78592K), 0.0567912 secs]
[Full GC 42090K->42090K(122304K), 0.1019642 secs]
[GC 74602K->65857K(141760K), 0.0601406 secs]
[Full GC 65857K->65853K(182144K), 0.1485418 secs]
Adding ArrayList values
[GC 117821K->77213K(195200K), 0.0381312 secs]
[GC 112746K->77245K(228288K), 0.0111372 secs]
[Full GC 77245K->137K(228288K), 0.0327287 secs]

C:\tmp>java -version
java version "1.6.0_25"
Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.0-b11, mixed mode)

A: Java won't do any special optimisations for this case. BigInteger is generally treated as a normal class like any other (unlike String, for example, which sometimes gets some special optimisations when you are concatenating many strings).
But in most cases, BigInteger is fast enough that it won't matter anyway. If you really think it might be a problem, I'd suggest profiling you code and working out what is taking the time.
If adding BigIntegers is really your bottleneck, then it might make sense to use a custom mutable big-integer class to act as an accumulator. But I wouldn't do this before you've proved that this is genuinely the main bottleneck.


text:
Q: Laravel mailer slow (1-2s) performance I have the need to send mail campaigns with around 100k mails as fast as possible. The listener which processes emails is nothing special:
public function handle(object $event)
{
    $message = EmailMessage::query()->findOrFail($event->messageId);

    $recipients = $message->recipients;

    $this->sendEmail($message, $recipients);

    $this->updateStatus($message);
}

protected function sendEmail(EmailMessage $message, Collection $recipientCollection): void
{
    $queuedEmail = new QueuedEmail($message->subject, $message->body, $message->conversation_uuid);

    $to = 'test+' . $message->conversation_uuid . '@gmail.com';

    $start = microtime(true);

    Mail::to($to)->send($queuedEmail);

    $time_elapsed_secs = microtime(true) - $start;
    echo "FINAL: $time_elapsed_secs\n";
}

Analyzing elapsed times, I noticed that each mail takes about 1-2s to process which I consider being really slow. Digging deeper in Swift\Mailer class I've noticed that its send() method is the one responsible for such performance. Is this normal for this library?
I am doing using Laravel queues over STOMP protocol, but I've tried using Redis driver as well, nothing changed.
For email setup, I am using companies exchange mail server, but it behaves the same with postfix  and mailtrap also.
Is this a Laravel/SwiftMailer issue or something on my side?


text:
Q: How can I perform a VBA script on click? I'm using a checkbox Legacy Form Field in my Word document. And I want to perform a VBA script each time I change the status of the checkbox. I thought I would have to perform this VBA script on event (no. 1 in the picture). But if I chose either no. 1 or no. 2, it only performs the VBA script if I'm changing to the next field.

My questions:
Now, how can I perform a VBA script on each click? And what is the difference between no. 2 and no. 3 in the picture above?

A: Word has no on event triggers for checkboxes if i remember correctly.
A possible workaround would be some kind of validation button which checks the value of the checkbox and then executes the appropriate commands.


text:
Q: I have a site coded with Html, CSS (Bootstrap), Nodejs, Express.js and I want to host it on a website, how can I do it? Do I have to upload the Node Modules folder too? Or is there something I haven't learned about yet, I'm a fresher and this is my first time deploying a site.

A: you can deploy your site on any depolyment platform such as heroku, vercel, or netlify. You don't need to upload node_modules as they will install by themselves.

A: If you have Cpanel access, then you can do it by Cpanel, otherwise, you can use any FTP server like FileZilla, and by using your credentials, access your site and upload all the files in the Public_html folder.
Check out this video for better understanding


text:
Q: Quebra de linha do select options que contenha um valor muito extenso É possível quebrar a linha de um option muito extenso?
ex:

<select>
  <option>texto muito extensp
restante do texto</option>
</select>

A: Não, isto não é possível de se fazer. No entanto podes sempre optar por utilizar esta solução alternativa de adicionar um title ao option:

<select>
    <option value="1" title="This is my lengthy explanation of what this selection really means, so since you only see "This is my lengthy..." on the drop down list you really know that you're opting to elect me as King of Willywarts!  Always be sure to read the fine print!">This is my lengthy...</option>
</select>

A: Aqui está a resposta para o seu problema:

Seleção com texto longo abaixo:

    <select name="select_this" id="testselectset">
        <option value="">Selecione abaixo...</option>
        <option value="01">Opção 1</option>
        <option value="02">Opção 2</option>
        <option value="03">Opção 3 - Muitos softwares de publicação e editores de páginas na internet agora usam Lorem Ipsum como texto-modelo padrão, e uma rápida busca por 'lorem ipsum' mostra vários websites ainda em sua fase de construção. </option>
        <option value="04">Opção 4</option>
        <option value="05">Opção 5 - o contrário do que se acredita, Lorem Ipsum não é simplesmente um texto randômico. Com mais de 2000 anos, suas raízes podem ser encontradas em uma obra de literatura latina clássica datada de 45 AC. Richard McClintock, um professor de latim do Hampden-Sydney College na Virginia, pesquisou uma das mais obscuras palavras em latim, consectetur, oriunda de uma passagem de Lorem Ipsum, e, procurando por entre citações da palavra na literatura clássica, descobriu a sua indubitável origem.</option>
        <option value="06">Opção 6</option>
        <option value="07">Opção 7</option>
        <option value="08">Opção 8</option>
    </select>

o código JavaScript:
$(function(){

    $("#testselectset").selectBoxIt({
        theme: "default",
        defaultText: "Selecione abaixo...",
        autoWidth: false
    });
    $("#testselectset").change(function(){
        alert("Item selecionado: "+this.value);
    });

});

A folha de estilo:
.selectboxit-container .selectboxit, .selectboxit-container .selectboxit-options {
  width: 200px; /* Width of the dropdown button */
  border-radius:0;
  max-height:240px;
}

.selectboxit-options .selectboxit-option .selectboxit-option-anchor {
    white-space: normal;
    min-height: 30px;
    height: auto;
}
.selectboxit-option a {
  text-indent: 0px;
}

Clique aqui para ver o exemplo executando.
Este é o link da documentação. E este é o link do projeto.


text:
Q: Azure DevOps Deploy Release step on Failure Our structure for a release in azure devops is to
deploy our app to our DEV environment.
Kick off my Selenium (Visual Studio) tests against that environment.
If passes, moves to our TEST environment.
If fails/hard stop.
We want to add new piece/functionality, starts same as above, Except instead of hard stop. 5) if default step fails, continue to next step. 6) New detail testing starts (turns on screen recorder)
The new detailed step has 'Agent Job' settings/parameters, I have the section "Run this job", set to "Only when previous job has failed".
My results have been, that if the previous/default/basic testing passed, the detailed step is skipped. As expected.
But if the previous step fails....the following new detailed step does not kick off.
Is it possible because the step is set up that if it fails hard stop and does not even evaluate the next step?
Or is it because the previous step says 'partially succeeded'. is this basically seen not as a failure?

A: Yes, this is correct. Because failed is equivalent of eq(variables['Agent.JobStatus'], 'Failed') status. But partially succeeded is eq(variables['Agent.JobStatus'], 'SucceededWithIssues').
Please check here.
You may try custom conditions like :
in(variables['Agent.JobStatus'], 'Failed', 'SucceededWithIssues')

A: As an addition to the solution, a piece I missed was on the 'detailed' job, the 'Trigger even when the selected stages partially succeed', also needed to be checked, as well as the solution for the same step above.


text: Q: Classification of Difference Equation I have to find the Order, Dimension and Degree of the following Difference Equations and have to classify them according to their linearity/nonlinearity, homogenity and Autonomous/NonAutonomous nature. Help!!


text:
Q: i need to check for every commit made in the branch, need list the changed, added & deleted files in Git I need to list all the changed, deleted & added  files from a branch in one line. later put added and modified in one file called added_or_modified.txt and dleted into deleted.txt. is there any way to find changed, added & deleted files in one line?

A: (Since you're not mentionning between which states you want to diff, I've assumed the simplest context, diffing against HEAD. If you try to see diff between other given states, feel free to add it to your question, I'll adapt my answer)
I'd do something along the lines of
git diff --name-status

You'll have letters symbolizing file status before file names :
A added
C changed
D deleted
M modified
R renamed
T changed
U unmerged
X unknown
B broken pairing

See here for details about these states.

And for a deleted files list in a file (same principle for other states), you can do
git diff --diff-filter=D > deleted.txt

A: Your question title says you need to check each commit.  In that case perhaps you mean something like git log.  On the other hand, your description of the output sounds like you just want one list of files (or, later, two).  That suggests git diff instead.
git log --name-only --format="" <upstream_branch_name>..<branch_name>

or
git diff --name-only <upstream_branch_name>..<branch_name>

For example, if you're checking a branch named my_feature and want to know what's changed in each commit since since it diverged from a develop branch, you could say
git log --name-only --format="" develop..my_feature

Here I've used --format="" so that you just get a list of filenames; if you're generating a list per commit, you might want to do something different with the format option.  I mention it because, as written, a file could appear multiple times - even showing up once because commit A created it, and again because commit B deleted it.  If that's not desirable, and you just want the net change associated with the branch, use diff instead of log.
Down the line you could change that to
git log --name-status --format="" develop..my_feature

or
git diff --name-status develop..my_feature

and process the results to separate the deletes to their own file.  Be aware that with --name-status, git will by default apply rename detection.  So you might get some lines like
D    file1
A    file2
M    file3

which is what you would want to see.  The one starting with D was deleted, so put it in the delete list; the others were added and modified.  But you also might get some lines like
R99  fileX   fileY

meaning that git thinks you've renamed fileX to fileY and made minor modifications in the same commit.  If you'd rather git just give you
D    fileX
A    fileY

so that you see simply which paths appear and disappear individually, then add the --no-renames option, as
git diff --name-status --no-renames develop..my_feature


text:
Q: Helping linqtosql datacontext use implicit conversion between varchar column in the database and table and a custom data type in my application I am creating an mssql database table, "Orders", that will contain a varchar(50) field, "Value" containing a string that represents a slightly complex data type, "OrderValue".
I am using a linqtosql datacontext class, which automatically types the "Value" column as a string.
I gave the "OrderValue" class implicit conversion operators to and from a string, so I can easily use implicit conversion with the linqtosql classes like this:
// get an order from the orders table
MyDataContext db = new MyDataContext();
Order order = db.Orders(o => o.id == 1);

// use implicit converstion to turn the string representation of the order
// value into the complex data type.
OrderValue value = order.Value;

// adjust one of the fields in the complex data type
value.Shipping += 10;

// use implicit conversion to store the string representation of the complex
// data type back in the linqtosql order object
order.Value = value;

// save changes
db.SubmitChanges();

However, I would really like to be able to tell the linqtosql class to type this field as "OrderValue" rather than as "string". Then I would be able to avoid complex code and re-write the above as:
// get an order from the orders table
MyDataContext db = new MyDataContext();
Order order = db.Orders(o => o.id == 1);

// The Value field is already typed as the "OrderValue" type rather than as string.
// When a string value was read from the database table, it was implicity converted
// to "OrderValue" type.
order.Value.Shipping += 10;

// save changes
db.SubmitChanges();

In order to achieve this desired goal, I looked at the datacontext designer and selected the "Value" field of the "Order" table.
Then, in properties, I changed "Type" to "global::MyApplication.OrderValue".
The "Server Data Type" property was left as "VarChar(50) NOT NULL"
The project built without errors.
However, when reading from the database table, I was presented with the following error message:
Could not convert from type 'System.String' to type 'MyApplication.OrderValue'.
    at System.Data.Linq.DBConvert.ChangeType(Object value, Type type)
    at Read_Order(ObjectMaterializer`1 )
    at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
    at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
    at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
    at Example.OrdersProvider.GetOrders()
    at ... etc

From the stack trace, I believe this error is happening while reading the data from the table. When presented with converting a string to my custom data type, even though the implicit conversion operators are present, the DBConvert class gets confused and throws an error.
Is there anything I can do to help it not get confused and do the implicit conversion?

A: Interesting problem... I managed to do it by extending the generated data context partial class. In there I created a separate "typed" object which is set on load of the original data and replaces the original data on save...
namespace LinqSQLTest
{
    partial class DataClasses1DataContext
    {

    }

    partial class Order
    {
        public OrderValue TypedValue { get; set; }

        partial void OnLoaded()
        {
            TypedValue = this.Value;
        }

        partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            if (action == System.Data.Linq.ChangeAction.Insert ||
                action == System.Data.Linq.ChangeAction.Update)
            {
                if (TypedValue != null) Value = TypedValue;
            }
        }
    }
}

To use it, you'd access your "Value" through the "TypedValue" property instead - not ideal, but it's the only way I can see of doing it.
private void button1_Click(object sender, RoutedEventArgs e)
{
    DataClasses1DataContext dc = new DataClasses1DataContext();
    Order order = new Order();
    OrderValue value = new OrderValue();
    value.OrderID=22;
    value.OtherStuff="stuff";
    order.Value= value;
    dc.Orders.InsertOnSubmit(order);
    dc.SubmitChanges();

    var incomingOrder = dc.Orders.Where(x => x.ID == 32).FirstOrDefault();
    Console.WriteLine("ID: {0} \r\n Stuff: {1}", incomingOrder.TypedValue.OrderID, incomingOrder.TypedValue.OtherStuff);

    incomingOrder.TypedValue.OrderID += 10;
    dc.SubmitChanges();

    var incomingOrder2 = dc.Orders.Where(x => x.ID == 32).FirstOrDefault();
    Console.WriteLine("ID: {0} \r\n Stuff: {1}", incomingOrder2.TypedValue.OrderID, incomingOrder2.TypedValue.OtherStuff);

}

A: Having a similar problem, and using reflector I determined that I could provide a public static method called Parse taking a string argument. The System.Data.Linq.DBConvert.ChangeType(object, Type) will call the Parse method if it exists in the class.
So for your example, add to your OrderValue class
public static OrderValue Parse(string source) {
    return new OrderValue().FromSourceString(source); // whatever you need to do to construct from the source
}

This is using .NET 4.5; I'm not sure if this "Parse" method support exists in previous System.Data.Linq or not.


text:
Q: How can I have two modules interact with each other without having a circular import on Python? I am making a small game with several files including :
Entity.py , Map.py.
I want Map to be able to manage an Entity position, so I have to import Entity in Map, but I also want Entity to be able to know the map on which it is, so I have to import Map in Entity.
Obviously this leads to circular imports, and I know a lot of answers to this problem is "You just have to modify your design pattern" and ofc I could do that, but I want to know if there is a way in python to have this kind of structure that I got used to be able to use in Java.


text:
Q: SVG Text and Rect position I have this code:
<g pointer-events="default">
    <g>
        <g x="0" y="0" width="145" height="47" regroup="false">
            <text x="0" y="0">
                <tspan x="0" y="0">some text</tspan>
            </text>
        </g>
        <g x="0" y="0" width="80" height="60" regroup="false">
            <rect x="0" y="0" width="80" height="60" fill="white" />
        </g>
    </g>
</g>

There is one css rule box-sizing: border-box;which is apply to all elements.
It produce that:

The grid is coming from a sliding element from the first <g>.
I don't understand why the text element and the rect are not displayed at the same y.
Does anyone have any idea?


text:
Q: How to add constraint resolver in MVC 5? I have the following on an ASP.NET MVC 5 project:
DefaultInlineConstraintResolver resolver = new DefaultInlineConstraintResolver();
resolver.ConstraintMap.Add("notetype", typeof(EnumConstraint<NoteType>));
RouteTable.Routes.MapMvcAttributeRoutes(resolver);
GlobalConfiguration.Configuration.MapHttpAttributeRoutes(resolver);

On the last line the resolver is not accepted on MapHttpAttributeRoutes. How can I do this?

A: Try this
DefaultInlineConstraintResolver resolver = new DefaultInlineConstraintResolver();
resolver.ConstraintMap.Add("notetype", typeof(EnumConstraint<NoteType>));
RouteTable.Routes.MapMvcAttributeRoutes(resolver);
GlobalConfiguration.Configuration.MapHttpAttributeRoutes(new HttpRouteBuilder(resolver));


text:
Q: OpenCV StereoCalibration with ChArUco-Board provides wrong values I am currently working on a stereo calibration of two cameras. I am currently using a normal checkerboard. I also get correct results, for example I measure the distance of my cameras and compare them with the translation matrix.
Now I have heard that it is more robust if I use the ChArUco board. I tried to find something on the internet but there are really almost no tutorials. I then tried to program it myself, however I get nonsense results. Is it even possible to do a stereo calibration with a ChArUco board? I have added the main party of my code, maybe I did something wrong and someone can give me a hint.
Thank you.
import numpy as np
import cv2
import glob
import sys

###################
'''This code is for performing the stereo calibration if
the intrinsic parameters and the necessary images are available.'''
###################
# Create ChArUco
aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
board = cv2.aruco.CharucoBoard_create(9, 6, 3, 1.25, aruco_dict)
arucoParams = cv2.aruco.DetectorParameters_create()

counter_L, corners_list_L, id_list_L = [], [], []
counter_R, corners_list_R, id_list_R = [], [], []

# load the intrinsic parameters obtained from Int_Calibration.py
with np.load('c2.npz') as X:
    mtxR, distR, rvecsR, tvecsR = [X[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')]

with np.load('c1.npz') as X:
    mtxL, distL, rvecsL, tvecsL = [X[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')]

# Arrays to store object points and image points from all the images.
objpoints = []  # 3d point in real world space
imgpointsL = []  # 2d points in left image plane
imgpointsR = []  # 2d points in right image plane

# Get images for left and right directory
images_l = glob.glob('data1/*.jpg')
images_r = glob.glob('data2/*.jpg')

# Images should be perfect pairs. Otherwise all the calibration will be false
images_l.sort()
images_r.sort()

# Pairs should be same size. Otherwise we have sync problem.
if len(images_l) != len(images_r):
    print("Numbers of left and right images are not equal. They should be pairs.")
    print("Left images count: ", len(images_l))
    print("Right images count: ", len(images_r))
    sys.exit(-1)

# Pair the images for single loop handling
pair_images = zip(images_l, images_r)

for images_l, images_r in pair_images:
    # Left Image Points
    img_l = cv2.imread(images_l)
    grayL = cv2.cvtColor(img_l, cv2.COLOR_BGR2GRAY)
    corners_L, ids_L, rejected_L = cv2.aruco.detectMarkers(grayL, aruco_dict, parameters=arucoParams)
    resp_L, charuco_corners_L, charucos_ids_L = cv2.aruco.interpolateCornersCharuco(corners_L, ids_L, grayL, board)

    # Right Image Points
    img_r = cv2.imread(images_r)
    grayR = cv2.cvtColor(img_r, cv2.COLOR_BGR2GRAY)
    corners_R, ids_R, rejected_R = cv2.aruco.detectMarkers(grayR, aruco_dict, parameters=arucoParams)
    resp_R, charuco_corners_R, charucos_ids_R = cv2.aruco.interpolateCornersCharuco(corners_R, ids_R, grayR, board)

    objpoints_L, imgpoints_L = cv2.aruco.getBoardObjectAndImagePoints(board, charuco_corners_L, charucos_ids_L)
    objpoints_R, imgpoints_R = cv2.aruco.getBoardObjectAndImagePoints(board, charuco_corners_R, charucos_ids_R)

    if resp_L == resp_R and (resp_L and resp_R) > 1:
        corners_list_L.append(charuco_corners_L)
        corners_list_R.append(charuco_corners_R)

        id_list_L.append(charucos_ids_L)
        id_list_R.append(charucos_ids_R)

        objpoints.append(objpoints_L)
        imgpointsR.append(imgpoints_R)
        imgpointsL.append(imgpoints_L)
        # Draw and display the corners
        cv2.aruco.drawDetectedCornersCharuco(img_l, charuco_corners_L, charucos_ids_L, (255,0,0))
        cv2.aruco.drawDetectedCornersCharuco(img_r, charuco_corners_R, charucos_ids_R, (255,0,0))

        cv2.imshow('imgL', img_l)
        cv2.imshow('imgR', img_r)
        cv2.moveWindow("imgR", 800, 0)
        cv2.waitKey(200)
    else:
        print("Chessboard couldn't detected. Image pair: ", images_l, " and ", images_r)
        continue

cv2.destroyAllWindows()

ret, M1, d1, M2, d2, R, T, E, F = cv2.stereoCalibrate(objpoints, imgpointsL, imgpointsR, mtxL, distL, mtxR, distR,(640, 480))
print(T)


text:
Q: How to make https.get request assign data from within the request to a variable outside of the request? I'm trying to get an https.get request to assign data from within the request to a variable outside of the request. I'm also using axios. Within the https.get request, it returns the data I want in the res.on('end'... But I can't figure out how to get that data outside of the res.on('end'... portion of the request. Here is my code:
require('dotenv').config();
const express = require('express');
const {SERVER_PORT} = process.env;
const https = require('https');
const xml2js = require('xml2js');
const parser = new xml2js.Parser({ attrkey: "ATTR" });

const app = express();

app.use(express.json());

app.post('/api/ecb/forex/stats', async(req, res) => {
    const {base_currency, base_amount, target_currency} = req.body;

    let currencyInfo = https.get("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml", function(res) {
        let data = '';

        res.on('data', async function(stream) {
            data += stream;
        });
        res.on('end', async function(){
            parser.parseString(data, async function(error, result) {
                if(error === null) {
                    return result['gesmes:Envelope'].Cube[0].Cube.forEach(element => {
                            console.log("at",element.Cube);
                            return element.Cube;
                        });;
                }
                else {
                    console.log(error);
                }
            });
        });
    });
    console.log(currencyInfo);
})

const port = SERVER_PORT;
app.listen(port, () => console.log(`Port running on port ${port}`));

I want the value of 'element.Cube;' within the res.on('end"... portion of the https.get request to be assigned to the variable "currencyInfo". What am I doing wrong and how do I fix the code?

A: You can change your code to something like below, then you have Promise to return:
let currencyInfo = await new Promise((resolve, reject) => {
  https.get('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml', function(res) {
    let data = '';

    res.on('data', async function(stream) {
      data += stream;
    });
    return res.on('end', async function() {
      return parser.parseString(data, async function(error, result) {
        if(error === null) {
           return result['gesmes:Envelope'].Cube[0].Cube.forEach(element => {
             resolve(element.Cube);
          });
        }
        else {
          reject(error);
        }
      });
    });
  });
});


text:
Q: Is there a regex to exclude a word list in awk? In an awk program , I'm trying to select the input from a line containing <<<local>>> and the next line containing the pattern <<<XXXX>>>, where
XXXX will be anything else but local.
<<<local>>>
line1
line2
line3
<<<XXXX>>>

The simplest awk code would be
$0=="<<<local>>>",/^<<<XXXX>>>$/ { ··· }

but XXXX should be replaced with a proper regular expression to exclude local.
As far I know, that can be done in python
(?!local)

and in Korn shell and other shells:
!(local)

but I have found nothing about this issue in the regex(7) man pages.
In order to bypass this handicap I use
$0=="<<<local>>>",/^<<<.+>>>$/ && $0!="<<<local>>>" { ··· }

but the crux of this question of mine is wether the awk regex engine accepts somehow a word list to exclude, I mean, as a counterpart of word1|word2|word3.

A: this would do...
awk '/<<<local>>>/{f=1} f; /<<<.*>>>/ && !/<<<local>>>/{f=0}' file

if you don't want to terminate the range for another word you can add to !/<<<(local|other)>>>/


text:
Q: MongoDB - Update with python I want to try add more values to array, but therefor two values must match. I get it working with one value, but not with two. This is what I have:
    { "_id" : ObjectId( "50f1a05d00bf6832b03a01cb" ),
  "app" : "494258956",
  "keywords" : [
    { "data" : [
        { "device" : "software",
          "date" : Date( 1358012509633 ),
          "rank" : 1,
          "shop" : "143443" } ],
      "keyword" : "test" } ] }

When I have a new "data" for the keyword "test" and app "494258956", then a new set should be added to "data" and look like this:
    { "_id" : ObjectId( "50f1a05d00bf6832b03a01cb" ),
  "app" : "494258956",
  "keywords" : [
    { "data" : [
        { "device" : "software",
          "date" : Date( 1358012509633 ),
          "rank" : 1,
          "shop" : "143443" }
 , { "device" : "software",
          "date" : Date( 1358012599633 ),
          "rank" : 2,
          "shop" : "143443" }],
      "keyword" : "test" } ] }

Thanks in advance.

A: This seems to do what you're asking (JavaScript syntax):
    coll.update({
        "app": "494258956",
        "keywords": {
            "$elemMatch": { "keyword": "test" }
        }
    },
    {
        "$push": {
            "keywords.$.data": {
                "device" : "software",
                "date" : new Date( 1358012599633 ),
                "rank" : 2,
                "shop" : "143443"
            }
        }
    }

A: Currently this isn't supported - because the positional operator $ doesn't currently work with upsert.  Please vote for SERVER-3326
Workarounds might be to revisit the schema design or multiple operations where you don't use a upsert - and inspect the number of items updated.  You have to take care not to hit a race condition eg:

*

*Do an update where {keywords: {$exists: true}}

*If update returns 0 - no keywords perform an upsert: where {keywords: {$exists: false}}

*If update returns 0 - there was a race and someone added keywords can now perform step 1.


text:
Q: Activator.CreateInstance with custom class argument I am trying to create a instance(Class Test) from dll by using Activator.CreateInstance.
Class Test has one constructor which requires a arguement Class CommonService. But it throw System.MissingMethodException error.
There is the code:
// Define
public class Test: BaseTest
{
    public Test(CommonService commonService) : base(commonService, new TestConfigurations()
    {
       enableTimer = false
    })
    {
    }
}

// Usage
var commonService = new CommonService();
var test = new Test(commonService); // test can be created successfully.

var dll = Assembly.LoadFile(@"xxx\Test.dll");
foreach (Type type in DLL.GetExportedTypes())
{
    if (type.BaseType?.Name?.Equals("BaseTest") == true)
    {
        dynamic c = Activator.CreateInstance(type, new object[] { // Throw System.MissingMethodException error
            commonService
        });
    }
}

Here is the full code link: https://codeshare.io/2EzrEv
Is there any suggestions about how to solve the problem?

A: The Activator.CreateInstance as shown: should work just fine. If it isn't, then the type you're initializing might not be what you think it is - check the value of type.FullName. Alternatively, it is possible that you have types by the same name in different locations, meaning: the CommonService that you're passing in is not the same as the CommonService that the type is expecting. You can check that with reflection. The following prints True twice:
using System;
using System.Linq;
using System.Reflection;

public class Test : BaseTest
{
    public Test(CommonService commonService) : base(commonService, new TestConfigurations()
    {
        enableTimer = false
    })
    {
    }
}

static class P
{
    static void Main()
    {
        // Usage
        var commonService = new CommonService();
        var test = new Test(commonService); // test can be created successfully.

        var type = typeof(Test); // instead of loop
        dynamic c = Activator.CreateInstance(type, new object[] { // Throw System.MissingMethodException error
            commonService
        });
        Console.WriteLine(c is object); // it worked

        var ctor = type.GetConstructors().Single();
        var ctorArg = ctor.GetParameters().Single();
        Console.WriteLine(ctorArg.ParameterType == typeof(CommonService)); // check the expected param type
    }
}
public class CommonService { }
public class TestConfigurations
{
    internal bool enableTimer;
}
public class BaseTest
{
    public BaseTest(CommonService svc, TestConfigurations cfg) { }
}


text:
Q: Ariadna fastAPI how to parse GraphQL request Here is my API:
app = FastAPI()
app.add_middleware(CORSMiddleware,
                   allow_origins=['*'],
                   allow_credentials=True,
                   allow_methods=["*"],
                   allow_headers=["*"])

type_defs = load_schema_from_path("schema.ql")
schema = make_executable_schema(type_defs, query,
                                snake_case_fallback_resolvers)
# print(dir(schema.__dict__))
print(schema.__dict__)
app = CORSMiddleware(GraphQL(schema, debug=True),
                     allow_origins=['*'],
                     allow_methods=("GET", "POST", "OPTIONS"))

Is there a way to parse an Ariadne graphql request into python key values at the middleware / router level in this file?


text:
Q: Bootstrap.min extremely slow in chrome while firefox runs fine Does anyone know why this is happening?
This occurs the section where the responsive video is embedded in the webpage.
Firefox runs fine, but chrome lags where that spot is crossed.
How to mitigate this issue? I am using instead.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

A: I faced the same problem, IE / FF works fast while chrome was slow.
I used bootstrap rtl version,
issue solved when i removed the direction: rtl property from the html tag.


text:
Q: var keyword turns black instead of blue Sometimes I get this strange behaviour in Visual Studio (both versions 2012 and 2013).

The var keyword simply turns black as if it isn't a keyword at all. If I want it to be blue again I have to delete it and write it again. Why?
It is not a deal-breaker but it irritates me because I use var pretty often. I can reproduce it by writting, for instance, var test = "test"; first and then writting on a line above another expression using var.


text:
Q: How can I change the output display of my pagination? How can I change the output display of my pagination? I have been trying for the past few hours to format the output of my pagination links (1,2,3, etc.) to resemble the below:

I have been unable to modify the code to get it even close to this. Could someone please point me in the right direction of what I need to be doing?
Here is my code:
<?php
    if ( get_query_var( 'paged' ) ) {
        $paged = get_query_var('paged');
    }elseif( get_query_var( 'page' ) ) {
        $paged = get_query_var( 'page' );
    }else{
        $paged = 1;
    }

    $per_page = 3;
    $number_of_terms = wp_count_terms( 'series' ); // This counts the total number terms in the taxonomy with a function)
    $paged_offset = ($paged - 1) * $per_page;

    $args = array(
        'orderby'           => 'ID',
        'order'             => 'DESC',
        'hide_empty'        => 0,
        'number'            => $per_page,
        'offset'            => $paged_offset
    );

    $terms = get_terms('series', $args);

    foreach($terms as $term){ ?>

            <div  class="article_image" style="background: url('<?php the_field('series_artwork', $term); ?>'); background-size: cover; background-position: 50%;">

<?php the_field('date', $term); ?>

<?php echo $term->name; ?>

<?php echo $term->description; ?>

                <a href="<?php echo get_term_link($term->slug, 'series'); ?>" class="button_styling">
                    Read More

    <?php }

    $big = 999999999; // need an unlikely integer
    echo paginate_links(
        array(
            'before_page_number' => '
Page '. $paged .' of ' . $term->max_num_pages . '
',
            'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format'  => '/page/%#%',
            'current' => max( 1, get_query_var('paged') ),
            'total'   => ceil( $number_of_terms / $per_page ),
            'prev_text' => __(''),
            'next_text' => __('')
        )
    );
?>

If you can get it to work with my existing function (something I have been trying to do) then bonus points to you!
functions.php
// numbered pagination
function pagination($pages = '', $range = 4)
{
 $showitems = ($range * 2)+1;

 global $paged;
 if(empty($paged)) $paged = 1;

 if($pages == '')
 {
     global $wp_query;
     $pages = $wp_query->max_num_pages;
     if(!$pages)
     {
         $pages = 1;
     }
 }

 if(1 != $pages)
 {
     echo "
Page ".$paged." of ".$pages."";
     if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "« First";
     if($paged > 1 && $showitems < $pages) echo "‹ Previous";

     for ($i=1; $i <= $pages; $i++)
     {
         if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
         {
             echo ($paged == $i)? "".$i."":"".$i."";
         }
     }

     if ($paged < $pages && $showitems < $pages) echo "Next ›";
     if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "Last »";
     echo "
\n";
 }
}

Function Call
<?php if (function_exists("pagination")) {
     pagination($terms->max_num_pages);
} ?>

Thank you for any help that can be provided!

A: I could see that you are trying to achieve the following output:

  Page {current} of {total pages}
  {links here}

And you attempted it like so:
'before_page_number' => '
Page '. // wrapped for clarity
  $paged .' of ' . $term->max_num_pages . '
'

But that will actually add the markup before each and every page number in the generated links. (And the $term->max_num_pages is also a null because in that context, $term doesn't have a max_num_pages property.)
So here's how you could achieve the expected output:
$big = 999999999; // need an unlikely integer
$cur_page = max( 1, $paged );
$num_pages = ceil( $number_of_terms / $per_page );
$links = paginate_links(
    array(
        'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format'  => '/page/%#%',
        'current' => $cur_page,
        'total'   => $num_pages,
        'prev_text' => __(''),
        'next_text' => __('')
    )
);

// If there are links to paginate, display the pagination.
if ( $links ) {
    $before = 'Page '. $cur_page .' of ' . $num_pages . '';
    echo '
' . $before . ' ' . $links . '
';
}

See the paginate_links() reference for more details on that function, such as the mid_size and end_size parameters that control the number of pages/links to be displayed.

A: The following will loop through a custom taxonomy and pull all the associated terms.
<?php if ( get_query_var( 'paged' ) ) {
        $page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    }

    $per_page = 9;
    $totalterms   = wp_count_terms( 'series' );
    $totalpages   = ceil( $totalterms / $per_page );
    $paged_offset = ( $page > 0 ) ?  $per_page * ( $page - 1 ) : 1;

    $args = array(
        'orderby'       => 'ID',
        'order'         => 'DSC',
        'hide_empty'    => true,
        'exclude'       => array(),
        'exclude_tree'  => array(),
        'include'       => array(),
        'number'        => $per_page,
        'fields'        => 'all',
        'slug'          => '',
        'parent'         => '',
        'hierarchical'  => true,
        'child_of'      => 0,
        'get'           => '',
        'name__like'    => '',
        'pad_counts'    => false,
        'offset'        => $paged_offset,
        'search'        => '',
        'cache_domain'  => 'core'
    );

    $terms = get_terms('series', $args);

    foreach($terms as $term){ ?>

            <div  class="article_image" style="background: url('<?php the_field('series_artwork', $term); ?>'); background-size: cover; background-position: 50%;">

<?php the_field('date', $term); ?>

<?php echo $term->name; ?>

<?php echo $term->description; ?>

                <a href="<?php echo get_term_link($term->slug, 'series'); ?>" class="button_styling">
                    Read More

    <?php }

    $big = 999999999; // need an unlikely integer
    printf( '
Page '.$page.' of '.$totalpages.'',
        custom_page_navi( $totalpages, $page, 3, 0 )
    );

    echo paginate_links(
        array(
            'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format'  => '/page/%#%',
            'current' => max( 1, get_query_var('paged') ),
            'total'   => ceil( $totalterms / $per_page ),
            'prev_next' => false
        )
    ); ?>


text:
Q: How to fix my code which is used in the validation step? When I train a Resnet, the accuracy of the shuffled validation set is not equal to the unshuffled version's.
The training set is shuffled in the same way.
I've tried to use a single sample each time to feed the network and got the same accuracy in the vali-set. But, when I use a batch of samples each  time, say 256, the accuary is not equal.
training process
count = 1
while 1:

    #get training_data
    if (count - 1) % 5200 == 0:
        train_set,train_label = get_traindata(eng, 70)

    tset,tlabel = train_set,train_label
    tset_num = tset.shape[0]

    #split and train
    num_batches = tset_num // batch_size
    order = np.random.choice(tset_num, num_batches * batch_size,replace = False)
    train_data_subset = tset[order,:]
    train_labels_subset = tlabel[order]

    for step in range(num_batches):

        offset = step * validation_size
        feed_dict = {
                    x: train_data_subset[offset:offset+batch_size,:],
                    y: train_labels_subset[offset:offset+batch_size],
                    }
        _, tloss, tacc,gd = sess.run([train_op,loss, accuracy,grad_norm],
                                     feed_dict=feed_dict)
        if (count-1) % 200 == 0:

            #get validationset
            if (count-1) % 1400 == 0:
                vset,vlabel = get_validata(eng, 20)
                vnum_batches = vset.shape[0] // validation_size
                order = np.random.choice(vset.shape[0], vnum_batches * validation_size,replace = False)  #shuffled
                va_data_subset = vset[order,:]
                va_labels_subset = vlabel[order]

            loss_list = []
            error_list = []
            loss_list_s = []
            error_list_s = []
            for stepv in range(vnum_batches):
               offsetv = stepv * validation_size
               feed_dict_shuffle = {
                    x: va_data_subset[offsetv:offsetv+validation_size,:],
                    y: va_labels_subset[offsetv:offsetv+validation_size],
                    }
               vloss_s, vacc_s = sess.run([loss, accuracy], feed_dict=feed_dict_shuffle)
               loss_list_s.append(vloss_s)
               error_list_s.append(vacc_s)
               feed_dict = {
                    x: vset[offsetv:offsetv+validation_size,:],
                    y: vlabel[offsetv:offsetv+validation_size],
                    }
               vloss, vacc = sess.run([loss, accuracy], feed_dict=feed_dict)
               loss_list.append(vloss)
               error_list.append(vacc)
            #the performance in the shuffled vali-set
            vloss_s = np.mean(loss_list_s)
            vacc_s = np.mean(error_list_s)
            #the performance in the unshuffled vali-set
            vloss = np.mean(loss_list)
            vacc = np.mean(error_list)

Theoretically, the order of the vali-set will not influence the result.

A: I'm assuming you are either using dropout or batch normalization. In either case you need to feed a bool tensorflow variable to training parameter during inference. Since the order seems to affect results, I'm going to assume batch normalization:
https://www.tensorflow.org/api_docs/python/tf/layers/batch_normalization.
feed training=False with a tensorflow placeholder


text:
Q: Suppress errors for if(file_exists) I was wondering if suppressing warning for a method might ever be a better and shorter version of using  an if or shorthand if statement like so:
if(file_exists('a/file/path/that/doesnt/exist.file')) {

    unlink('a/file/path/that/doesnt/exist.file');

}

Possible shorter version:
@unlink('a/file/path/that/doesnt/exist.file');

If we are definitely sure, that the only problem that could occur during the unlink method is a 'file missing/not found' situation, and not anything else(permission denied etc.), would it be okay to simply suppress the unlink function?


text:
Q: What does "their" refer to in this sentence? I'm having a hard time with this sentence:

Professional bodies will monitor, and if necessary, discipline members who do not adhere to their ethical principles.

Does 'their' refer to the members or to the professional bodies?

A: I agree with @Nigel J in that the sentence is ambiguous, but if I had to guess:
Short answer
'Their' refers to the professional bodies.
Explanation
From a practical standpoint, a professional body probably doesn't exist to enforce one member's set of ethical principles, which may differ from one member to another. Rather, a professional body likely exists to enforce the agreed-upon ethical principles of an organization with which that professional body is associated.


text:
Q: Azure Cloud Shell blue and blank Azure cloud shell shows weird behavior most of the time. As shown in the image it remains blank. If we type the white courser moves. Sometimes we can see it all but when we execute a command the cursor goes up and remains among the text above. we have to clear screen to see the cursor again or to see what we type. Is there an alternative UI to cloud shell?

EDIT:
As per one of the answers below I tried another link. But that too gave the same error as given below. Frequency is less in this UI though.

A: You can also go to this link -> then click the Try It button:

After login, you can see the azure cloud shell screen:

Or if you still have the issue in azure portal, just click the restart button to reset the cloud shell:


text:
Q: Adding handler name in Monolog logs from Symfony I'm using a custom monolog processor as described here and I'd like to add the handler name into my logs.
The code snippet on above links shows the argument being passed as session. How can I pass in the handler argument?
    app.logger.session_request_processor:
        class: AppBundle\Logger\SessionRequestProcessor
        arguments:  ['@session']
        tags:
            - { name: monolog.processor, method: processRecord }

A: This is not as easy as it seems. Processor are either registered per logger or per handler.
If the processor is registered in the logger, there is no way of knowing which handler the processor went through, as all handlers are executed after all processors were executed. If you register the processor on a handler, you always know which handler is executed, but registering a processor for every handler manually is quite cumbersome.
In order to solve this, you could add a CompilerPass which does the manual work for you.
Lets assume we have this processor
class HandlerProcessor
{
    /**
     * @var string
     */
    private $handlerName;

    public function __construct($handlerName)
    {
        $this->handlerName = $handlerName;
    }

    public function processRecord(array $record)
    {
        $record['extra']['handler_name'] = $this->handlerName;

        return $record;
    }
}

With this processor you can then create a compiler pass, which creates all the definitions for the different handlers monolog created
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class HandlerProcessorPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasParameter('monolog.handlers_to_channels')) {
            return;
        }

        foreach ($container->getParameter('monolog.handlers_to_channels') as $handlerId => $channels) {
            $definition = new Definition(HandlerProcessor::class);
            $handlerDefinition = $container->getDefinition($handlerId);

            $handlerName = $handlerDefinition->getClass();
            $definition->addArgument($handlerName);

            $handlerProcessorId = 'handler_processor.' . $handlerId;
            $container->setDefinition($handlerProcessorId, $definition);

            $handlerDefinition->addMethodCall('pushProcessor', array(new Reference($handlerProcessorId)));
        }
    }
}

As compiler passes can be quite confusing if you never used them before, lets go line by line:
if (!$container->hasParameter('monolog.handlers_to_channels')) {
    return;
}

This checks if the monolog bundle is registered. The parameter monolog.handlers_to_channels is added to the container in the MonologExtension. The parameter itself contains an array where the key is the name of the handler id and the value is an array with all channels this handler is registered to (or null if this handler is valid for all channels)
foreach ($container->getParameter('monolog.handlers_to_channels') as $handlerId => $channels) {
    $definition = new Definition(HandlerProcessor::class);
    $handlerDefinition = $container->getDefinition($handlerId);

Here we create a new definition of our HandlerProcessor and get the definition of the current processed handler.
$handlerName = $handlerDefinition->getClass();
$definition->addArgument($handlerName);

This will fetch the class name of the handler (e.g. Monolog\Handler\SlackHandler) and adds it as a constructor argument to the HandlerProcessor
$handlerProcessorId = 'handler_processor.' . $handlerId;
$container->setDefinition($handlerProcessorId, $definition);

$handlerDefinition->addMethodCall('pushProcessor', array(new Reference($handlerProcessorId)));

And last but not least we create a new ID for the processor definition we just created at the beginning of the foreach loop and add it with the method call pushProcessor to our newly created processor.
Now that everything is set up, you have to register this compiler pass in your container. I assume you are using symfony 2.x so you have to do that in your AppBundle
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new HandlerProcessorPass());
    }
}

Here are some additional links which might be helpful:

*

*https://symfony.com/doc/2.7/service_container/definitions.html

*https://symfony.com/doc/2.7/service_container/compiler_passes.html

*https://symfony.com/doc/2.7/service_container/calls.html


text:
Q: Socket notifications I have a screen that receives notifications from the Spring Boot backend, and I show them in a bell. When deleting a notification it deletes it well, but when another new notification arrives it loads the ones that I had already deleted.
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

// core components

const HeaderNotificacions = () => {

const [chipData, setChipData] = useState([]); //Hook where I load the notifications that come from the backend    >

const historyAlerts = localStorage.getItem('notys')
 ? JSON.parse(localStorage.getItem('notys'))
 : [];   if (chipData.length === 0 && historyAlerts.length !== 0) { //I get the notifcations when I reload the browser
 setChipData(historyAlerts);   }

useEffect(() => {

 var sock = new SockJS(
   `${process.env.REACT_APP_WEB_SOCKET}mocaConsola/api/notifications`
 );
 let stompClient = Stomp.over(sock);
 sock.onopen = function () {
   /*    console.log('open'); */
 };
 stompClient.connect({}, function (frame) {
   stompClient.subscribe('/ws/alertNotification', function (greeting) {
     if (stompClient !== null) {
       stompClient.disconnect();
     }

     setChipData([
       ...chipData,
       {
         key: greeting.headers['message-id'],
         label: JSON.parse(greeting.body).content,
       },
     ]);
   });
 });   }, [chipData]);

localStorage.setItem('notys', JSON.stringify(chipData));

const handleDelete = (chipToDelete) => () => {
 const historyAlerts = localStorage.getItem('notys')  //function to delete a notification
   ? JSON.parse(localStorage.getItem('notys'))
   : [];

 setChipData((chips) =>
   chips.filter((chip) => chip.key !== chipToDelete.key)
 );

 const local = historyAlerts.filter((chip) => chip.key !== chipToDelete.key);
 localStorage.setItem('notys', JSON.stringify(local));   };

A: One of the problems could be that you do not disconnect from the socket, so first subscription (having initial value of chipData in closure) brings it back. Unsubscribing on effect's clean up could help, similar to:
useEffect(() => {

/* your code */

>     stompClient.connect({}, function (frame) {
>       subscription = stompClient.subscribe('/ws/alertNotification', function (greeting) {
>         if (stompClient !== null) {
>           stompClient.disconnect();
>         }
>
>         setChipData([
>           ...chipData,
>           {
>             key: greeting.headers['message-id'],
>             label: JSON.parse(greeting.body).content,
>           },
>         ]);
>       });
>     });

   return () => subscription && subscription.unsubscribe();
}, [chipData]);

Also for performance considerations we can skip recreation of the connection/subscription each time we update chipData. We can use callback version of setChipData's argument which refer to latest value of state.
setChipData(prevData => [
>           ...prevData,
>           {
>             key: greeting.headers['message-id'],
>             label: JSON.parse(greeting.body).content,
>           },
>         ]);

so we can replace [chipData] to [] as second argument of useEffect and open connection only once per component load.


text:
Q: Is it possible to set up an alias on an Active Directory domain controller Linux server? We have a Red Hat Enterprise based Linux distro that is the domain controller for a bunch of Win 10 clients. Some clients are not in the right AD domain (they are on a former domain that was used before the server crashed and was reconfigured before I came here.)
I can't change them to the right domain because I can't login with admin account.
Now, I'd like to set up an alias for the old domain so the clients can find and login on the server. So how do I do that? Any help is appreciated.
Thanks

A: This is not how domains work. They won't be able to login or otherwise work correctly with the new domain even if you were able to set up "alias".
Use tools, (e.g. chntpw) to change admin passwords in those computers, then join them correctly into the new domain.


text:
Q: Transform text in OpenOffice.org Spreadsheet I have list of text that contain double quoate and upderscore.
How can I use function to change text pattern to following format.
"CUSTOMER_DETAIL"  to CustomerDetail
"PERSON" to Person
"CUSTOMER_ADDRESS_DETAIL" to CustomerAddressDetail

Thank you for replay.

A: Use SUBSTITUTE to replace "_" with space and PROPER to capitalize first letters. Use MID to get text inside quotes. At the end use SUBSTITUTE to strip spaces.
=SUBSTITUTE(PROPER(SUBSTITUTE(MID(A1;2;LEN(A1)-2);"_";" "));" ";"")


text:
Q: How to create a custom error message for a spring boot rest aplication I am using Spring Boot to handle REST calls. In this context, I have implemented a controller class with the following method:
@GetMapping("/{id}")
public ResponseEntity<employeeDetails> getEmployee(@PathVariable Long id) {
    Optional<Employee> employee = employeeService.getEmployee(id);
    if (employee.isPresent()) {
        return ResponseEntity.ok(employee.get());
    } else {
        throw new ApiRequestException("Could not find requested employee");
    }
}

I am now sending a request, asking for a non-existent employee. I have verified that the else-block is executed. My issue is that I am not returned a custom error message, instead I see the same old error message in my Browser console that I have seen before implementing the ApiRequestException:

I cannot understand why I don't see my custom error message. Here is how I have implemented the ApiRequestException:

*

*I have implemented the ApiRequestException class:
public class ApiRequestException extends RuntimeException {

  public ApiRequestException(String message) {
    super(message);
  }
}

*I have implemented an Exception handler:
@ControllerAdvice
public class ApiExceptionHandler {

  @ExceptionHandler(value = { ApiRequestException.class })
  public ResponseEntity<Object> handleApiRequestException(ApiRequestException e) {
    HttpStatus badRequestStatus = HttpStatus.BAD_REQUEST;
    ApiRequestError apiRequestError = new ApiRequestError(badRequestStatus, e.getMessage());
    return ResponseEntity.status(badRequestStatus)
                         .body(apiRequestError);
  }
    }

*Well, as you can see, the exception handler is using an ApiRequestError class. I have implemented this as well: It's just a class that stores a message-string and an httpStatus.
When debugging my application, I have verified that the exception handler is called. Setting a breakpoint inside my GET-Controller shows that the ApiRequestException is thrown. The exception is handled by the ExceptionHandler.
So, anyways, I cannot explain why there is no custom error message in my browser console, but instead what seems to be a default message generated by Spring Boot. Can somebody help?
===================================================
update:
As it turns out, this issue seems to be related to my frontend, not my backend. The code I have presented here works fine. I have tested this by logging the error message in the way described in this follow-up question.

A: Try extending ResponseEntityExceptionHandler
@ControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler{
    ...
}

A: Did you add these configs in the properties file?
server.error.include-message=always
server.error.include-binding-errors=always


text:
Q: Variables documentation in Scala I'm new in Scala (I come from Java) and I would like to know how is the correct way to generate documentation for the class variables.
For example, if I have the following code:
class MyClass (bar:bar) {

  val foo = bar

  def function {
      ...
      ...
  }
}

what's the correct way to create the documentation for the variable foo ? Do I just add the comment right before the declaration? Isn't it a bit confusing?
Thanks!

A: You can use Javadoc in Scala. But Scala also introduces its own documentation generator called Scaladoc. This is what is used to generate the standard language documentation.
In general, Scaladoc follows similar conventions to Javadoc but introduces new features. You can read more about Scaladoc comments style here.

A: There is no difference between java and scala comments. You can choose any documentation strategy you used in java.


text:
Q: Pannellum clickHandlerFunc I am trying to use the clickHandlerFunc to open a Modal box. I am getting the error "Uncaught TypeError: a.clickHandlerFunc is not a function at HTMLDivElement. (pannellum.js:68)"
The following is my codes:
"hotSpots": [
                    {

                        "pitch": 1.60311491347256,
                        "yaw": 22.349004691308146,
                        "type": "scene",
                        "text": '',
                        "sceneId": "",
                        "clickHandlerFunc": "openModal"
                    },

function openModal() {
        $(".popup-overlay, .popup-content").addClass("active");
    }

How can I resolve the problem? I need to open a modal box when the hotspot is clicked.

A: Try the following out...
first define the function you wish to call before the call to pannellum, for example..
var openModal=function(){alert("hello")};

Then the line for the click handler should be...
"clickHandlerFunc": openModal

i.e. without the quotes.
Substitute the alert("hello") for whatever function call or code that you like.


text:
Q: Is there a way to reverse the comparison direction of ruby case statements? Let me explain with code, and perhaps it will become more clear what I'm asking. This of course is hypothetical code given that it does not currently function in the manner I'm intending (the deductive and creative abilities of humans I'm clearly leveraging here).
class AnySet < Array
  def ===(other)
    (other & self).any?
  end
end

class AllSet < Array
  def ===(other)
    other.sort == self.sort
  end
end

case AnySet.new([:bar])
when [:bar]
  true # a more complex...
when [:bar, :biz]
  true # result could...
when [:biz]
  false # be imagined.
end

case AllSet.new([:biz, :bar])
when [:bar, :biz]
  true # a more complex...
when [:biz, :foo]
  false # result could...
when [:biz]
  false # be imagined.
end

Note: poor :biz. :)
Wouldn't this be handy? Anyway to accomplish this or am I restricted to building my A**Sets in the when clauses?
Edit: I tweaked the A**Set classes to extend Array. Not really important, I'm just OCD.

A: With ruby's built-in case/when it's not possible. when clauses will contain receivers of the threequals operator and its argument will be the value you passed to the case.
You could flex your metaprogramming muscles and cook up a custom function/DSL for this.
consider AllSet.new([:biz, :bar]) do
  if_matches [:bar, :biz]  { 'first' }
  if_matches [:biz, :foo]  { 'second' }
  if_matches [:biz] { 'third' }
end

It's up to you to decide if this is an improvement in readability/maintainability (or whichever other metric is important to you).


text:
Q: Specificity issue in CSS So I have a list of items inside a div with the class book-select and one of the li's in my unordered list has the class selected.  According to the CSS rules I've defined, the li's in the div has the background color skyblue and the one li with the class selected would be steelblue.
The problem is that the book-select class is overwriting the selected class, which I don't understand.  Wouldn't the div class be less specific than the li with the class selected?  The li is in a ul which is in the div.
Here's the relevant CSS and HTML:
.book-select li {
    font-size: 0.75em;
    text-align: center;
    list-style: none;
    background: skyblue;
    width: 25%;
    margin: auto;
}

.selected {
    background: steelblue;
}

Pick a book:

Set A Volume 1, Course Foundation

Set A Volume 2, Expeditionary Airman

Set A Volume 3, Professional Airman

Set B Volume 1, Supervisory Communicator

Set B Volume 2, Supervisor of Airmen

All

This is part of a quiz and the idea is that the user clicks on a book and jQuery will change the class of the selected item to whatever is clicked on, with the last li with the text "All" being the default selected book.  I could use a different jQuery method to change the background color, but the fact that CSS is giving me this specificity error is bothering me.
I know .book-select li is overwriting .select because the console is showing the background: steelblue; as crossed off.
Shouldn't it be the other way around?  Isn't .selected the more specific class, as it only contains one element, which is itself?

A: Use this selector to increase the specifity of that CSS rule:
.book-select li.selected {
   background: steelblue;
}

About "specifity": Simply said, one class plus one tag (.book-select li)  has more "weight" concerning specifity than just one class (.selected), so a rule with one class plus one tag will overwritea rule with  just one class.  And the selector shown above will overrule that again, since it consists of two classes and one tag.

A: Even Something as simple as
li.selected
{
background: steelblue;
}

Should overide the background for you :)

A: for a possible solution, you can do this:
.selected {
    background: steelblue !important;
}

important will avoid this style from being override