text:
Q: Issue Setting ContentVersion Owner I am getting an attachment via a Salesforce email service and in the Email service apex class logic, I query the user object by the email from address and set the ContentVersion owner as the user coming from the Query.
I am getting this error while performing this operation.
INVALID_STATUS, Documents in a user's private library must always be owned by that user.: [OwnerId]
Here is my code :
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

        //Get users for the incoming email address and also community user
        List<User> lstUsersFromCommunity = [SELECT Id
                                            FROM User
                                            WHERE Profile.UserLicense.Name = 'Partner Community';
                                            AND Email =: email.fromAddress];

        //Process only if the incoming email address is belongs to a valid community user
        if(lstUsersFromCommunity.size() > 0){
            //Get the user from the results list
            User user = lstUsersFromCommunity.get(0);
            try{
                //Create a list of ContentVersion to store new ContentVersion records
                List<ContentVersion> lstVersion = new List<ContentVersion>();
                //Iterate over the incoming email attachments
                for (Messaging.Inboundemail.BinaryAttachment binaryAttachment : email.binaryAttachments) {
                    //New ContentVersion record
                    ContentVersion newContentVersion = new ContentVersion();
                    newContentVersion.versionData = binaryAttachment.body;
                    newContentVersion.OwnerId = user.Id;
                    newContentVersion.ContentLocation = 'S';
                    newContentVersion.SharingOption = 'A';
                    newContentVersion.Origin = 'H';
                    newContentVersion.title = email.subject;
                    newContentVersion.pathOnClient = binaryAttachment.fileName;
                    lstVersion.Add(newContentVersion);
                }
                insert lstVersion;
            }catch(Exception ex){
                System.debug('### EXCEPTION :  ' + ex.getLineNumber() + ' : ' + ex.getMessage());
            }
        }else{
            //No user in for the from email address
        }

        return result;
    }

A: Add this line:
newContentVersion.firstPublishLocationId= user.Id;

A more detailed explanation:
When documents are created via apex (contentversion object), you need to specify the library otherwise they will always be created in private library of the context user. Since you are querying a random user (and probably this user is not the context user of running code), your code tries to create document in context users private library but owner is coming from your user query.
To better understand the data model of contents, create a library in your org and upload a file by using user interface. (file will be uploaded to your private library). Then publish it to library you created. When you check the data model you will see 4 important objects

*

*ContentVersion (version of your document)

*ContentDocument (actual record of document it has a link to latest version) (created automatically when you insert contentversion)

*ContentWorkspace (Libraries)

*ContentWorkspaceDoc (Junction between libraries and ContentDocument) (created when you publish your content to a library)

So as you can see,
Contentdocument is your actual record, you can have multiple versions linked to contentdocument(contentversion - in your code you create only first version).
Contentdocument also is your relation to libraries behind the scene.
last but not least, on contenversion object there is a firstpublishlocationID (this field can be filled with multiple objects including libraries(contentworkspace) and users).

A: I found from document :

FirstPublishLocationId is id of the location where the version was first published. If the version is first published into a user's personal library or My Files, the field will contain the ID of the user who owns the personal library or My Files. In Lightning Experience, if the first version is published into a public library, the field will contain the ID of that library.
  Accepts all record IDs supported by ContentDocumentLink (anything a file can be attached to, like records and groups).
  Setting FirstPublishLocationId allows you to create a file and share it with an initial record/group in a single transaction, and have the option to create more links to share the file with other records or groups later. When a file is created, it's automatically linked to the record, and PublishStatus will change to Public from Pending/Personal.
  This field is only set the first time a version is published via the API. FirstPublishLocationId can't be set to another ID when a new content version is inserted.

In my case, I set FirstPublishLocationId  = userinfo.getUserId() instead of another content version ownerid, and error disappears.


text:
Q: How to correctly set up the time element markup for a line with a duration, day, date and time I am somehow confused how to properly markup the following example:
The course takes 2 days
from Sunday, 12.06.2014 9:00-18:00
to Monday, 13.06.2014 9:00-14:00

I came up with the following but i am uncertain if that is the correct proper way:

The course takes <time datetime="P 2 D">2 days</time>

 from <time datetime="2014-06-12">Sunday, 12.06.2014 </time><time datetime="2014-06-12T9:00+1:00">9:00</time>-<time datetime="2014-06-12T18:00+1:00">18:00</time>

 to <time datetime="2014-06-13">Monday, 13.06.2014 </time><time datetime="2014-06-13T9:00+1:00">9:00</time>-<time datetime="2014-06-13T14:00+1:00">14:00</time>

A:
The time element represents its contents, along with a machine-readable form of those contents in the datetime attribute. The kind of content is limited to various kinds of dates, times, time-zone offsets, and durations.
The time element

Semantically your markup is ok.
However, there are few issues with datetime attribute:

*

*Remove whitespaces from duration string: P 2 D --> P2D.

*An hour in time string and time-zone offset string must consist of 2 digits: 2014-06-12T9:00+1:00 --> 2014-06-12T09:00+01:00.

After fix:

The course takes <time datetime="P2D">2 days</time>

 from <time datetime="2014-06-12">Sunday, 12.06.2014 </time><time datetime="2014-06-12T09:00+01:00">9:00</time>-<time datetime="2014-06-12T18:00+01:00">18:00</time>

 to <time datetime="2014-06-13">Monday, 13.06.2014 </time><time datetime="2014-06-13T09:00+01:00">9:00</time>-<time datetime="2014-06-13T14:00+01:00">14:00</time>

redpajama_set_name: RedPajamaStackExchange


text:
Q: GZIP IIS caused images to dissapear from virtual path After I've configured GZIP on IIS 6 the web site was loaded very fast but the problem is that some images that are located in a virtual folder inside the IIS couldn't be viewed. even if the user writes the exact link to the image, the link doesn't work for him. I've removed GZIP and the images are working again. Has anyone ever configured GZIP and had problems like these?
Thanks


text:
Q: Взаимодействие двух программ по сети через многоадресное вещание Нужно передать текстовую строку из одной программы в другую через многоадресное вещание (насколько я правильно понимаю для этого используются адреса 224.0.0.0 и выше).
Код взят отсюда https://github.com/bluejekyll/multicast-example/blob/master/src/lib.rs только сильно урезан, что бы передать суть проблемы
Программа отправитель:
extern crate socket2;
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket};
use socket2::{Domain, Protocol, SockAddr, Socket, Type};

fn main() {

let socket = Socket::new(
    Domain::ipv4(),
    Type::dgram(),
    Some(Protocol::udp())
);

match socket {
    Result::Ok(sckt) => {
        sckt.set_multicast_if_v4(&Ipv4Addr::new(0, 0, 0, 0));
        sckt.bind(&SockAddr::from(SocketAddr::new(
            Ipv4Addr::new(0, 0, 0, 0).into(),
            7645,
        )));
        let udpsock=sckt.into_udp_socket();

        let message = b"Hello fromgiop client!";
        let socketaddr = SocketAddr::new(
            IpAddr::V4(Ipv4Addr::new(224,0,0,123)),
            7645
        );
        udpsock.send_to(message, &socketaddr).expect("could not send_to!");
    }
    Result::Err(err) =>panic!("called `Result::unwrap()` on an `Err` value: {:?}", err),
};
}

Программа получатель:
extern crate socket2;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket};
use socket2::{Domain, Protocol, SockAddr, Socket, Type};

 fn main() {
 let socket = Socket::new(
    Domain::ipv4(),
    Type::dgram(),
    Some(Protocol::udp())
);

match socket {
    Result::Ok(sckt) => {
        sckt.join_multicast_v4(
            &Ipv4Addr::new(224, 0, 0, 123),
            &Ipv4Addr::new(0, 0, 0, 0)
        );
        let addrbind=SocketAddr::new(
            Ipv4Addr::new(0, 0, 0, 0).into(),
            7645
        );
        sckt.bind(&socket2::SockAddr::from(addrbind));
        let udpsock=sckt.into_udp_socket();

        let mut buf = [0u8; 64];
        match udpsock.recv_from(&mut buf) {
            Ok((len, remote_addr)) => {
                let data = &buf[..len];
                println!(
                    "got data: {} from: {}",
                    String::from_utf8_lossy(data),
                    remote_addr
                );
            }
            Err(err) => {
                println!("{}:server: got an error: ", err);
            }
        }
    }
    Result::Err(err) =>panic!("called `Result::unwrap()` on an `Err` value: {:?}", err),
};
}

Это работает, если и отправитель и получатель запускаются на одном компьютере. Если запускать на разных компьютерах (компьютеры подключены к одной сети и находятся рядом), тогда не работает. Что нужно изменить?


text:
Q: Angular 9: Http POST comes empty I am not getting response from my backend and dont know what to do.
This is my request:
   httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json'
        // Authorization: 'my-auth-token'
      })
    };

getServiceById(request: string): Observable < any > {
      const url = this.endpoint + '/GetById';
      return this.http.post<Service>(url, request, this.httpOptions).pipe(
          retry(3),
          catchError(this.handleError)
        );
    }

Used on component like this:
  getServiceById(id: string) {
    this.httpService.getServiceById(id).subscribe((resp: any) => {
      this.service = resp;
      console.log('getServiceById: ', this.service);
    });
  }

The request works

The parameters are well

But the response comes empty

This is not a backend problem, i already tested and work well. Maybe im doing something bad on angular's request.


text:
Q: How do you output preprocessed data from a pipeline as objects? In many sklearn pipeline examples, I see people using another pipeline to pipe the preprocessing pipeline to some linear regression model. Is it possible to just output the preprocessed data from a pipeline so I can feed it into my flaml baseline code:
automl.fit(X_train=pp_training_data, y_train=pp_training_labels, **automl_settings)

Here is what I want my preprocessing pipeline code  to look and act like (I know this doesn't work):
def diamond_preprocess(data_dir):
    data = pd.read_csv(data_dir)
    cleaned_data = data.drop(['id', 'depth_percent'], axis=1)  # Features I don't want

    x = cleaned_data.drop(['price'], axis=1)  # Train data
    y = cleaned_data['price']  # Label data

    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

    numerical_features = x_train.select_dtypes(include=['int64', 'float64']).columns
    categorical_features = x_train.select_dtypes(include=['object']).columns

    numerical_transformer = Pipeline(steps=[
        ('imputer', SimpleImputer(strategy='median')),  # Fill in missing data with median
        ('scaler', StandardScaler())  # Scale data
    ])

    categorical_transformer = Pipeline(steps=[
        ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),  # Fill in missing data with 'missing'
        ('onehot', OneHotEncoder(handle_unknown='ignore'))  # One hot encode categorical data
    ])

    preprocessor_pipeline = ColumnTransformer(
        transformers=[
            ('num', numerical_transformer, numerical_features),
            ('cat', categorical_transformer, categorical_features)
        ])

    pp_training_data, pp_training_label = preprocessor_pipeline

    return pp_training_data, pp_training_label

A: You can apply the pipeline to the feature matrix only, without an estimator in the final step. See the code below for an example.
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split

# generate the data
data = pd.DataFrame({
    'y':  [1, 2, 3, 4, 5],
    'x1': [6, 7, 8, np.nan, np.nan],
    'x2': [9, 10, 11, np.nan, np.nan],
    'x3': ['a', 'b', 'c', np.nan, np.nan],
    'x4': [np.nan, np.nan, 'd', 'e', 'f']
})

# extract the features and target
x = data.drop(labels=['y'], axis=1)
y = data['y']

# split the data
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)

# map the features to the corresponding types (numerical or categorical)
numerical_features = x_train.select_dtypes(include=['int64', 'float64']).columns.tolist()
categorical_features = x_train.select_dtypes(include=['object']).columns.tolist()

# define the numerical features pipeline
numerical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())
])

# define the categorical features pipeline
categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

# define the overall pipeline
preprocessor_pipeline = ColumnTransformer(transformers=[
    ('num', numerical_transformer, numerical_features),
    ('cat', categorical_transformer, categorical_features)
])

# fit the pipeline to the training data
preprocessor_pipeline.fit(x_train)

# apply the pipeline to the training and test data
x_train_ = preprocessor_pipeline.transform(x_train)
x_test_ = preprocessor_pipeline.transform(x_test)


text:
Q: Custom UIView; do stuff when view's size is below certain trash-hold I have a custom view that I add dynamically to another (image)view that is within a scrollview. Therefor the image size will vary based upon the (initial) zoomscale of the scrollView.
So, basicly I want to set some properties and constraints when thsi view has been added to the (image)View. I thought this could be handled on didMoveToSuperView(), but frame and bounds are always 0??
How to solve this?
My custom View:
//MARK: - Properties
    private var annotation: Annotation!

    private var pinImageView = UIImageView()
    private var completedImageView = UIImageView()
    private var arrowImageView = UIImageView()
    private var pinTitleLabel = ProjectTitleLabel(withTextAlignment: .center, andFont: UIFont.preferredFont(forTextStyle: .callout), andColor: .label)

    //MARK: - Init
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required convenience init(with annotation: Annotation) {
        self.init(frame: .zero)
        self.annotation = annotation
        configure()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - Configure view
    private func configure() {
        (...)
    }

    override func didMoveToSuperview() {
        print("HERE: \(self.frame.height)", bounds.height, intrinsicContentSize)
        //Compensate for when the pin view becomes really small (on very low res images)
        if self.bounds.height <= 40 {
            pinTitleLabel.minimumScaleFactor = 0.45
            pinTitleLabel.font = UIFont.preferredFont(forTextStyle: .caption1)
            pinTitleLabel.heightAnchor.constraint(equalToConstant: 12).isActive = true
            print("SMALL")
        } else {
            pinTitleLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
            print("NORMAL")
        }
    }
}

and the code that adds this view:
    var annotation: Annotation? {
        didSet {
            //remove any previous pin
            mapImageLocationPin?.removeFromSuperview()

            if let location = annotation?.location {
                //Activate the corresponding Map Image and update picker
                selectedMapImage = location.map
                mapImagePickerView.selectRow(mapImagesController.getRowFor(location.map), inComponent: 0, animated: true)

                //Instantiate new Pin with annotation
                mapImageLocationPin = MapImageLocationPin(with: annotation!)
                mapImageView.addSubview(mapImageLocationPin!)

                //Desired height and width
                let desiredWidth: CGFloat = 160
                let desiredHeight: CGFloat = 80

                //compensate for scrollView zoomscale, but never bigger than desired width & height!
                let width = min(desiredWidth, desiredWidth / mapImageScrollView.minimumZoomScale)
                let height = min(desiredHeight, desiredHeight / mapImageScrollView.minimumZoomScale)
                print("w: \(width) x h: \(height)")

                //center the pin image horizontal on location
                let y = location.coordinateY
                let x = location.coordinateX - (width / 2)

                //position (frame) the pin
                mapImageLocationPin?.frame = CGRect(x: x, y: y, width: width, height: height)
            }
        }
    }


text:
Q: Pipe output from process substitution to variable I have very complicated set of commands:
command | ... | ... | tee >(grep -c '[^3]$') >(grep -c '[^35]$') 1>/dev/null

I don't want to have a temporary file to save up output, as it is pretty huge. I tried doing >(grep -c '[^3]$' | read variable) and >(grep -c '[^3]$' | read variable2) but I guess bit doesn't work because of process substitution's sub-shell invocation.
What can I do to pipe output directly to multiple variables? Is it even possible?
Right now I have this workaround:
var=$(command ... | ... | ... | tee >(grep -c '[^3]$') >(grep -c '[^35]$') 1>/dev/null)
var1=$(tail -1 <<< $var)
var2=$(head -1 <<< $var)

but I think it is clumsy and doesn't look nice. I am aware I can grep into another file but I don't like it either.
Thanks in advance.

A: Use awk, instead of tee-ing to two grep process substitutions.  For example:
command | ... | ... | awk '
     /[^3]$/  { c1++; next };
     /[^35]$/ { c2++; next };
     END { print c1, c2 > counts.txt }'

read var1 var2 < counts.txt
rm counts.txt

If you don't want to use a temporary file, you could do it like this:
read var1 var2 < <(command | ... | ... | awk '
         /[^3]$/  { c1++; next };
         /[^35]$/ { c2++; next };
         END { print c1, c2 }')

A: Firstly, you're sending standard output in your command chain to /dev/null, so youre assignation will likely be assigning a null value.  Remove that.  It looks like you're trying to capture only the first and last line of the output; this can be tricky to do in a one-liner but awk should be able to handle it:
var="$(command ... | [...] | tee [...] | awk 'NR==1{print $0} END { print $0}')"

However, pipes are simple creatures.  They have one input and one output.  You can't (easily) use pipes to send data into multiple places.  The closest you'll be able to get would be to use named pipes, which essentially are the temporary files you're trying to avoid (technically not true; FIFO queues are different from files, but I am simplifying).


text:
Q: RSpec undefined method "errors_on" I have the following model that I want to test with RSpec:
class Language < ActiveRecord::Base
  has_and_belongs_to_many :dvds
  validates :title, presence: true, uniqueness: { case_sensitive: false }
end

language_spec.rb
describe Language do
  describe 'title validation' do
    context 'title is present' do
      before(:each) do
        @lang = Language.new(title: 'English')
      end

      it 'is valid with present title' do
        expect(@lang).to have_exactly(0).errors_on(:title)
      end
    end

    context 'title is not present' do
      before(:each) do
        @lang = Language.create
      end

      it 'has an error on title attribute' do
        expect(@lang).to have_exactly(1).errors_on(:title)
      end

    end
  end
end

Unfortunately I'm getting test failures:

Failures:
1) Language title validation title is present is valid with present
  title
       Failure/Error: expect(@lang).to have_exactly(0).errors_on(:title)
       NoMethodError:
         undefined method errors_on' for #<Language:0xaa40e98>
       # ./spec/models/language_spec.rb:9:inblock (4 levels) in '
2) Language title validation title is not present has an error on
  title attribute
       Failure/Error: expect(@lang).to have_exactly(1).errors_on(:title)
       NoMethodError:
         undefined method errors_on' for #<Language id: nil, title: nil, created_at: nil, updated_at: nil>
       # ./spec/models/language_spec.rb:19:inblock (4 levels) in '

Gemfile
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring',        group: :development

# Pagination plugin
gem 'will_paginate', '~> 3.0'

# Testing
group :development, :test do
  gem "rspec-rails", "~> 3.0.1"
  gem "factory_girl_rails", "~> 4.4.1"
end

group :test do
  gem "faker", "~> 1.3.0"
  gem "capybara", "~> 2.3.0"
  gem "database_cleaner", "~> 1.3.0"
  gem "launchy", "~> 2.4.2"
  gem "selenium-webdriver", "~> 2.42.0"
end

Any ideas why I'm getting undefined method "errors_on"?

A: The errors_on matcher moved to the rspec-collection_matchers gem, so adding that to your Gemfile would fix the error.
If you wanted to move away from non-core syntax, you could do
describe Language do
  describe 'title validation' do
    context 'title is present' do
      before(:each) do
        @lang = Language.new(title: 'English')
      end

      it 'is valid with present title' do
        expect(@lang.errors[:title]).to be_empty
      end
    end

    context 'title is not present' do
      before(:each) do
        @lang = Language.create
      end

      it 'has an error on title attribute' do
        expect(@lang.errors.added?(:title, :blank)).to be_true
      end
    end

  end
end

(have_exactly and related matchers have also moved to rspec-collection_matchers.)

A: Try to set type option:
describe Language, type: :model do

Or use infer_spec_type_from_file_location! (See here)
RSpec.configure do |config|
  config.infer_spec_type_from_file_location!
end


text:
Q: ClassNotFound exception in enums in dynamic moxy I am using EclipseLink dynamic moxy for jaxb. When I try to set an enum value, I get a ClassNotFound exception. Can anyone point out what I am doing wrong?
Schema:

<xs:element name="customer" type="customerType"> </xs:element>

 <xs:complexType name="customerType">
    <xs:sequence>
        <xs:element name="number" type="numberEnum"/>
        <xs:element name="name" type="xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:simpleType name="numberEnum">
    <xs:restriction base="xs:string">
        <xs:enumeration value="1"/>
        <xs:enumeration value="2"/>
        <xs:enumeration value="3"/>
    </xs:restriction>
</xs:simpleType>

Java code:
    package uic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.xml.bind.JAXBException;

import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;

public class test{

DynamicJAXBContext context;

test() {
    try{
        context = DynamicJAXBContextFactory.createContextFromXSD(new FileInputStream(new File("sample/NewXMLSchema1.xsd")), null, null, null);
    } catch(JAXBException e) {
        e.printStackTrace();
    } catch(FileNotFoundException e){
        e.printStackTrace();
    }

    DynamicEntity root = context.newDynamicEntity("CustomerType");

    root.set("name", "tom");

    Object enumValue = null;
    try {
        enumValue = context.getEnumConstant("uic.NumberEnum", "2");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    root.set("Number", enumValue);
}

public static void main(String args[]) {
    new test();
}
}

Am i going wrong when I create the context using createContextFromXSD()? I followed this example: EclipseLink dynamic MOXy accessing enum values
I don't have a problem when I am accessing other JAXB generated classes. The problem is only for the enum classes. Are they placed in a different package from the other generated classes or something?
Edit: In the main program, I receive an xml schema file as the input. I use an xsom parser to retrieve the element and type declarations, and then marshal using JAXB generated classes, to get the output, an XML file. So, any changes I need to do to the schema will have to be done dynamically.
Thanks.

A: I am a developer on the EclipseLink product and have been looking at your issue.  A NumberEnum class was not generated because the enumeration values are all numbers, which is invalid for a Java enum.  If you were to run your schema through the xjc command-line tool, you would also see that no enum class was generated.
One solution would be to change your enum values to ONE, TWO, THREE, if you have the flexibility of changing your schema.
Otherwise, the standard way to get around this would be with the use of a JAXB bindings file, to customize the enum values:
    <jxb:bindings
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
        version="2.1">
        <jxb:bindings schemaLocation="schema.xsd">

            <jxb:bindings node="//xs:simpleType[@name='numberEnum']/xs:restriction/xs:enumeration[@value='1']">
                <jxb:typesafeEnumMember name="ONE"/>
            </jxb:bindings>

            <jxb:bindings node="//xs:simpleType[@name='numberEnum']/xs:restriction/xs:enumeration[@value='2']">
                <jxb:typesafeEnumMember name="TWO"/>
            </jxb:bindings>

            <jxb:bindings node="//xs:simpleType[@name='numberEnum']/xs:restriction/xs:enumeration[@value='3']">
                <jxb:typesafeEnumMember name="THREE"/>
            </jxb:bindings>

        </jxb:bindings>
    </jxb:bindings>

However, we currently have a bug in EclipseLink Dynamic JAXB, and this enum customization is not being taken into account.  We are working on this for our 2.4.1 release, you can track the progress of this bug here:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=383575
Thanks,
Rick


text:
Q: Is this person Jessica Jones? In "Blessing of Many Fractures," Joy mentions hiring a private investigator to follow her board members:

JOY: I hired a private investigator a while ago to start digging. She was worth every penny…when
  she was sober.

This certainly sounds similar to Jessica Jones (PI, female, drinks), but could also match a bunch of other PIs (not everything in the MCU needs to be an easter egg).
Is there any definite evidence (interviews, etc) that this is a reference to Jessica Jones?

A: Yes. It was a subtle reference, but it was her. There is no point in mentioning gender and the alcohol issues unless it was an Easter Egg. Joy could have just said PI and been done with it.


text:
Q: Avoid duplicated key error when saving entity I'm starting with Play! Framework 2 and I'm facing an issue when trying to save an entity to the database (Postgres).
I've created a Model where there is a @Column(unique = true) annotation on name attribute. So, there must be two unique attributes when saving: the ID, which is always correctly generated and the name, which is an input provided by the user.
When I check for errors in Controller (filledForm.hasErrors()), there are no errors, because (I guess) it does not check for duplicated attributes, but just for form errors.
Then it goes to the Model and tries to save the object thebean.save();. And then it "crashes" and shows an error in the browser.
My question is: since the save() method returns void, how can I catch this error and know what kind of error it is (to warn the user)?
Thanks

A: Alternative solution is to manualy check constraint.
There is a entity method called validate() (in models). It's automatically called when form is validating.
So:
public List<ValidationError> validate() {
    List<ValidationError> errors = new ArrayList<>();

    if(YouModel.find.where().eq("name", name).ne("entity_id", entity_id).findRowCount() != 0){
        errors.add(new ValidationError("name", "error.yourModel.name.unique"));
        return errors;
    }

    return null;
}

error.yourModel.name.unique is a custom constant from /conf/messages file. You should create it.


text:
Q: Sorcery Log_out not working Here is my route-
    get 'login' => 'sessions#new'
    post 'login' => 'sessions#create'
    delete 'logout' => 'sessions#destroy'

Here is my controller action-
  def destroy
    logout
    redirect_to(login_url, notice: 'You have Succesfully Logged out.')
  end

Here is my view-

      <%if current_user %>
      <%= link_to logout_path, method: :delete do %>
       Log out
      <%end%>
      <%end%>

The problem I am having is: whenever I logout it says-

No route matches [GET] "/logout".

I tried with GET, I tried with DELETE and POST, nothing works.
Routes
login_path  GET     /login(.:format)    sessions#new
            POST    /login(.:format)    sessions#create
logout_path DELETE  /logout(.:format)   sessions#destroy

A: Make sure you have these in your app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs


text:
Q: Counting multiple columns & groups from one UNION ALL query I am attempting to get counts of items in multiple columns in a union all-ed query.
I have a MySQL database of trips taken, with location data for origin and destination for each trip. The columns are as such:

o_continent
o_country
o_state
o_city
d_continent
d_country
d_state
d_city
tripdate

North America
United States
California
San Diego
North America
United States
Arizona
Phoenix
2020-10-01

North America
United States
California
Los Angeles
North America
United States
California
Santa Rosa
2020-04-03

North America
United States
California
Los Angeles
North America
United States
Washington
Spokane
2020-03-01

North America
United States
Oregon
Portland
North America
Canada
Alberta
Calgary
2020-01-22

North America
Canada
Alberta
Edmonton
North America
United States
California
Los Angeles
2020-04-01

I am merging the origins and the destinations using UNION ALL, as such:
SELECT o__continent as continent, o__country as country, o__state_name as state, o__city_name as city, o_ AS code
FROM db.trips
WHERE year(tripdate) = 2020
UNION ALL
SELECT d__continent as continent, d__country as country, d__state_name as state, d__city_name as city, d_ AS code
FROM db.trips
WHERE year(tripdate) = 2020

This produces a table that looks like this:

continent
country
state
city

North America
Canada
Alberta
Calgary

North America
Canada
Alberta
Edmonton

North America
United States
Arizona
Phoenix

North America
United States
California
Los Angeles

North America
United States
California
Los Angeles

North America
United States
California
Los Angeles

North America
United States
California
San Diego

North America
United States
California
Santa Rosa

North America
United States
Oregon
Portland

North America
United States
Washington
Spokane

I am seeking out how I might be able to group these together (obviously traditionally you would use GROUP BY continent, country, state, city), but also to count the instances of each column in separate columns. The ideal final result would look something like this (note: the Los Angeles entries are grouped):

continent
country
state
city
continent_count
country_count
state_count
city_count

North America
Canada
Alberta
Calgary
10
2
2
1

North America
Canada
Alberta
Edmonton
10
2
2
1

North America
United States
Arizona
Phoenix
10
8
1
1

North America
United States
California
Los Angeles
10
8
5
3

North America
United States
California
San Diego
10
8
5
1

North America
United States
California
Santa Rosa
10
8
5
1

North America
United States
Oregon
Portland
10
8
1
1

North America
United States
Washington
Spokane
10
8
1
1

I have been sifting for several days through other potential answers to this question on StackOverflow with little luck. Ideally I would not query the db.trips database over and over, as it is large. Is there a way to do this without losing too much efficiency?
Any help offered is most kindly and greatly appreciated.

A: Given that you said you are stuck on MySQL 5.7, your best bet is going to be a normal GROUP BY and then post processing the counts in your programming language of choice -
SELECT *, COUNT(*) AS l_count
FROM (
(
    SELECT o_continent as continent, o_country as country, o_state as state, o_city as city
    FROM trips
    WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31'
 ) UNION ALL (
    SELECT d_continent as continent, d_country as country, d_state as state, d_city as city
    FROM trips
    WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31'
)
) `locations`
GROUP BY continent, country, state, city
ORDER BY continent ASC, country ASC, state ASC, city ASC;

But if you want to build the final result set in SQL there are a few different approaches and this performed best with my test dataset -
SELECT `locations`.*,
    `continents`.`count` AS continent_count,
    `countries`.`count` AS country_count,
    `states`.`count` AS state_count,
    COUNT(*) AS city_count
FROM (
(
    SELECT o_continent as continent, o_country as country, o_state as state, o_city as city
    FROM trips
    WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31'
 ) UNION ALL (
    SELECT d_continent as continent, d_country as country, d_state as state, d_city as city
    FROM trips
    WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31'
)
) `locations`
INNER JOIN (
    -- DERIVED TABLE FOR COUNT OF CONTINENTS
    SELECT continent, SUM(cnt) AS `count` FROM (
        SELECT o_continent AS continent, COUNT(*) AS cnt FROM trips WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY continent
        UNION ALL
        SELECT d_continent AS continent, COUNT(*) AS cnt FROM trips WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY continent
    ) tmp
    GROUP BY continent
) `continents` ON `locations`.`continent` = `continents`.`continent`

INNER JOIN (
    -- DERIVED TABLE FOR COUNT OF COUNTRIES
    SELECT country, SUM(cnt) AS `count` FROM (
        SELECT o_country AS country, COUNT(*) AS cnt FROM trips WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY country
        UNION ALL
        SELECT d_country AS country, COUNT(*) AS cnt FROM trips WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY country
    ) tmp
    GROUP BY country
) `countries` ON `locations`.`country` = `countries`.`country`

INNER JOIN (
    -- DERIVED TABLE FOR COUNT OF STATES
    SELECT state, SUM(cnt) AS `count` FROM (
        SELECT o_state AS state, COUNT(*) AS cnt FROM trips WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY state
        UNION ALL
        SELECT d_state AS state, COUNT(*) AS cnt FROM trips WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY state
    ) tmp
    GROUP BY state
) `states` ON `locations`.`state` = `states`.`state`

GROUP BY `locations`.`continent`, `locations`.`country`, `locations`.`state`, `locations`.`city`
ORDER BY `locations`.`continent` ASC, `locations`.`country` ASC, `locations`.`state` ASC, `locations`.`city` ASC;

If you are running MySQL > 8.0 then using window functions is definitely the easiest and most performant solution -
SELECT *,
    SUM(COUNT(*)) OVER (PARTITION BY continent) AS continent_count,
    SUM(COUNT(*)) OVER (PARTITION BY country) AS country_count,
    SUM(COUNT(*)) OVER (PARTITION BY state) AS state_count,
    COUNT(*) AS city_count
FROM (
(
    SELECT o_continent as continent, o_country as country, o_state as state, o_city as city
    FROM trips
    WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31'
 ) UNION ALL (
    SELECT d_continent as continent, d_country as country, d_state as state, d_city as city
    FROM trips
    WHERE tripdate BETWEEN '2020-01-01' AND '2020-12-31'
)
) `locations`
GROUP BY continent, country, state, city
ORDER BY continent ASC, country ASC, state ASC, city ASC;


text:
Q: How to check if Meteor.call() fails when server connection is down? When the Meteor server connection is lost, how can I verify that Meteor.call() failed? Meteor.call() doesn't return any value. Basically Ctrl+Z in the Meteor shell when your app is running, then do something in the app that triggers a Meteor.call i.e. adding a new blog post:
Meteor.call('createPhrase', phrase, function(error) {
  console.log("This NEVER gets called if server is down.");

  if (error) {
     throwError(error.reason);
  }
});

I tried using Session vars, but the reactivity screws it up, i.e. the code below will trigger an error in my template handler (that get's flashed to the browser quickly) and as soon as isMyError is set to true, then when the Meteor.call is successful the error goes away as per isMyError = false, but this looks really sloppy.
Session.set("isMyError", true);

Meteor.call('createPhrase', phrase, function(error) {
   console.log("This NEVER gets called if server is down.");

   Session.set("isMyError", false);

    if (error) {
        throwError(error.reason);
    }
});

Template.index.isMeteorStatus = function () {

   myClientStatus = Meteor.status();

   if ( (myClientStatus.connected === false) || (Session.get("isMyError") === true) ) {
     return false;
   } else {
     return true;
   }
};

A: Meteor's calls are generally entered into a queue that are sent to the server in the order that they are called. If there is no connection they stay in the queue until the server is connected once more.
This is the reason nothing is returned because Meteor hopes that it can reconnect then send the call and when it does it does eventually return a result then.
If you want to validate whether the server is connected at the point of the call it's best to check Meteor.status().connected (which is reactive) and only run Meteor.call if it is else throw an error
if(Meteor.status().connected)
    Meteor.call(....
else throwError("Error - not connected");

You could also use navigator.onLine to check whether the network is connected.
The reason you would experience a 60 second delay with Meteor.status().connected on the true status of whether meteor is connected or not is there isn't really a way for a browser to check if its connected or not.
Meteor sends a periodic heartbeat, a 'h' on the websocket/long polling wire to check it is connected. Once it realizes it didn't get a heartbeat on the other end it marks the connection disconnected.
However, it also marks it as disconnected if a Meteor.call or some data is sent through and the socket isn't able to send any data. If you use a Meteor.call beforehand to Meteor.status().connected it would realize much sooner that it is disconnected. I'm not sure it would realize it immediately that you can use them one line after the next, but you could use a Meteor.setTimeout after a second or two to fire the call.
Attempt to succeed:
Meteor is designed very well to attempt to succeed. Instead of 'attempting to fail' with an error stating the network is not available its better to try and queue everything up until the connection is back.
The best thing to do would be to avoid telling the user the network is down because usually they would know this. The queued tasks ensure the userflow would be unchanged as soon as the connection is back.
So it would be better to work with the queues that are built into the reconnection process rather than to avoid them.


text:
Q: codenameone and Opentok native interface I am trying to implement step 5 of : https://tokbox.com/developer/tutorials/android/basic-video-chat/#connect
I am stuck at point 4 and 5.
I don't know how to implement them (I am a new user of codename one).
I don't know if I have to use a lifecyclelistener (and if so how?, because I do not find documentation) and if not what should I do?
Thank you for your help,
Amina

A: The sample just uses the activity since it works top to bottom but I doubt you need that. My guess is that you can probably create your own class and instance and instead of using:
mSession.setSessionListener(this);

You can probably just use:
mSession.setSessionListener(myObject);

Where myObject would just be a class you create and place next to the regular native class that implements this interface.
Another point of interest is the onCreate or other callbacks you might need. onCreate can probably be mapped to our lifecycle methods thru a native interface but you can also use addLifecycleListener which should work roughly like this:
com.codename1.impl.android.AndroidNativeUtil.addLifecycleListener(new LifecycleListener() {
  public void onCreate(android.os.Bundle savedInstanceState) {
     // ... on create code
  }
  public void onResume() {}
  public void onPause() {}
  public void onDestroy() {}
  public void onSaveInstanceState(android.os.Bundle b) {}
  public void onLowMemory() {}
});


text:
Q: How can i append pure string into div? So this is the requirement. The user can insert tags inside text_field input.
and i got the data from the db like this.
var input = "test
" ;

I ONLY want to append this to PURE string. not tags
but if i append it runs like a tag.
the result i want is just printing
test

as a pure string.
Any good solution?
html,

javascript,
$(function(){
            var input = "test
" ;
            $("#i_want_only_string").append(input);
});

DEMO

A: Try appending a TextNode - create it using document.createTextNode()
$(function () {
    var input = "test
";
    $("#i_want_only_string").append(document.createTextNode(input));
});

Demo: Fiddle

As @BillCriswell noted below if the container #i_want_only_string is empty, you can use .text() like
$(function () {
    var input = "test
";
    $("#i_want_only_string").text(input);
});

Demo: Fiddle

A: You can append your container with the contents of a new tag that has your input text as its innerText
$(function () {
    var input = "test
";
    $("#i_want_only_string").append($('').text(input).contents());
});

DEMO


text:
Q: How to Send mail using amazon web services from android application I found some information in amazon webservices for sending mail from android application.It contains the following code.How to use this code in my application.Please help me.
    AWSCredentials credentials = new BasicAWSCredentials( PropertyLoader.getInstance().getAccessKey(), PropertyLoader.getInstance().getSecretKey() );
    AmazonSimpleEmailServiceClient sesClient = new AmazonSimpleEmailServiceClient(credentials);
    String subjectText = "Feedback from " + nameField.getText();
    Content subjectContent = new Content(subjectText);
    String bodyText = "Rating: " + ratingBar.getRating() + "\nComments\n" + commentsField.getText();
    Body messageBody = new Body(new Content(bodyText));
    Message feedbackMessage = new Message(subjectContent,messageBody);
    String email = PropertyLoader.getInstance().getVerifiedEmail();
    Destination destination = new Destination().withToAddresses(email);
    SendEmailRequest request = new SendEmailRequest(email,destination,feedbackMessage);
    SendEmailResult result = clientManager.ses().sendEmail(request);


text:
Q: How does javascript evaluate arguments? I wrote a simple javascript function to display a progressbar with the help of JQuery ProgressBar(check here).
The progressBar function can be set to display different background images with different values. I want to display values in [0, MAX0.3] as red, (MAX0.3, MAX0.7] as orange, and (MAX0.7, MAX] as green. So I write a helper function as follows:
function setBar(bar, cur, total) {
    var v1 = parseInt(total * 0.3);
    var v2 = parseInt(total * 0.7);

    // if I run alert(v1) and alert(v2) here, the values are all right.

    bar.progressBar(cur, {
        max: total,
        textFormat: 'fraction',
        boxImage: '/img/pbar/progressbar.gif',
        barImage: {
            0:  '/img/pbar/progressbg_red.gif',
            v1: '/img/pbar/progressbg_orange.gif',
            v2: '/img/pbar/progressbg_green.gif'
        }
    });
}

The argument cur is the current value while total is the MAX value of the progress bar. The function doesn't seem to work, but when I replace "v1:" and "v2:" with actual values like 50 and 120, the function works well. And I have also checked the value of v1 and v2 before calling bar.progressBar, they are all right.
So the problem seems that I cannot pass a variable instead of a constant to the function bar.progressBar, I think it maybe have relations with javascript argument evaluation order, is there any fix to this problem?

A: try building the object before you pass it:
var barImageObj = {};
barImageObj[0] = '/img/pbar/progressbg_red.gif';
barImageObj[v1] = '/img/pbar/progressbg_orange.gif';
barImageObj[v2] = '/img/pbar/progressbg_green.gif';

bar.progressBar(cur, {
    max: total,
    textFormat: 'fraction',
    boxImage: '/img/pbar/progressbar.gif',
    barImage: barImageObj
});

the problem is that javascript interperets {a:'foo'} and {'a':'foo'} as an object with the string key "a", not with whatever the value of the variable a happens to be

A: Your problem is in
barImage: {
            0:  '/img/pbar/progressbg_red.gif',
            v1: '/img/pbar/progressbg_orange.gif',
            v2: '/img/pbar/progressbg_green.gif'
        }

When using the object literal form, the element names are taken as literals, i.e the fact that v1 and v2 are variables has no effect, the object you created has elements 0, 'v1' and 'v2'.
To do what you want you need
barImage = { };

barImage[0] = '/img/pbar/progressbg_red.gif';
barImage[v1] = '/img/pbar/progressbg_orange.gif';
barImage[v2] = '/img/pbar/progressbg_green.gif';

A: the problem may be that v1 and v2 are float numbers rather than strings. You are
using them as keys on a javascript object.
Try converting them to integers and then to strings if that still doesn't work.


text:
Q: Entity framework savechanges() not working EF5, .Net4 I have the following code to update some inventory values...
private static void UpdateInventory(int prodId, int qty)
    {
        using (var context = new uStore7_1Entities())
        {
            //Get the catalogNo and ProductUnitID of the product passed in so we can find all identical products that might just be boxed differently
            var currProdItem = context.Products.Where(c => c.ProductID.Equals(prodId))
                                       .Select(c => new {c.CatalogNo, c.ProductUnitID}).FirstOrDefault();

            //Get the units per box factor for calculating total product ordered
            var prodIdAmount =
                context.ProductUnits.Where(pa => pa.ProductUnitID.Equals(currProdItem.ProductUnitID))
                       .Select(pa => pa.Amount)
                       .FirstOrDefault();

            //Calculate the total number of units for this item
            var prodUnits = qty*prodIdAmount;

            //Get the entire list of products with the specified catalog number excluding the product passed in
            var uStoreProducts =
                context.Products.Where(p => p.CatalogNo.Equals(currProdItem.CatalogNo) && !p.ProductID.Equals(prodId))
                       .Select(p => p.ProductID);

            //Loop through each product in the uStoreProductsList
            foreach (var uStoreProduct in uStoreProducts)
            {
                var currentProduct = uStoreProduct;

                //Get the current product's ProductUnitId to get the 'pieces' per "box"
                var currentUnitId =
                    context.Products.Where(u => u.ProductID.Equals(currentProduct))
                           .Select(u => u.ProductUnitID)
                           .FirstOrDefault();

                //Use the ProductUnitId to get the "Amount" from the ProductUnits table.
                var inventoryFactor =
                    context.ProductUnits.Where(i => i.ProductUnitID.Equals(currentUnitId))
                           .Select(i => i.Amount)
                           .FirstOrDefault();

                //Divide the quantity passed
                var qtyInUnits = prodUnits/inventoryFactor;

                var inventory =
                    context.ProductInventories.Where(pi => pi.ProductID.Equals(currentProduct))
                           .Select(pi => pi.InventoryQuantity)
                           .FirstOrDefault();

                /*var inventory = (from i in context.ProductInventories
                                where i.ProductID == currentProduct
                                select i).FirstOrDefault();
                */

                if (inventory != null)
                {
                    var newinv = inventory - qtyInUnits;
                    inventory = newinv;
                    //context.SaveChanges();
                }
            }
            context.SaveChanges();

        }

    }

The SaveChanges() does not seem to be updating anything.  I have debugged it and the inventory value gets changed to the value needed, but for some reason it isn't updating.  I've tried it inside the loop and outside the loop, both with no change. Any ideas?  What am I missing here?

A: Your code does not update anything. All you do is gather entities and assign calculated values in local variables. But you never actually change a property of one of your entities.
Note that selecting properties of your entities, storing them in variables and replacing the value of this variable does not work. You need to select the entity if you want to modify it.

A: Your problem is object replacement, rather than re-assignment. When "newinv" is created, it's detached from your context, whereas "inventory" is the attached object. When "newinv" is assigned to "inventory", then it loses the association with the context.
Try this:
    var prodInventory =
                   context.ProductInventories
                   .Where(pi => pi.ProductID.Equals(currentProduct))
                   .FirstOrDefault();

                if (prodInventory != null)
                {
                    var newinv = prodInventory.InventoryQuantity - qtyInUnits;
                    prodInventory.InventoryQuantity = newinv; // This updates the actual context object now.
                }


text:
Q: PHP Executing Program With Variables I am trying to run a script that saves a derived number using PHP. I've confirmed that this script works manually from the debian terminal when I execute this command, it saves a file with my number and echos

"file saved"

./number-code-gen "12345678-1234-123456"

I've confirmed that the script works to an extent by running it without parameters using this from PHP:
$output = exec("./number-code-gen", $output2);
print_r($output2);

It echos back:

"No Arguments. Please enter a number."

I've tried all of the following with and without quotes around the argument (works either way in terminal)
exec('./nfz_core "12345678-12345678-12345678"', $output2);
print_r($output2);

$output = shell_exec('./nfz_core "12345678-12345678-12345678"');
echo $output;

passthru('./number-code-gen 12345678-1234-123456',$rtn);
echo $rtn;

I don't get echos or errors for either of these, and my file isn't generated. Is there a specific thing I'm missing here?
Basically, I just want to run ./number-code-gen 12345678-1234-123456 from PHP, but it isn't working. I am running Debian and PHP version: 5.6.33


text:
Q: How to add an array of objects to parse.com db? I'm developing an application and need to add many items at a time.
How can I do that with node.js?
This is the npm module for parse.com but there is no method like
insertAll("Foo", [objs...], ...)

I don't want to insert single object every time.

A: Write a convenience function that interfaces between your application and parse.com. You will have to write the iteration code once (or debug mine)
var async = require('async');
var parseApp = require('node-parse-api').Parse;
var APP_ID = "";
var MASTER_KEY = "";
var parseApp = new Parse(APP_ID, MASTER_KEY);

function insertAll(class, objs, callback){
  // create an iterator function(obj,done) that will insert the object
  // with an appropriate group and call done() upon completion.

  var insertOne =
  ( function(class){
      return function(obj, done){
        parseApp.insert(class, obj, function (err, response) {
          if(err){  return done(err);  }
          // maybe do other stuff here before calling done?
          var res = JSON.parse(response);
          if(!res.objectId){  return done('No object id')  };
          done(null, res.objectId);
        });
      };
    } )(class);

  // async.map calls insertOne with each obj in objs. the callback is executed
  // once every iterator function has called back `done(null,data)` or any one
  // has called back `done(err)`. use async.mapLimit if throttling is needed

  async.map(objs, insertOne, function(err, mapOutput){
    // complete
    if(err){ return callback(err) };
    // no errors
    var objectIds = mapOutput;
    callback(null, objectIds);
  });
};

// Once you've written this and made the function accessible to your other code,
// you only need this outer interface.

insertAll('Foo', [{a:'b'}, {a:'d'}], function(err, ids){
  if(err){
    console.log('Error inserting all the Foos');
    console.log(err);
  } else {
    console.log('Success!);
  };
});


text:
Q: make sure to call FacebookSdk.sdkInitialize() although initialized This is my activity:
import com.apprikot.kooora.controller.interfaces.HasTwitter;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.twitter.sdk.android.core.identity.TwitterAuthClient;

public class SocialActivity extends BaseActivity implements HasTwitter {
    protected CallbackManager mCallbackManager;
    protected TwitterAuthClient mTwitterAuthClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        mCallbackManager = CallbackManager.Factory.create();
        mTwitterAuthClient = new TwitterAuthClient();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
        mTwitterAuthClient.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public TwitterAuthClient getTwitterAuthClient() {
        return mTwitterAuthClient;
    }
}

The simple solution that's not working with me, is to put the initialization before the setContentView, which is already done in my case.
This is the main activity manifest declaration (it extends the SocialActivity above):
<activity
    android:name=".controller.activities.MainActivity"
    android:clearTaskOnLaunch="true"
    android:configChanges="orientation|screenSize"
    android:label="@string/app_name"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"
    android:theme="@style/AppTheme"
    android:windowSoftInputMode="adjustPan"/>

Finally, this is the crash I'm getting:
java.lang.RuntimeException: Unable to resume activity {com.sikooora/com.facebook.FacebookActivity}: The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.\n\tat android.app.ActivityThread.performResumeActivity(ActivityThread.java:2853)\n\tat android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2882)\n\tat android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2314)\n\tat android.app.ActivityThread.access$700(ActivityThread.java:157)\n\tat android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)\n\tat android.os.Handler.dispatchMessage(Handler.java:99)\n\tat android.os.Looper.loop(Looper.java:176)\n\tat android.app.ActivityThread.main(ActivityThread.java:5317)\n\tat java.lang.reflect.Method.invokeNative(Native Method)\n\tat java.lang.reflect.Method.invoke(Method.java:511)\n\tat com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)\n\tat com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)\n\tat dalvik.system.NativeStart.main(Native Method)\nCaused by: The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.\n\tat com.facebook.internal.Validate.sdkInitialized(Validate.java:136)\n\tat com.facebook.FacebookSdk.getApplicationContext(FacebookSdk.java:427)\n\tat com.facebook.AccessTokenManager.getInstance(AccessTokenManager.java:84)\n\tat com.facebook.AccessToken.getCurrentAccessToken(AccessToken.java:144)\n\tat com.facebook.login.LoginClient.authorize(LoginClient.java:121)\n\tat com.facebook.login.LoginClient.startOrContinueAuth(LoginClient.java:108)\n\tat com.facebook.login.LoginFragment.onResume(LoginFragment.java:152)\n\tat android.support.v4.app.Fragment.performResume(Fragment.java:2020)\n\tat android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1107)\n\tat android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)\n\tat android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1234)\n\tat android.support.v4.app.FragmentManagerImpl.dispatchResume(FragmentManager.java:2056)\n\tat android.support.v4.app.FragmentController.dispatchResume(FragmentController.java:196)\n\tat android.support.v4.app.FragmentActivity.onResumeFragments(FragmentActivity.java:505)\n\tat android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:494)\n\tat android.app.Activity.performResume(Activity.java:5417)\n\tat android.app.ActivityThread.performResumeActivity(ActivityThread.java:2830)


text:
Q: Using tf.data.Dataset with Keras on a TPU I am training a model with Keras which constitutes of a Huggingface RoBERTa model as a backbone with a downstream task of span prediction and binary prediction for text.
I have been training the model regularly with datasets which are under 2 Gb in size, which has worked fine. The dataset has grown in size in recent weeks and now recently, it has gotten to around 2.3 Gb in size which makes it over the 2 Gb google protobuf hard limit. This makes it impossible to train the model with keras with numpy tensors without a generator on TPUs as tensorflow uses google protobuf to buffer the tensors for the TPUs, and trying to serve all the data without a generator fails. If I use a dataset under 2 Gb in size, everything works fine. TPUs don't support Keras generators yet, so I was looking into using the tf.data.Dataset api instead.
After seeing this question I adopted code from this gist trying to get this to work, resulting in the following code:
def tfdata_generator(x, y, is_training, batch_size=384):

    dataset = tf.data.Dataset.from_tensor_slices((x, y))

    if is_training:
        dataset = dataset.shuffle(1000)
    dataset = dataset.map(map_fn)
    dataset = dataset.batch(batch_size)
    dataset = dataset.repeat()
    dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)

    return dataset

The model is created and compiled for TPU use as before which has never caused any problems and then I create the generators and call the fit function:
train_gen = tfdata_generator(x_train, y_train, is_training=True)

model.fit(
  train_gen,
  steps_per_epoch=10000,
  epochs=1,
)

This results in the following error:
FetchOutputs node : not found [Op:AutoShardDataset]

edit: Colab with bare minimum code and a dummy dataset - unfortunately, b/c of Colab RAM restrictions, building a dummy dataset exceeding 2 Gb in size crashes the notebook. But still, displays code that runs and works on CPU/TPU with a smaller dataset.
This code does however work on a CPU. I can't find any further information on this error online and haven't been able to find more detailed information on how to use TPUs with Keras servicing training data using generators. Have looked into tfrecords a bit but also find documentation on TPUs missing. All help appreciated!

A: For numpy tensors, 2GB seams to a hard limit for TPU training (as of now).
I see 2 workarounds that you could use.

*

*Write your tf.data to a gs bucket as TFRecord/CSV using TFRecordWriter and let the TPU use training data from that bucket.

*Use tf.data service, for your input pipeline. It's a relatively new service that let's you run your data pipeline on separate workers. For details on how to run please see running_the_tfdata_service.


text:
Q: Android facebook sdk AccessToken.getCurrentAccessToken() returns null On application startup I show facebook login window using the following code.
LoginManager.getInstance().logInWithReadPermissions(activity,    Arrays.asList("public_profile"));

I got response onSuccess which is ok. AccessToken exists and Profile.getCurrentProfile() also returns valid profile. BUt after I shut down the application and open again AccessToken.getCurrentToken() returns null. Does anyone have the same problem? I can't understand what's going on.
I am using latest Facebook SDK. 4.x

A: I would say make sure the user hasn't revoked access to the app from their facebook settings. Accesstoken null basically means your app isn't authorized or you are calling logOut() somewhere else. You should go back to the login screen if this happens.

A: I Found the problem. FacebookSdk.sdkInitialize method was not in Application.onCreate method. I thought I had But it was at different place.
So ALWAYS call FacebookSdk.sdkInitialize method from onCreate method at the top after calling super.onCreate


text:
Q: Strange print behavior with time.sleep in python I was trying to create a progress-like thing by printing a dot every second on the same line. Something like "Fishing.....". This is what I used:
import time

print('Fishing', end='')
for i in range(5):
    time.sleep(1)
    print('.', end='')

But it waits for 5 seconds and prints Fishing..... all at once. But when I don't use the end='', it prints dots every second, but on separate lines like so
Fishing.
.
.
.
.

My questions:

*

*Why does print behave this way?

*How can I print a dot every second, but on the same line?

A: *

*Why does print behave this way?

This has less to do with print and more with your terminal. For performance reasons, the text only gets "flushed" everytime there's a newline character, and not one character at a time.

*How can I print a dot every second, but on the same line?

By "flushing" the standard output manually everytime you printed something:
import time
import sys

print('Fishing', end='')
sys.stdout.flush()
for i in range(5):
    time.sleep(1)
    print('.', end='', flush=True)  # another way

If you need this all the time, you could define a seperate flushing print function:
from functools import partial
myprint = partial(print, end='', flush=True)
myprint('Fishing')
for i in range(5):
    time.sleep(1)
    myprint('.')

A: This is because print is considered to be an expensive operation: it will usually wait until it has to print a lot of data, or until a new line is encountered (usually only if output is written to a terminal):

Output buffering is determined by file. Use file.flush() to ensure, for instance, immediate appearance on a screen.

Evidently it is not expensive in the sense that it takes minutes: but asking the terminal operator to print new content, or the operating system to write data to a file (in case of I/O redirection) is still not "lightning fast".
You can force to print all data that is still in the queue, by using a flush on the standard output channel.

A: use
 print('.', end="", flush=True)


text:
Q: In Javascript what does an object refer to base on its declaration? I am having a theory question in my mind while learning Java Script (OOP concepts), until now i have learn two of the following way in which we can define object and initialize it's property and set its value for eg:

// 1st method
var obj1 = {
  name: "John",
  middleName: "XYZ",
  lastName: "David",
};
document.write(obj1.name + obj1.middleName + obj1.lastName);

In the above method the object : obj1 is defined using a keyword (var) which is use for declaring a variable but here we are using it to define an object.Now i know that this object is global and i can acces its property anywhere inside a function or outside a function but what concerns me that this object has no instance to refer (i.e we cannot use instanceof keyword for this object) since i am familar with "Java" language in which every object is an instance of it's class but in JavaScript its a different concept to understand in short my question is : What exactly does the above object is referring to or is this object initialized automatically even when there is no class declared for this object ?

//2nd method

var obj2 = new Person("David");
function Person(name)
{
  document.write(name + " " + "is a person");

}
 document.write(" ");
 document.write(obj2 instanceof Person);

In second method the object : obj2 is an object of a function Person() again being familiar with "Java" concept i thought that the obj2 is an object of class Person and Person() being its constructor for the class Person in short my question is : How can an object be an instanceof a function without a class being declared first ?

A: JavaScript does not have the concept of classes built into it. There are no classes but objects and links between those objects. The objects are linked to each other using the "prototype" property. When you use new with a function name, the object created can be what you return explicitly or "this" within the function if you do not return explicitly.
You can find detailed information at  You-Dont-Know-JS/this & object prototypes.
When not declared using the new keyword, the object you are assigning to it is automatically linked to Object.prototype. This contains several methods that you can invoke via delegation from the newly created object. You can explicitly create an object linked to another using the  Object.create method passing in the object to be linked to as the first parameter. If you do not want your new object to be linked to any other object, you can simply create it as Object.create(null). There are other ways to link objects, however Object.create was introduced recently to simplify the process.

A: I found this helpful to my question and it explains a lot about what i was asking this question for, since every function in java script is treated as an object hence the object declared using new will be an instance of that function
var obj2 = new Person("David"); // Instance of Person()
function Person(name)
{
   //Constructor declared also its an object of prototype i.e. Person.prototype

}
document.write(obj2 instanceof Person);
// true, because: Object.getPrototypeOf(obj2) === Person.prototype

which in turn is the object of prototype object and in the first method above which is
var obj1 = {
  //Rest codes go here
};

has an instance of it's constructor method which is by default Object
 var obj1 = {
  name:David,
  middleName:XYZ,
  lastName:John
};
// Is same as
var obj1 = new Object();
  obj1.name=David;
  obj1.middleName=XYZ;
  obj1.lastName=John;
  document.write(obj1 instanceof Object);
  // true, because: Object.getPrototypeOf(obj1) === Object

Hence in Javascript an object has its instance based on its Constructor method if define explicitly then it is the instance of that function or it is by default instance of Object method
Reference's:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
JavaScript: Class.method vs. Class.prototype.method
Every Object is a function and every function is Object - Which is Correct?
http://www.w3schools.com/js/js_object_definition.asp


text:
Q: git rebase. How Do I Use it to Collapse Reams of Ancient Commits I now have a big honking, bloated, Git repository consuming mucho disk space on GitHub that I want to put on a diet. I need to discard ancient commits made early in the history of the project that are are essentially irrelevant to the current direction the project is going.
I am - and will always be - the sole user of this private repo.
Ideally I could do something like:
git rebase from-birth-of-repo-until-one-month-ago
Thanks,
Doug

A: The --squash option to git merge might be useful, and is available in git 1.4.1 and later.  This stages the effects of a merge, but doesn't create a commit.  So, if 143eff is the oldest commit you want to include in the squashed commit, your current branch is master and the "one month ago" commit is dcb7e5, you could do:
# Save the old position of "master" by creating a branch old-master:
$ git checkout master
$ git branch old-master

# Create and checkout a branch called "new-master" that's at the old commit:
$ git checkout -b new-master 143eff

# Stage the effects of merging the "one month ago" commit:
$ git merge --squash dcb7e5
Updating 143eff3..dcb7e5b
Fast-forward
Squash commit -- not updating HEAD
[... status output showing the staged changes ..]

# Create the squashed commit:
$ git commit -m "A commit squashing history up to a month ago"
# (You could use --amend if you want them to be squashed into 143eff
# instead of being a commit after that.)

Now you can check with git diff dcb7e5 new-master that they really are the same.
Next, you want to rebase the rest of your work onto new-master:
$ git rebase --onto new-master dcb7e5 master

That will leave you on a rebased master which should have the history you want.  (Again, you can check this with git diff old-master master and git log.  When pushing master to github you will need to add --force since you've rewritten history:
# Push master to github, with "--force", since you've rewritten history:
$ git push --force origin master

You can now remove new-master, which is at the squash commit, with:
git branch -d new-master

Apparently github runs git gc --auto on pushes, so you should see some space saving soon...

A: Actually, I will go with boring old git rebase -i HEAD~Number where Number will walk me back from the head to the inital commit. More time consuming but at least I have a vague understanding of what it is doing. Thanks for all the suggestions.

A: Here's a recipe that will work in Git 1.7.2 or newer:

start=$starting_sha1
git checkout --orphan new_master $start
git commit -m 'new root'
git rebase --onto new_master $start master
git checkout master
git reset --hard new_master
git push -f origin master

Cleaning out the old objects that you no longer reference is more work, since they could be pointed to by reflogs, stash, tags, other branches, etc.  Once you're sure these are fixed or removed, one or more of the following should help:

git prune
git gc
git repack -ad


text:
Q: Declaration of this haskell method Im trying to understand Haskell and I have a question: What is the type of this function and how do you call it.
two f(a,b) = f a b

A: If we take, for example, arguments of type Int, then the type of two is like this:
two :: (Int -> Int -> Int) -> (Int, Int) -> Int
two f (a,b) = f a b

example:
two (*) (3,4)
12

Explanation:
You are taking a function that takes 2 arguments (Int -> Int -> Int)and a tuple (Int, Int) and applying that function to a and b.
The actual type, when not constrained, is actually like this:
:t two
two :: (t1 -> t2 -> t) -> (t1, t2) -> t

So for example other things are possible:
two (++) ("he","llo")
"hello"

(etc etc.)


text:
Q: How can I get Snippet in TextSearchReport in V10.4 In the help page, there is a column named snippet which is very useful, but I cann't see it when I evaluate the Function TextSeachReport on V10.3 or V10.4

A: I think this may be a bug because when the code is executed in the documentation the results don't have the "Snippet" column. Perhaps you should report this to WRI.
As a workaround you can create it yourself.
TextSearchReport["ExampleData/Text", "dog"][All,
   <|"Snippet" -> ContentObject[#["Location"]]["Snippet"], #|> &]

Hope this helps.


text:
Q: Issue in 2 node cluster using infinispan 5.3 | ActionStatus.ABORT_ONLY > is not in a valid state to be invoking cache operations on I have a setup of 2 node cluster using Infinispan 5.3. I am testing the failover scenario. When I killed one node, i'm getting the below exception (I'm using the sync cache). The cluster is not getting. So I need to restart the application, which is not practically possible in production environment
         2020-05-06 18:50:28,082 ERROR [org.infinispan.interceptors.InvocationContextInterceptor] ISPN000136: Execution error
    java.lang.IllegalStateException: Transaction TransactionImple < ac, BasicAction: -3f57f478:dd0a:5eb2b455:2d461 status: ActionStatus.ABORT_ONLY > is not in a valid state to be invoking cache operations on.
        at org.infinispan.interceptors.TxInterceptor.enlist(TxInterceptor.java:275)
        at org.infinispan.interceptors.TxInterceptor.enlistIfNeeded(TxInterceptor.java:239)
        at org.infinispan.interceptors.TxInterceptor.enlistReadAndInvokeNext(TxInterceptor.java:233)
        at org.infinispan.interceptors.TxInterceptor.visitGetKeyValueCommand(TxInterceptor.java:229)
        at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:62)
        at org.infinispan.interceptors.base.CommandInterceptor.invokeNextInterceptor(CommandInterceptor.java:120)
        at org.infinispan.interceptors.base.CommandInterceptor.handleDefault(CommandInterceptor.java:134)
        at org.infinispan.commands.AbstractVisitor.visitGetKeyValueCommand(AbstractVisitor.java:96)
        at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:62)
        at org.infinispan.interceptors.base.CommandInterceptor.invokeNextInterceptor(CommandInterceptor.java:120)
        at org.infinispan.statetransfer.StateTransferInterceptor.handleTopologyAffectedCommand(StateTransferInterceptor.java:216)
        at org.infinispan.statetransfer.StateTransferInterceptor.handleDefault(StateTransferInterceptor.java:200)
        at org.infinispan.commands.AbstractVisitor.visitGetKeyValueCommand(AbstractVisitor.java:96)
        at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:62)
        at org.infinispan.interceptors.base.CommandInterceptor.invokeNextInterceptor(CommandInterceptor.java:120)
        at org.infinispan.interceptors.CacheMgmtInterceptor.visitGetKeyValueCommand(CacheMgmtInterceptor.java:113)
        at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:62)
        at org.infinispan.interceptors.base.CommandInterceptor.invokeNextInterceptor(CommandInterceptor.java:120)
        at org.infinispan.interceptors.base.CommandInterceptor.handleDefault(CommandInterceptor.java:134)
        at org.infinispan.commands.AbstractVisitor.visitGetKeyValueCommand(AbstractVisitor.java:96)
        at org.infinispan.interceptors.IsMarshallableInterceptor.visitGetKeyValueCommand(IsMarshallableInterceptor.java:97)
        at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:62)
        at org.infinispan.interceptors.base.CommandInterceptor.invokeNextInterceptor(CommandInterceptor.java:120)
        at org.infinispan.interceptors.InvocationContextInterceptor.handleAll(InvocationContextInterceptor.java:128)
        at org.infinispan.interceptors.InvocationContextInterceptor.handleDefault(InvocationContextInterceptor.java:92)
        at org.infinispan.commands.AbstractVisitor.visitGetKeyValueCommand(AbstractVisitor.java:96)
        at org.infinispan.commands.read.GetKeyValueCommand.acceptVisitor(GetKeyValueCommand.java:62)
        at org.infinispan.interceptors.InterceptorChain.invoke(InterceptorChain.java:343)
        at org.infinispan.CacheImpl.containsKey(CacheImpl.java:372)
        at org.infinispan.DecoratedCache.containsKey(DecoratedCache.java:410)
        at com.abcr.ServiceContext.existsInSyncCache(ServiceContext.java:1740)
        at com.abcr.ServiceContext.getObjectForUpdateInSyncCache(ServiceContext.java:1778)
        at com.abcr.core.cache.ClusterServiceNodeListCacheManager.getObjectForUpdate(ClusterServiceNodeListCacheManager.java:90)
        at com.suntecgroup.tbms.tpe.core.server.ServerManager.callBackOnMembersModified(ServerManager.java:3385)
        at com.abcr.core.ServiceContainerCommandDespatcher.run(ServiceContainerCommandDespatcher.java:64)
    2020-05-06 18:50:28,086 ERROR [com.abcr.core.ServiceContainer] Invocation of callback APIs on leaving coordinator role failed for service 'ABC'.
    com.suntecgroup.tbms.container.services.ContainerPlatformServicesException: Failed to retrieve object[SERVER/SERVICE_NODES/28000] for update.

This my infinspan and jgroups configuration

<infinispan
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:infinispan:config:5.3 http://www.infinispan.org/schemas/infinispan-config-5.3.xsd"
      xmlns="urn:infinispan:config:5.3">
<global>
    <!-- Note that if these are left blank, defaults are used.  See the user guide for what these defaults are -->
    <asyncListenerExecutor factory="org.infinispan.executors.DefaultExecutorFactory">
      <properties>
        <property name="maxThreads" value="5" />
        <property name="threadNamePrefix" value="AsyncListenerThread" />
      </properties>
    </asyncListenerExecutor>
    <asyncTransportExecutor factory="org.infinispan.executors.DefaultExecutorFactory">
      <properties>
        <property name="maxThreads" value="25" />
        <property name="threadNamePrefix" value="AsyncSerializationThread" />
      </properties>
    </asyncTransportExecutor>
    <evictionScheduledExecutor factory="org.infinispan.executors.DefaultScheduledExecutorFactory">
      <properties>
        <property name="threadNamePrefix" value="EvictionThread" />
      </properties>
    </evictionScheduledExecutor>
    <replicationQueueScheduledExecutor factory="org.infinispan.executors.DefaultScheduledExecutorFactory">
      <properties>
        <property name="threadNamePrefix" value="ReplicationQueueThread" />
      </properties>
    </replicationQueueScheduledExecutor>
    <globalJmxStatistics enabled="false" jmxDomain="infinispan_1" />
    <!--
         If the transport is omitted, there is no way to create distributed or clustered caches.
         There is no added cost to defining a transport but not creating a cache that uses one, since the transport
         is created and initialized lazily.
         -->
    <transport clusterName="PC_SITE_1" distributedSyncTimeout="50000" transportClass="org.infinispan.remoting.transport.jgroups.JGroupsTransport">
      <properties>
        <property name="configurationFile" value="./tmp/_clusterconfig/pc_jgroups_main_sync.xml" />
      </properties>
    </transport>
    <!-- Note that the JGroups transport uses sensible defaults if no configuration property is defined. -->
    <!-- See the JGroupsTransport javadocs for more flags -->
    <!-- Again, sensible defaults are used here if this is omitted.  -->
    <serialization marshallerClass="org.infinispan.marshall.VersionAwareMarshaller" version="1.0" />
    <!--
         Used to register JVM shutdown hooks.
         hookBehavior: DEFAULT, REGISTER, DONT_REGISTER
        -->
    <shutdown hookBehavior="DEFAULT" />
  </global>
  <!-- *************************** -->
  <!-- Default "template" settings -->
  <!-- *************************** -->
  <!-- this is used as a "template" configuration for all caches in the system. -->
  <default>
    <!--
         isolation levels supported: READ_COMMITTED and REPEATABLE_READ
         -->
    <locking isolationLevel="READ_COMMITTED" lockAcquisitionTimeout="60000" writeSkewCheck="false" concurrencyLevel="5000" useLockStriping="false" />
    <!--
        Used to register a transaction manager and participate in ongoing transactions.
        -->
    <!-- ECPCacheTxManagerLookup -->
    <!--
        Used to register JMX statistics in any available MBean server
        -->
    <jmxStatistics enabled="false" />
    <!--
        Used to enable invocation batching and allow the use of Cache.startBatch()/endBatch() methods.
        -->
    <clustering mode="replication">
      <sync replTimeout="600000" />
      <stateTransfer timeout="480000" fetchInMemoryState="true" />
    </clustering>
    <storeAsBinary enabled="true" />
  </default>
  <namedCache name="GLOBAL_SYNC_CACHE">
    <transaction transactionMode="TRANSACTIONAL" transactionManagerLookupClass="com.suntecgroup.tbms.container.services.cluster.ContainerCacheTxManagerLookup" syncRollbackPhase="false" syncCommitPhase="true" useEagerLocking="true" lockingMode="PESSIMISTIC" />
  </namedCache>
  <namedCache name="GLOBAL_NONTX_SYNC_CACHE">
    <transaction transactionMode="NON_TRANSACTIONAL" />
  </namedCache>
</infinispan>

JGROUPS configuration..

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="urn:org:jgroups" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:org:jgroups file:schema/JGroups-2.8.xsd">
  <TCP bind_port="7800" loopback="true" recv_buf_size="20M" send_buf_size="640K" max_bundle_size="64000" max_bundle_timeout="30" enable_bundling="false" use_send_queues="true" sock_conn_timeout="300" tcp_nodelay="true" thread_pool.enabled="true" thread_pool.min_threads="1" thread_pool.max_threads="25" thread_pool.keep_alive_time="5000" thread_pool.queue_enabled="false" thread_pool.queue_max_size="100" thread_pool.rejection_policy="run" oob_thread_pool.enabled="true" oob_thread_pool.min_threads="1" oob_thread_pool.max_threads="8" oob_thread_pool.keep_alive_time="5000" oob_thread_pool.queue_enabled="false" oob_thread_pool.queue_max_size="100" oob_thread_pool.rejection_policy="run" enable_diagnostics="false" />
  <!--MPING mcast_addr="232.1.2.13"
                   mcast_port="7500"
                   num_initial_members="2"
                   timeout="2000" /-->
  <TCPPING timeout="3000" initial_hosts="${jgroups.tcpping.initial_hosts:localhost[7800],localhost[7801]}" port_range="0" num_initial_members="3" />
  <MERGE2 max_interval="100000" min_interval="20000" />
  <FD_SOCK />
  <FD timeout="60000" max_tries="5" />
  <VERIFY_SUSPECT timeout="30000" />
  <BARRIER />
  <pbcast.NAKACK use_mcast_xmit="false" exponential_backoff="500" discard_delivered_msgs="true" />
  <UNICAST timeout="300,600,1200" />
  <pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000" max_bytes="400000" />
  <pbcast.GMS print_local_addr="false" join_timeout="3000" view_bundling="true" />

  FRAG2 frag_size="60000"

  pbcast.STATE_TRANSFER
</config>

A: Current transaction was aborted (probably due to a timeout, but maybe as a consequence of delivery failure). You need to rollback current transaction and start new.
However let me note that 5.3 was released 2013/06/26 - you're using almost 7 years old version. If there is a bug, no-one will even try to check it out.


text:
Q: An error about vectorization in R My R code is as follows. The main task is to calculate the row number of repetitions.
library(plyr)
data<-data.frame(1,2,3);
x <- read.table(text = "ID1    ID2    n    m
13    156   12   15
94    187   14   16
66    297   41   48
29    89    42   49
78    79    51   79", header= TRUE)

distfunc <- function(data,ID1,ID2,n,m){
X1<-ID1; ################
X2<-ID2; ################
X3<-unlist(mapply(':', n, m));
data<-rbind(data,data.frame(X1,X2,X3));
return(data);
}

data<-distfunc(data,x$ID1, x$ID2,x$n, x$m)

data<-data[-1,]

    plyr::count(data, names(data)); ## Calculates the row number of repetitions

The error message I get:
Error in data.frame(X1, X2, X3) :
  arguments imply differing number of rows: 5, 52

I try to fix it by R Error: "In numerical expression has 19 elements: only the first used", but it failed and the result is wrong. This probelm is not the same as that probelm.

A: I just fixed it.
distfunc <- function(data, ID1, ID2, n, m) {
  X1 <- ID1
  X2 <- ID2
  X3 <- unlist(mapply(':', n, m))
  data <- rbind(data,data.frame(X1, X2, X3))
  return(data)
}

A: I suppose you want to do:
# library(plyr)
# data<-data.frame(1,2,3);
x <- read.table(header=TRUE, text =
"ID1    ID2    n    m
  13    156   12   15
  94    187   14   16
  66    297   41   48
  29    89    42   49
  78    79    51   79")

#distfunc <- function(data, ID1, ID2, n, m) {
#  X1 <- ID1 ################
#  X2 <- ID2 ################
#  X3 <- unlist(mapply(':', n, m))
#  data <- rbind(data, data.frame(X1,X2,X3))
#}

#data <- distfunc(data, x$ID1, x$ID2, x$n, x$m)
L <- apply(x, 1, function(x) data.frame(X1=x[1], X2=x[2], X3=x[3]:x[4], row.names=NULL))
data <- L[[1]]
for (i in 2:length(L)) data <- rbind(data, L[[i]])

or with a better readable function in apply():
L <- apply(x, 1, function(r) data.frame(X1=r["ID1"], X2=r["ID2"], X3=r["n"]:r["m"], row.names=NULL))
data <- L[[1]]; for (i in 2:length(L)) data <- rbind(data, L[[i]])

Here is a simpler variant:
data <- data.frame(X1=x$ID1[1], X2=x$ID2[1], X3=x$n[1]:x$m[1])
for (i in 2:nrow(x)) data <- rbind(data, data.frame(X1=x$ID1[i], X2=x$ID2[i], X3=x$n[i]:x$m[i]))


text:
Q: The union of a NOT strictly increasing sequence of $\sigma$-algebras is not a $\sigma$-algebra Im refering to
The Problem with strictly increasing sequences
What will change if I have not a strictly increasing sequence but just an increasing one:
$A_1\subseteq A_2 \subseteq A_3 \subseteq \cdots $?

A: If there are infinitely any strict inclusions $A_n\subsetneq A_{n+1}$, then by discarding all equalities in the chain, you get a strictly increasing chain which has the same union, and hence this union is not a $\sigma$-algebra by the problem you've linked to.
On the other hand, if there are only finitely many strict inclusions, then for some $n$ we have $A_n=A_{n+1}=\cdots$, and hence $\cup_i A_i=A_n$, which is a $\sigma$-algebra by assumption.


text:
Q: Fortran confusion, modules, declarations, dummy arguments my problem is to integrate a function using romberg integration. I am retaking this class and was successful last semester but this time around my professor is requiring modules, which I could never figure out. Another problem has always been dummy arguments. The basic layout is this
Global variable module >
Main prog >
external fn within prog >
subprogram romberg (module, uses function)

I placed my "x" variable in the global variable module but am not sure where I need interfacing and where I need the USE statement. I can't get the romberg module to compile because it's not seeing the x variable I declared no matter where I place it.
MODULE globvar
IMPLICIT NONE
INTEGER,PARAMETER:: dp=selected_real_kind(15)
REAL(dp)::a,b,epsil,cp,h,x,mu
REAL(dp),PARAMETER::pi=3.141592653589, m=45000.0, D=1.032, Ts=250.0, k=0.153
INTEGER::maxit,nt,n,exitflag
END MODULE globvar

Romberg Mod
MODULE romod
CONTAINS

SUBROUTINE Romberg(f,a,b,nt,epsi,maxit,exitflag,n)
IMPLICIT NONE
INTEGER, PARAMETER :: dp = selected_real_kind(15)
REAL(dp),INTENT(IN)::a,b
INTEGER,INTENT(IN)::epsi,maxit
INTEGER,INTENT(OUT)::exitflag
INTEGER,INTENT(INOUT)::nt
REAL(dp),DIMENSION(maxit+1,maxit+1)::T
REAL(dp)::sone,stwo,h
INTEGER::r,n,I,j,k

INTERFACE !Interface function ! I was told this wasnt needed then it was
FUNCTION f(x)
USE globvar
IMPLICIT NONE
INTEGER::f
END FUNCTION f
END INTERFACE

Romberg algorithm omitted, unless asked for. x is being passed to an upper and lower limit
END SUBROUTINE Romberg

END MODULE romod

Main Prog
PROGRAM Waste
USE globvar
USE romod
IMPLICIT NONE
INTEGER, EXTERNAL::f

INTERFACE
FUNCTION f(x)
USE globvar !Use Module Variables
IMPLICIT NONE
INTEGER::f
END FUNCTION f
END INTERFACE

read prompts

CALL Romberg(f,a,b,nt,epsi,maxit,exitflag,n)

END PROGRAM Waste

FUNCTION f(x)
USE globvar !Use Module Variables
IMPLICIT NONE
INTEGER::f

f=x**3

END FUNCTION f

END PROGRAM Waste

Any help would be appreciated. This is my 5th semester using fortran and some of the rules still elude me.

A: Lots of stuff going on here, but just addressing the dummy variable issue think about this,
suppose I have a 'global' variable x via use module both in calling program and a function and I do this:
 USE globvar
  ...
 x=2
 y=3
 z=f(y)

..
 function f(x)
 USE globvar
 f=x^2

!! is x 2 or 3 ??
Of course this is logically inconsistent, and will fail to compile. (and no the compiler will not be satisfied if you painstakingly only ever call f(x) )
My advice is to avoid the use of global variables all together.
re: interface, there is nothing about your function that requires an explicit interface in the first place.


text:
Q: Jersey Client - Post request giving error "Content-Type header must be application/vnd.api+json" I am trying to test post request using jersey client, although i am setting header as below i am getting error in response that Content-Type header must be application/vnd.api+json. Please refer below code:
String input = "{\r\n" +
                "  \"data\": {\r\n" +
                "    \"attributes\": {\r\n" +
                "      \"email\": \"emailqwszxwe@example.com\",\r\n" +
                "      \"password\": \"password\",\r\n" +
                "      \"avatar_url\": \"http://example.com/example.png\",\r\n" +
                "      \"first-name\": \"John\",\r\n" +
                "      \"last-name\": \"Doe\",\r\n" +
                "      \"details\": \"example\",\r\n" +
                "      \"contact\": \"example\",\r\n" +
                "      \"facebook-url\": \"http://facebook.com/facebook\",\r\n" +
                "      \"twitter-url\": \"http://twitter.com/twitter\",\r\n" +
                "      \"instagram-url\": \"http://instagram.com/instagram\",\r\n" +
                "      \"google-plus-url\": \"http://plus.google.com/plus.google\",\r\n" +
                "      \"original-image-url\": \"https://cdn.pixabay.com/photo/2013/11/23/16/25/birds-216412_1280.jpg\"\r\n" +
                "    },\r\n" +
                "    \"type\": \"user\"\r\n" +
                "  }\r\n" +
                "}";
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://qe.events.infostretch.com/api");

    String content = "application/vnd.api+json";
    Response response = target.path("/v1/users").request().header("Content-Type", content).post(Entity.json(input));

Output :
{"errors": [{"source": "", "detail": "Content-Type header must be application/vnd.api+json", "title": "InvalidRequestHeader", "status": 415}], "jsonapi": {"version": "1.0"}}```

I am not able to understand why it is not showing correct response???

i am using below dependency:

<dependency> <groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.30.1</version> </dependency>


text:
Q: Why use hidden Markov model vs. Markov model in Baum Welch algorithm So I am trying to build the Baum Welch algorithm to do parts of speech tagging for practice. However, I am confused about using a hidden Markov Model vs. a Markov Model. Since it seems that you are losing context moving from state to state. Since the output of the last state isn't taken into account when moving to the next state. Is it just to save memory?
edit: added an example for clarity
For example if two states, A and B output a 0 or 1 there will be 4 state transitions and 2 obseravation possibilities for each state, which can be can be made into 8 transitions if you mix each pair of incoming transitions with it's state's obseravation probabilities. But my hang up is why not initially train a machine with four states {(A,1),(B,1),(A,2),(B,2)} with 16 transitions. I am quite new to nlp so I wondering if I am unaware of some algorithmic redundancy that hard to see without harder math.
Since it seems that one loses the information of what the transitions will be when of the last A was 1 vs. 2. But I'm wondering if the training algorithms might not need that information.
https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm
Thanks for the information.

A: It's not just to save memory, it's to provide a better model of what is really going on. In the case of text, you believe that there is an underlying grammar which says that this word is being used as a noun, and that word is being used as a verb, but you don't get labels that say this and it isn't always obvious from the data. E.g. - looking at what I have just typed, better is an adjective in "a better model" but if I am using stack overflow to better myself, I have just used better as a verb. So whether better is an adjective or a verb is a hidden state and a realistic model will reflect this.
Hidden markov models are also flexible enough that if you really don't have any hidden state, you can create a degenerate sort of hidden markov model that reflects this. For instance, if every hidden state can produce only one possible output, and no two hidden states can ever produce the same output, then you have a hidden markov model in which you can always predict the so-called hidden state from the output and vice versa. It will be very easy to fit the parameters of this, but it probably won't be as good at modelling reality as a proper hidden markov model.