text:
Q: processing parquet file in pyspark on saving giving error I am doing a process using csv files like this
df = spark.read.csv(path = '/mycsv.csv', header = True)

then saving to db
%sql
CREATE DATABASE IF NOT EXISTS MY_DB

and
df.write.saveAsTable("MY_DB.mycsv")

it's working fine
now In case of parquet I am doing somehow same
df = spark.read.format("parquet").load(path = '/sample.parquet', header = True)

then
df.write.saveAsTable("MY_DB.sample")

and it's giving me error
AnalysisException
AnalysisException:
Found invalid character(s) among " ,;{}()\n\t=" in the column names of your
schema.
Please enable column mapping by setting table property 'delta.columnMapping.mode' to 'name'.

For more details, refer to https://learn.microsoft.com/azure/databricks/delta/delta-column-mapping
Or you can use alias to rename it.

what it means ?
UPDATE
on print schema on parquet file it is showing
root
 |-- Region: string (nullable = true)
 |-- Country: string (nullable = true)
 |-- Item Type: string (nullable = true)
 |-- Sales Channel/test: string (nullable = true)
 |-- Order Priority: string (nullable = true)
 |-- Order Date: date (nullable = true)
 |-- Order ID: integer (nullable = true)
 |-- Ship Date: date (nullable = true)
 |-- Units Sold: integer (nullable = true)
 |-- Unit Price: double (nullable = true)
 |-- Unit Cost: double (nullable = true)
 |-- Total Revenue: double (nullable = true)
 |-- Total Cost: double (nullable = true)
 |-- Total Profit: double (nullable = true)

and for csv file it is showing (it is diff file and parquet is diff file)
root
 |-- HashKey: string (nullable = true)
 |-- GLKey: string (nullable = true)
 |-- AccountingDateKey: string (nullable = true)
 |-- MainAccountKey: string (nullable = true)
 |-- LocationKey: string (nullable = true)
 |-- BusinessUnitKey: string (nullable = true)
 |-- DepartmentKey: string (nullable = true)
 |-- CompanyKey: string (nullable = true)
 |-- FinancialHierarchyKey: string (nullable = true)
 |-- FinancialSLIDKey: string (nullable = true)
 |-- FinancialTaxKey: string (nullable = true)
 |-- FinancialPayrollKey: string (nullable = true)
 |-- FinancialCustomerKey: string (nullable = true)
 |-- FinancialVendorKey: string (nullable = true)
 |-- FinancialBankKey: string (nullable = true)
 |-- FinancialInventoryKey: string (nullable = true)
 |-- FinancialIntangiblesKey: string (nullable = true)
 |-- FinancialBankSubKey: string (nullable = true)
 |-- DimGLKey: string (nullable = true)
 |-- DWCreatedDateTime: string (nullable = true)

A: So as indicating by @Mohamed Yasser there was issue in columns name which were creating issue . after using select in conjunction with a list comprehension it is now returning name of columns as  Item_Type which fixed the issue
from pyspark.sql import functions as F

renamed_df = df.select([F.col(col).alias(col.replace(' ', '_')) for col in df.columns])


text:
Q: From two Tensors (labels, inputs) to DataLoader I'm working with two tensors, inputs and labels, and I want to have them together to train a model. I'm using torch 1.7, but I can't use the function TensorDataset() and then apply DataLoader(), due to some incompatibilities with other packages when I use TensorDataset(). There is another solution to my problem?
Summary:
2 Tensors --> DataLoader without using TensorDataset()

A: You can construct your own custom DataSet:
class MyDataSet(torch.utils.data.Dataset):
  def __init__(self, x, y):
    super(MyDataSet, self).__init__()
    # store the raw tensors
    self._x = x
    self._y = y

  def __len__(self):
    # a DataSet must know it size
    return self._x.shape[0]

  def __getitem__(self, index):
    x = self._x[index, :]
    y = self._y[index, :]
    return x, y

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularFire - Push data from firestore collection query into an array I'm querying a Firestore collection an successfully retrieving the results. However, I'm using a sortable angular plugin that requires an array to sort.
The issue I have is that the items are being pushed into the array, but I cannot find a correct location to clear the array when new items come in. Without clearing the array, the results returned start to duplicate in the array.
Is someone able to help refactor the code below so that I can successfully push the collection results into the array and clear it in the correct spot please?
...
itemsArray = []
...

getData(){
    this.issueCollection = this.afs.collection<any>(`users/${user}/projects/${project}/issues`, ref => {
      return ref.orderBy('order');
    });
    this.issues = this.issueCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;

        this.itemsArray.push({ id, ...data });

        return { id, ...data };
      }))
    );
  }

HTML - How I need the HTML to display the results
<ul>
   <li *ngFor="let issue of itemsArr">
      {{ issue.issueName }}
   </li>
</ul>

Update - This seems to work
  getData(){
    this.issueCollection = this.afs.collection<any[]>(`users/${user}/projects/${project}/issues`, ref => {
      return ref.orderBy('issue_order');
    });
    this.issues = this.issueCollection.snapshotChanges().pipe(
      map(actions => {
      this.itemsArr = [];
      return actions.map(a => {

        const data = a.payload.doc.data();
        const id = a.payload.doc.id;

        this.itemsArr.push({ id, ...data });

        return { id, ...data };
      });
    }))
  }

A: What I would do is make it subcribe to the collection and do this:
getData(){
    this.issueCollection = this.afs.collection<any[]>(`users/${user}/projects/${project}/issues`, ref => {
      return ref.orderBy('order');
    });
    this.issues = this.issueCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;

            return { id, ...data };
        }))).subscribe((items: any[]) => {
          this.itemsArray = [];
          this.itemsArray = items;
       });
  }

This will allow you to empty the itemsArray and refill it. Instead of only pushing the array and never empty it.


text:
Q: thymeleaf-spring4:jar could not find artifact - gradle intelijj I'm trying to build a simple application, using gradle, groovy, and spring-boot framework with this code:
@Grab("thymeleaf-spring4")

@Controller
class ViewBasedApp {
    def chapters = ["Quick Start With Groovy",
                    "Quick Start With Java",
                    "Debugging and Managing Your App",
                    "Data Access with Spring Boot",
                    "Securing Your App"]
    @RequestMapping("/")
    def home(@RequestParam(value="name", defaultValue="World") String n) {
        new ModelAndView("home")
                .addObject("name", n)
                .addObject("chapters", chapters)
    }
}

This is my build.gradle file:
group 'LoginApp'
version '1.0-SNAPSHOT'

apply plugin: 'groovy'

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    testCompile group: 'junit', name: 'junit', version: '4.12'

    compile("org.springframework.boot:spring-boot-starter-web")
    //compile("org.thymeleaf:thymeleaf-spring4") //first try
   // compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect") //first try
    compile 'org.springframework:spring-webmvc:3.0.0.RELEASE'

    // https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring4 //secound try
    compile group: 'org.thymeleaf', name: 'thymeleaf-spring4', version: '3.0.0.RELEASE'
   // compile group: 'org.thymeleaf', name: 'thymeleaf-spring4', version: '4.1.6.RELEASE' //third try
}

html file:

    <title>Learning Spring Boot - Chapter 1</title>

To launch my app I using spring boot CLI. When I have been using "spring run" in command prompt, I always have got the same error:
Could not find artifact :thymeleaf-spring4:jar: in local (file:/C:/Users/kubas/repository).
I have tried to add "thymeleaf-spring4.jar" - downloaded from maven page, to folder "repository" and nothing, always the same error.
Can anybody suggest on this?

A: I resolved issue by adding dependency from local Repository:
buildscript {
    repositories {
        mavenLocal()
    }
    dependencies {
        classpath("org.thymeleaf:thymeleaf-spring5:3.0.9.RELEASE")
    }
}
repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect") //first try
    compile 'org.springframework:spring-webmvc:4.0.6.RELEASE'
    compile 'org.springframework:spring-web:4.0.6.RELEASE' //@EnableWebMvc @ComponentScan
}

Now thymeleaf is taken from C:\Users\kubas\org\thymeleaf\thymeleaf-spring5
I had to change annotation in app.groovy to @Grab("thymeleaf-spring5")
but now I can't configure path to my templates file. My path to this file is:
F:\gradle_login_aPP\src\main\resources\templates ...
This is the error:

Cannot find template location: classpath:/templates/

I have tried add application.properties file in \src\main\resources\  but it doesn't work. I know it is possible to add default prefix, but I can't find information about file, where i need to add this. Any Suggestion, how to run this templates with gradle project?

A: I resolved this issue. I have used .html file and this is the way how I use this file in my Controller Class:
@RestController
class LoginServiceApplication {

    @RequestMapping("/")
    String home() {
        def htmlContent = new File("F:\\APKA_W_SPRINGU\\Spring-apps-master\\AppWithLoginPage\\LoginService\\src\\main\\resources\\templates\\index.html").text

        htmlContent
    }
}

For the first question -  all I had have to do was a run main class in intelijj using  button run (Class must not contain @Grab annotation!), before I resolved this problem  I was using spring CLI  and that was a problem. Now everything works fine.


text:
Q: Strip Characters in Jupyter I have what should be a simple problem. I have a lot of data which comes in the timestamp as below
I want to remove the values " +01" from the right hand side.
     Time
0 12/11/2021 09:26:02.001 +01
1 12/11/2021 09:26:02.021 +01

I am using the code below, but this also removes the .001 part of the first timestamp also
df=df.map(lambda x: x.rstrip(' +01'))

Is there a simple way to do this?

A: rstrip method deals with the provided strings as a list of characters to remove. It will remove any character (from the right side) that is within the string.
You can instead use regex:
import re
re.sub(r" \+01", "", a)


text:
Q: How to spot/measure artifacts produced by several rotations of 2-dimensional data? I am trying to transform dataset to mulitiply its size but preserve its initial random nature.
I have 5-dimensional numerical dataset which represent particles in plane, produced by Monte Carlo simulation. Dataset consists of energy, position(x,y), and direction cosines (x,y) for particles. This is scatter plot of my particle positions
I have rotated this plane 5 times and combined results into one new dataset which now has 5 time s more particles.
My question is: Is there a method of statistical analysis which would give me some quantitative results of how much have i disrupted randomness by rotating it ?
I am aware of visual artifacts that can be spotted after several rotations (example: if i rotate by 72deg 5 times (up to 360), there should be pentagram-like pattern in scatter plot, for 60 degres 6 times - hexagram-like pattern etc.), but i'm interested in more elegant solution for analysis.


text:
Q: presto configuration through emr launch config I am trying to deploy presto om EMR through our EMR launch config JSON. I have decided the config properties as advised in this github issue of presto. I have added the following presto properties in the launch config
{
    "Classification": "presto-connector-hive",
    "Properties": {
        "hive.metastore.glue.datacatalog.enabled": "true",
        "hive.table-statistics-enabled": "true"
    },
    "Configurations": []
},
{
    "Classification": "presto-config",
    "Properties": {
        "query.max-memory": "150G",
        "query.max-memory-per-node": "20G",
        "query.max-total-memory-per-node": "30G",
        "memory.heap-headroom-per-node": "10G",
        "query.initial-hash-partitions": "15"
    },
    "Configurations": []
}

EMR cluster has been created but presto is failing due to the following errors
1) Explicit bindings are required and com.facebook.presto.memory.LowMemoryKiller is not explicitly bound.
  while locating com.facebook.presto.memory.LowMemoryKiller
    for parameter 7 at com.facebook.presto.memory.ClusterMemoryManager.<init>(ClusterMemoryManager.java:123)
  at com.facebook.presto.server.CoordinatorModule.setup(CoordinatorModule.java:189) (via modules: com.facebook.presto.server.ServerMainModule -> com.facebook.presto.server.CoordinatorModule)

2) Error: Could not coerce value '150G' to io.airlift.units.DataSize (property 'query.max-memory') in order to call [public com.facebook.presto.memory.MemoryManagerConfig com.facebook.presto.memory.MemoryManagerConfig.setMaxQueryMemory(io.airlift.units.DataSize)]

3) Error: Could not coerce value '20G' to io.airlift.units.DataSize (property 'query.max-memory-per-node') in order to call [public com.facebook.presto.memory.NodeMemoryConfig com.facebook.presto.memory.NodeMemoryConfig.setMaxQueryMemoryPerNode(io.airlift.units.DataSize)]

4) Configuration property 'memory.heap-headroom-per-node' was not used
  at io.airlift.bootstrap.Bootstrap.lambda$initialize$2(Bootstrap.java:234)

5) Configuration property 'query.max-memory' was not used
  at io.airlift.bootstrap.Bootstrap.lambda$initialize$2(Bootstrap.java:234)

6) Configuration property 'query.max-memory-per-node' was not used
  at io.airlift.bootstrap.Bootstrap.lambda$initialize$2(Bootstrap.java:234)

7) Configuration property 'query.max-total-memory-per-node' was not used
  at io.airlift.bootstrap.Bootstrap.lambda$initialize$2(Bootstrap.java:234)

7 errors
    at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:466)
    at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:155)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)
    at com.google.inject.Guice.createInjector(Guice.java:96)
    at io.airlift.bootstrap.Bootstrap.initialize(Bootstrap.java:241)
    at com.facebook.presto.server.PrestoServer.run(PrestoServer.java:114)
    at com.facebook.presto.server.PrestoServer.main(PrestoServer.java:66)

My config.properties file
coordinator=true
node-scheduler.include-coordinator=false
discovery.uri=X.X.X.X:YYYY
http-server.threads.max=500
discovery-server.enabled=true
sink.max-buffer-size=1GB
query.max-memory=150G
query.max-memory-per-node=20G
query.max-history=40
query.min-expire-age=30m
http-server.http.port=8889
http-server.log.path=/var/log/presto/http-request.log
http-server.log.max-size=67108864B
http-server.log.max-history=5
log.max-size=268435456B
log.max-history=5
query.initial-hash-partitions = 15
memory.heap-headroom-per-node = 10G
query.max-total-memory-per-node = 30G

A: Setup fails because

*

*You need to use "GB" (not "G") as the unit when setting data size config properties

*Your version (0.194) doesn't support some properties that you're setting (memory.heap-headroom-per-node nor query.max-total-memory-per-node).


text:
Q: Conan create package with dependencies I'm trying to build a conan package for netcdf-c. NetCDF requires zlib and hdf5 as dependencies, both of them are available through the conan center.
I added them as requirements to my conanfile.py. When running conan create . testing/build to create the conan package from my conanfile.py CMake is not able to build netcdf-c. The output of conan create shows me that zlib and hdf5 are installed, but can't be found. When compiling netcdf-c with cmake I have to set configure it like this: CPPFLAGS="-I${H5DIR}/include -I${ZDIR}/include" LDFLAGS="-L${H5DIR}/lib -L${ZDIR}/lib" --prefix=${NCDIR} --disable-dap. How can I set these flags inside my conanfile.py ?
conanfile.py:
from conans import ConanFile, CMake, tools

class NetcdfcConan(ConanFile):
    name = "netcdf_c"
    version = "4.7.3"
    license = "BSD 3-Clause 'New' or 'Revised' License"
    author = "Arne Osterthun arne.osterthun@dlr.de"

    description = "The Unidata network Common Data Form (netCDF) is an interface for scientific data access and a freely-distributed software library that provides an implementation of the interface. The netCDF library also defines a machine-independent format for representing scientific data. Together, the interface, library, and format support the creation, access, and sharing of scientific data. The current netCDF software provides C interfaces for applications and data. Separate software distributions available from Unidata provide Java, Fortran, Python, and C++ interfaces. They have been tested on various common platforms."
    topics = ("raster data", "ndarray", "array")
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [True, False]}
    default_options = {"shared": False}
    requires = "zlib/1.2.11", "hdf5/1.10.6"
    generators = "cmake"

    def source(self):
        self.run("git clone --branch v4.7.3 https://github.com/Unidata/netcdf-c.git")

    def build(self):
        cmake = CMake(self)
        cmake.configure(source_folder="netcdf-c")
        cmake.build()

    def package(self):
        pass

    def package_info(self):
        pass

output:
[HOOK - attribute_checker.py] pre_export(): WARN: Conanfile doesn't have 'url'. It is recommended to add it as attribute
Exporting package recipe
netcdf_c/4.7.3@testing/build: A new conanfile.py version was exported
netcdf_c/4.7.3@testing/build: Folder: /home/domane/.conan/data/netcdf_c/4.7.3/testing/build/export
netcdf_c/4.7.3@testing/build: Package recipe modified in export, forcing source folder removal
netcdf_c/4.7.3@testing/build: Use the --keep-source, -k option to skip it
netcdf_c/4.7.3@testing/build: Exported revision: d70e63d07a15cf7376055e606b3244c3
Configuration:
[settings]
arch=x86_64
arch_build=x86_64
build_type=Release
compiler=gcc
compiler.libcxx=libstdc++11
compiler.version=7
os=Linux
os_build=Linux
[options]
[build_requires]
[env]

netcdf_c/4.7.3@testing/build: Forced build from source
netcdf_c/4.7.3@testing/build (test package): Installing package
Requirements
    hdf5/1.10.6 from 'conan-center' - Cache
    netcdf_c/4.7.3@testing/build from local cache - Cache
    zlib/1.2.11 from 'conan-center' - Cache
Packages
    hdf5/1.10.6:d1d93931f0a5aab8450858e1d6eae88ac6c39f6d - Cache
    netcdf_c/4.7.3@testing/build:ed9c760b5cbeeac4d6f9420203834fe68a6384de - Build
    zlib/1.2.11:d50a0d523d98c15bb147b18fa7d203887c38be8b - Cache

Installing (downloading, building) binaries...
zlib/1.2.11: Already installed!
hdf5/1.10.6: Already installed!
netcdf_c/4.7.3@testing/build: WARN: Build folder is dirty, removing it: /home/domane/.conan/data/netcdf_c/4.7.3/testing/build/build/ed9c760b5cbeeac4d6f9420203834fe68a6384de
netcdf_c/4.7.3@testing/build: Configuring sources in /home/domane/.conan/data/netcdf_c/4.7.3/testing/build/source
Cloning into 'netcdf-c'...
Note: checking out 'b7cd387bee8c661141fabb490f4969587c008c55'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

Checking out files: 100% (2211/2211), done.
netcdf_c/4.7.3@testing/build: Copying sources to build folder
netcdf_c/4.7.3@testing/build: Building your package in /home/domane/.conan/data/netcdf_c/4.7.3/testing/build/build/ed9c760b5cbeeac4d6f9420203834fe68a6384de
netcdf_c/4.7.3@testing/build: Generator cmake created conanbuildinfo.cmake
netcdf_c/4.7.3@testing/build: Calling build()
-- The C compiler identification is GNU 7.5.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check if the system is big endian
-- Searching 16 bit integer
-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for stdint.h
-- Looking for stdint.h - found
-- Looking for stddef.h
-- Looking for stddef.h - found
-- Check size of unsigned short
-- Check size of unsigned short - done
-- Using unsigned short
-- Check if the system is big endian - little endian
-- Performing Test LIBTOOL_HAS_NO_UNDEFINED
-- Performing Test LIBTOOL_HAS_NO_UNDEFINED - Success
-- Performing Test CC_HAS_WCONVERSION
-- Performing Test CC_HAS_WCONVERSION - Success
-- Performing Test CC_HAS_SHORTEN_64_32
-- Performing Test CC_HAS_SHORTEN_64_32 - Failed
-- Unable to determine HDF5 C flags from HDF5 wrapper.
-- Unable to determine HDF5 C version from HDF5 wrapper.
CMake Error at /usr/share/cmake-3.10/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
  Could NOT find HDF5 (missing: HDF5_LIBRARIES HDF5_INCLUDE_DIRS
  HDF5_HL_LIBRARIES C HL) (found version "")
Call Stack (most recent call first):
  /usr/share/cmake-3.10/Modules/FindPackageHandleStandardArgs.cmake:378 (_FPHSA_FAILURE_MESSAGE)
  /usr/share/cmake-3.10/Modules/FindHDF5.cmake:905 (find_package_handle_standard_args)
  CMakeLists.txt:623 (FIND_PACKAGE)

-- Configuring incomplete, errors occurred!
See also "/home/domane/.conan/data/netcdf_c/4.7.3/testing/build/build/ed9c760b5cbeeac4d6f9420203834fe68a6384de/netcdf-c/build/CMakeFiles/CMakeOutput.log".
See also "/home/domane/.conan/data/netcdf_c/4.7.3/testing/build/build/ed9c760b5cbeeac4d6f9420203834fe68a6384de/netcdf-c/build/CMakeFiles/CMakeError.log".
netcdf_c/4.7.3@testing/build:
netcdf_c/4.7.3@testing/build: ERROR: Package 'ed9c760b5cbeeac4d6f9420203834fe68a6384de' build failed
netcdf_c/4.7.3@testing/build: WARN: Build folder /home/domane/.conan/data/netcdf_c/4.7.3/testing/build/build/ed9c760b5cbeeac4d6f9420203834fe68a6384de
ERROR: netcdf_c/4.7.3@testing/build: Error in build() method, line 22
        self.run("cd netcdf-c && mkdir build && cd build && cmake .. && cmake --build . -- -j8", run_environment=True)
        ConanException: Error 1 while executing cd netcdf-c && mkdir build && cd build && cmake .. && cmake --build . -- -j8

A: Indeed your requirements are installed, but CMake doesn't know about it. Conan won't do it automatically, thus, you need to add the generator cmake_find_package in your list, which will provide the Findxxx.cmake files for your build:
generators = "cmake", "cmake_find_package"

What does cmake generator do?
It creates the file conanbuildinfo.cmake which contains all information required to build your package. However, you need to inject that file in the author's cmake file.
Take a look on Conan docs to learn more about that generator.


text: Q: Product page not found if product data is set Appointment Service I installed the booked plugin and integrated with Woocemmerce.  When I checked the product type to be appointments service, why was my product page not found on frontend.  where is the code i need to fix?  if you provide a solution, it is worth it


text:
Q: How to store values from Trident/Storm in a List (using the Java API) I'm trying to create a few Unit Tests to verify that certain parts of my Trident topology are doing what they are supposed to.
I'd like to be able to retrieve all the values resulting after running the topology and put them in a List so I can "see" them and check conditions on them.
   FeederBatchSpout feederSpout = new FeederBatchSpout("some_time_field", "foo_id");
   TridentTopology topology = new TridentTopology();
   topology.newStream("spout1", feederSpout)
    .groupBy(new Fields("some_time_field", "foo_id"))
    .aggregate(new Fields("foo_id"), new FooAggregator(),
               new Fields("aggregated_foos"))
    // Soo... how do I retrieve the "aggregated_foos" from here?

I am running the topology as a TrackedTopology (got the code from another S.O. question, thank you @brianghig for asking it and @Thomas Kielbus for the reply)
This is how I "launch" the topology and how I feed sample values into it:
TrackedTopology tracked = Testing.mkTrackedTopology(cluster, topology.build());
cluster.submitTopology("unit_tests", config, tracked.getTopology());

feederSpout.feed(new Values(MyUtils.makeSampleFoo(1));
feederSpout.feed(new Values(MyUtils.makeSampleFoo(2));

When I do this, I can see in the log messages that the topology is running correctly, and that the values are calculated properly, but I'd like to "fish" the results out into a List (or any structure, at this point) so I can actually put some Asserts in my tests.
I've been trying [a s**ton] of different approaches, but none of them work.
The latest idea was adding a bolt after the aggregation so it would "persist" my values into a list:
Below you'll see the class that tries to go through all the tuples emitted by the aggregate and would put them in a list that I had previously initialized:
class FieldFetcherStateUpdater extends BaseStateUpdater<FieldFetcherState> {
    final List<AggregatedFoo> results;

    public FieldFetcherStateUpdater(List<AggregatedFoo> results) {
        this.results = results;
    }

    @Override
    public void updateState(FieldFetcherState state, List<TridentTuple> tuples,
                            TridentCollector collector) {
        for (TridentTuple tuple : tuples) {
            results.add((AggregatedFoo) tuple.getValue(0));
        }
    }
}

So now the code would look like:
// ...
List<AggregatedFoo> results = new ArrayList();
topology.newStream("spout1", feederSpout)
    .groupBy(new Fields("some_time_field", "foo_id"))
    .aggregate(new Fields("foo_id"), new FooAggregator(),
               new Fields("aggregated_foos"))
    .partitionPersist(new FieldFetcherFactory(),
                        new Fields("aggregated_foos"),
                        new FieldFetcherStateUpdater(results));

     LOGGER.info("Done. Checkpoint results={}", results);

But nothing... The logs show Done. Checkpoint results=[] (empty list)
Is there a way to get that? I imagine it must be doable, but I haven't been able to figure out a way...
Any hint or link to pages or anything of the like will be appreciated. Thank you in advance.

A: You need to use a static member variable result. If you have multiple parallel tasks running (ie, parallelism_hint > 1) you also need to synchronize the write access to result.
In your case, result will be empty, because Storm internally, creates a new instance of your bolt (including a new instance of ArrayList). Using a static variable ensures, that you get access to the correct object (as there will be only one over all instances of your bolt).


text:
Q: Plot distances between points matlab I've made a plot of 10 points
10                       10
248,628959661970    66,9462583977501
451,638770451973    939,398361884535
227,712826026548    18,1775336366957
804,449583613070    683,838613746355
986,104241895970    783,736480083219
29,9919502693899    534,137567882728
535,664190667238    885,359450931142
87,0772199008924    899,004898906140
990                        990
With the first column as x-coordinates and the other column as y-coordinates
Leading to the following Plot:
Using the following code: scatter(Problem.Points(:,1),Problem.Points(:,2),'.b')

I then also calculated the euclidean distances using Problem.DistanceMatrix = pdist(Problem.Points);
Problem.DistanceMatrix = squareform(Problem.DistanceMatrix);
I replaced the distances by 1*10^6 when they are larger than a certain value.
This lead to the following table:

Then, I would like to plot the lines between the corresponding points, preferably with their distances, but only in case the distance < 1*10^6.
Specifically i want to plot the line [1,2] [1,4] [1,7] [2,4] etc.
My question is, can this be done and how?

A: Assuming one set of your data is in something called xdata and the other in ydata and then the distances in distances, the following code should accomplish what you want.
hold on
for k = 1:length(xdata)
    for j = 1:length(ydata)
        if(distances(k,j) < 1e6)
            plot([xdata(k) xdata(j)], [ydata(k) ydata(j)]);
        end
    end
end

You just need to iterate through your matrix and then if the value is less than 1e6, then plot the line between the kth and jth index points.  This will however double plot lines, so it will plot from k to j, and also from j to k, but it is quick to code and easy to understand.  I got the following plot with this.

A: This should do the trick:
P = [
    10.0000000000000  10.0000000000000;
   248.6289596619700  66.9462583977501;
   451.6387704519730 939.3983618845350;
   227.7128260265480  18.1775336366957;
   804.4495836130700 683.8386137463550;
   986.1042418959700 783.7364800832190;
    29.9919502693899 534.1375678827280;
   535.6641906672380 885.3594509311420;
    87.0772199008924 899.0048989061400;
   990.0000000000000 990.0000000000000
];
P_len = size(P,1);

D = squareform(pdist(P));
D(D > 600) = 1e6;

scatter(P(:,1),P(:,2),'*b');

hold on;

for i = 1:P_len
    pi = P(i,:);

    for j = 1:P_len
        pj = P(j,:);
        d = D(i,j);

        if ((d > 0) && (d < 1e6))
            plot([pi(1) pj(1)],[pi(2) pj(2)],'-r');
        end
    end
end

hold off;

Final output:

On a side note, the part in which you replaces the distance values trespassing a certain treshold (it looks like it's 600 by looking at your distances matrix) with 1e6 can be avoided by just inserting that threshold into the loop for plotting the lines. I mean... it's not wrong, but I just think it's an unnecessary step.
D = squareform(pdist(P));

% ...

if ((d > 0) && (d < 600))
    plot([pi(1) pj(1)],[pi(2) pj(2)],'-r');
end

A: A friend of mine suggested using gplot
gplot(Problem.AdjM, Problem.Points(:,:), '-o')

With problem.points as the coordinates and Problem.AdjM as the adjacency matrix. The Adjacency matrix was generated like this:
Problem.AdjM=Problem.DistanceMatrix;
Problem.AdjM(Problem.AdjM==1000000)=0;
Problem.AdjM(Problem.AdjM>0)=1;

Since the distances of 1*10^6 was the replacement of a distance that is too large, I put the adjacency there to 0 and all the other to 1.
This lead to the following plot, which was more or less what I wanted:

Since you people have been helping me in such a wonderful way, I just wanted to add this:
I added J. Mel's solution to my code, leading to two exactly the same figures:

Since the figures get the same outcome, both methods should be all right. Furthermore, since Tommasso's and J Mel's outcomes were equal earlier, Tommasso's code must also be correct.
Many thanks to both of you and all other people contributing!


text:
Q: Laravel 5.0 separated error messages for form validation I did define my validator rules like this:
foreach ($this->request->get('name') as $key => $val) {
            $rules['name.'.$key]    = 'required';
            $rules['phone.'.$key]   = 'required';
            $rules['comment.'.$key] = 'required';
        }
return $rules;

The problem is that i can't loop through, for example, name errors. All I can do is looping through them like this:
@foreach ($errors->all() as $error)
    {{ $error }}
@endforeach

I have 3 different input fields. How can I write out the errors separately beneath each input box?

A: Laravel does not offer the functionality to display the error messages individually for every field. You would have to figure out a manual way of doing this if you want the feature in your application.
Update
I don't know if this particular thing existed in earlier versions of Laravel, I sure never heard of it, but as of Laravel 5.2 you can display form validation error messages separately. Here is a good video that demonstrates the functionality on Laracasts.
Using your example, here is what the code would look like (Without any styling):
<input name='name'>
@if ($errors->has('name'))
    {{ $errors->first('name') }}
@endif

A: Your update solution works but if your validation returns more than one message it only shows the first one. If you want to give all the error information to the user you should do this:
@if ($errors->has('name'))
  @foreach($errors->get('name') as $error)
    {!! $error !!}
  @endforeach
@endif

I recommend to put this into a partial blade and @include it for each input you need just passing the $errors object and the name of the input.


text:
Q: Incrementing and padding in Javascript I'm trying to write an app that allows a user to increment a series of numbers. When I let i = 1, all is well and my sequence output is perfect. Unfortunately, the series will rarely start with 1, it will start with a user defined number. And that's where I'm getting hung up:

const totalEl = document.querySelector('#total');
const perEl = document.querySelector('#per');
const numEl = document.querySelector('#num');
const calculateEl = document.querySelector('#calculate');
const outputEl = document.querySelector('#output');

calculateEl.addEventListener('click', onCalculateButtonClick);

function onCalculateButtonClick() {
  const total = Number(totalEl.value);
  const numPerRoll = Number(perEl.value);
  const num = Number(numEl.value);
  const numPerBatch = numPerRoll * 2;

  const batches = Math.ceil(total / numPerBatch);
  let output = `Total batches: ${batches}\nTotal rolls: ${batches * 2}\n\n`;

  for (let i = 1; i <= batches; i++) {
    output += `Batch ${i}A -- ${(numPerBatch * (i - 1)) + 1}-${(numPerBatch * (i - 1)) + numPerRoll}\n`;
    output += `Batch ${i}B -- ${(numPerBatch * (i - 1)) + numPerRoll + 1}-${numPerBatch * i}\n`;
  }

  outputEl.innerText = output;
}
body {
  font-family: system-ui;
  background: linear-gradient(to bottom, azure, #a4ffff);
  color: black;
  height: 100vh;
  margin: 0;
  display: grid;
  }

 Generator 0.1

Please enter your values in the dashboard
 Note: in order to print a complete 2-up batch, the order may be rounded up

Order total <input id="total" value="50000"/>

Total per sequence <input id="per" value="1500"/>

Starting number <input id="num" value="1"/>

Prefix <input id="prefix" value="ABC"/>

<button id="calculate">Calculate</button>

How do I let i = a user defined number? I'm missing something fundamentally obvious here.
I also need to turn this number into a string (I think) and pad it out to 8 digits... I've tried adding something like this in with lots of hilarity, hair pulling and no results:
let num = i;
let text = num.toString();
let padded = text.padStart(8,"0");

I think what I tried was something like this:
for (let i = num; i <= batches; text = num.toString(); padded = text.padStart(8,"0"); {

I've got a kind of working version of this at codepen:
https://codepen.io/swartzfeger/pen/yLjgEpK
More in-depth dump of what I'm trying to accomplish
TL;DR What I need: generate a series of UPC codes that are incremented and split into batches.
Let's say our customer wants 10,000 UPCs, with 1000 UPCs per roll (these are being printed on film and wound onto rolls).
That would be a total of 10 rolls. But each 2x 1000 sequence can be printed at once, printing 2 up. So there are a total of 5 print batches.
That's not the hard part since the example is cut and dried. Most client jobs vary greatly, and we often have to print extra so we're not wasting film -- ie, we always want a full batch and not printing just 1 up for the batch. A partial batch would leave us with 1 roll of empty non-printed film.
ie, an order of 50,000 total, 1500 per sequence. 50k / 3000 per batch leaves us with 16.66 batches. So we would want to round that up to 17. So we would want to bump the print total to 51k (17 x 3000 = 51,000.
What I need to do is create a dashboard where the operator enters the job total (50,000) and the total per sequence (1500). The dashboard would then spit out you're running a job total of 51,000, 17 batches/34 rolls total. It would then give the operator the print breakdown --

*

*Batch 1A -- 0000-1500

*Batch 1B -- 1501-3000

*Batch 2A -- 3001-4500

*Batch 2B -- 4501-6000 etc

HOWEVER -- we would rarely begin a sequence with i =1 -- we would be picking up from where our last job ended, so the user would enter the new beginning sequence number. So I wouldn't be incrementing from 0 or 1, but an arbitrary number like 6293.
AND -- these numbers are of going to be a fixed length (usually 8 digits). So a starting sequence number of 6293 would have to be padded out to 00006293.

A: Make a small utility function like so:
const z = (number, size) => number.toString().padStart(size, "0");

Then assign some variables to the function's returns and then interpolate those variables into the template literals like so:
let A1 = z(AB, 8);
let A2 = z(AB + (now / 2) - 1, 8);
let B1 = z(AB + (now / 2), 8);
let B2 = z(AB + now - 1, 8);
output += `Batch ${z(i + 1, 2)}A -- ${A1}-${A2}\n`;
output += `Batch ${z(i + 1, 2)}B -- ${B1}-${B2}\n`;

I removed the for loop and added .reduce().
Details are commented in example

const genForm = document.forms.generator;
const fc = genForm.elements;
const totalFC = fc.total;
const perFC = fc.per;
const numFC = fc.num;
const outputFC = fc.output;

// Utility function for padding zeros
const z = (number, size) => number.toString().padStart(size, "0");

genForm.addEventListener('submit', onCalculate);

function onCalculate(e) {
  e.preventDefault();
  const total = Number(totalFC.value);
  const numPerRoll = Number(perFC.value);
  const init = Number(numFC.value);
  const numPerBatch = numPerRoll * 2;

  const batches = Math.ceil(total / numPerBatch);
  let output = `Total batches: ${batches}\nTotal rolls: ${batches*2}\n\n`;

  // Generate an array of batches
  const totalBatches = [...new Array(batches)].fill(numPerBatch);
  /**
   * On each iteration of totalBatches by .reduce()...
   * >AB< is the accumulator, it will keep track of it's own value
   * >now< is the current value (>numPerBatch<)
   * >AB< starts as >init<, defaulting to 1
   * >A1< - >A2< is >numPerRoll<
   * >B1< - >B2< is >numPerRoll<
   * >output< is rendered to display ranges A and B
   * >now< is added to >AB<
   * The returned value isn't used but needs to be defined so
   * that the accumulator returns on the next iteration increased
   */
  const final = totalBatches.reduce((AB, now, idx) => {
    let A1 = z(AB, 8);
    let A2 = z(AB + (now / 2) - 1, 8);
    let B1 = z(AB + (now / 2), 8);
    let B2 = z(AB + now - 1, 8);
    output += `Batch ${z(idx + 1, 2)}A -- ${A1}-${A2}\n`;
    output += `Batch ${z(idx + 1, 2)}B -- ${B1}-${B2}\n`;
    return AB + now;
  }, init);

  outputFC.innerText = output;
}
html {
  font: 300 2ch/1.15 'Segoe UI'
}

body {
  min-height: 100vh;
  margin: 0 auto;
  background: linear-gradient(to bottom, azure, #a4ffff);
}

form {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 20px;
}

fieldset {
  position: relative;
  width: min(70vw, 500px);
}

input,
button {
  font: inherit;
}

input {
  width: 12rem;
}

button {
  position: absolute;
  right: 30px;
  cursor: pointer;
}

label {
  display: flex;
  justify-content: space-between;
  margin: 0 20px 15px 0;
}

label sup {
  align-self: flex-start;
}

legend {
  font-size: 1.5rem;
}

legend b,
[type="number"],
output {
  font-family: Consolas;
}

[type="number"] {
  text-align: right;
}

.note {
  margin-left: 0.5ch;
  font-size: 0.75rem;
  text-indent: -1ch;
}

sup {
  color: tomato
}
<form id="generator">
  <fieldset>
    <legend>❚❘❘❙⦀Generator 0.1❚⦀⦀∥❙❙❘❘❘⦀∥</legend>

Please enter your values in the dashboard

    Order total⚝ <input id="total" type="number" value="50000"/>

    Total per sequence <input id="per" type="number" value="1500"/>
    Starting number <input id="num" type="number" value="1"/>
    Prefix <input id="prefix" placeholder="ABC"/>

    <button>Calculate</button>

⚝Note: in order to print a complete 2-up batch,
the order may be rounded up.

    <output id="output"></output>
  </fieldset>
</form>

A: The const z utility @zer00ne added cleaned things up for padding the digits
const z = (number, size) => number.toString().padStart(size, "0");

The user defined number sets the starting number of the sequence, and size determines the length in digits of the sequence. The "0" determines what the sequence will be padded with to reach the required final length.
ex, the user defines '123' as the starting the number of the sequence; const z turns this into '00000123' (an 8-digit sequence)
Defining the value >now< for the accumulator/iteration made things work flawlessly.
By using AB + now, the batches were able to increment properly:
// Generate an array of batches

const totalBatches = [...new Array(batches)].fill(numPerBatch);

// * On each iteration of totalBatches by .reduce()...
// * >AB< is the accumulator, it will keep track of it's own value
// * >now< is the current value (>numPerBatch<)
// * >AB< starts as >init<, defaulting to 1
// * >A1< - >A2< is >numPerRoll<
// * >B1< - >B2< is >numPerRoll<
// * >output< is rendered to display ranges A and B
// * >now< is added to >AB<
// * The returned value isn't used but needs to be defined so
// * that the accumulator returns on the next iteration increased

const final = totalBatches.reduce((AB, now, idx) => {
let A1 = z(AB, 8);
let A2 = z(AB + now / 2 - 1, 8);
let B1 = z(AB + now / 2, 8);
let B2 = z(AB + now - 1, 8);

and for the final output:
output += `Batch ${z(idx + 1, 2)}A | ${prefix} ${A1} - ${prefix} ${A2}\n`;
output += `Batch ${z(idx + 1, 2)}B | ${prefix} ${B1} - ${prefix} ${B2}\n`;
return AB + now;
}, init);

outputEl.innerText = output;
}


text:
Q: Why do we use "PipeTransform" in custom pipes? Here is my custom pipe:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'dc'
})
export class DcPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    if (!value) return value;

    return value.replace(/\w\S*/g, function(txt) {
      return txt.charAt(0).toLowerCase() + txt.substr(1).toUpperCase();
    });
  }
}

What's the purpose of using implements PipeTransform in a class declaration?
From what I see is working even without this part.

A: PipeTransform is an interface: https://angular.io/api/core/PipeTransform
Including it and using implements PipeTransform ensures that your class will implement the required transform method and conform to its interface (specifically requiring the first value parameter ... it doesn't do much else).
Conforming to the interface catches possible runtime errors (during transpile time) including but possibly not limited to:

*

*Not implementing transform at all

*Not returning a value from transform
This is similar to implements OnInit / ngOnInit. You don't have to implement it for the code to work, but it's a good practice.

A: Here is the API definition: https://angular.io/api/core/PipeTransform
Link to the code behind: https://github.com/angular/angular/blob/5.1.3/packages/core/src/change_detection/pipe_transform.ts#L1-L38
PipeTransform is a simple interface, it's describing what should be expected expectations of implementation, nothing more.


text:
Q: How to fetch values from Realtime Database Firebase that are not string values I have Linked my React Webapp to the Real-time Database of Firebase and am successfully fetching string values and displaying it on my webapp.
But when it comes to the Boolean values, I am not able to display them on the webapp interface. Although I am successful in fetching the data and can see the object received in the Console log.
export default class Webapp extends Component {
constructor(){
    super()
    this.state ={
      bloodConnect:'',
    }
    }

    componentWillMount=()=> {
    const rootRef = firebase.database().ref('machineOne');
       rootRef.on('value', snap=>{
          this.setState({
            bloodConnect: snap.val(),
          });
      });
    }

    render() {
    console.log('this.state',this.state.bloodConnect)

    return ({this.state.bloodConnect.Entry1})}

A: If you're fetching them that must be a problem with your client code.
Have you tried to display the boolean value as a string?
{ String( value ) }

You can also use ternary operator such as :
{myBooleanValue ? 'Its true' : 'Its false'}


text:
Q: Python Pandas get part of dataframe based on a mask I have a data frame that looks like this:
      TTL1     TTL2      TTL3       TTL4
0     val1     val2      val3       val4
1     val1     val2      val3       val4
2     val1     val2      val3       val4
3     val1     val2      val3       val4

and a mask that looks like this:
[[ 0 0 0 0 ]
 [ 0 0 1 0 ]
 [ 0 1 0 0 ]
 [ 0 0 0 0 ]]

I want to cut the main df, by the values of the mask: if there is 1 in a row, get the row.
so the output should be another dataframe that looks like this:
      TTL1     TTL2      TTL3       TTL4
1     val1     val2      val3       val4
2     val1     val2      val3       val4

I tried this line but it doesn't work:
df.loc[mask.any(axis=1)]

any ideas please?
thank you

A: try using loc with mask.any(1)
df.loc[mask.any(1)]

   TTL1  TTL2  TTL3  TTL4
1  val1  val2  val3  val4
2  val1  val2  val3  val4

setup
df = pd.DataFrame(
    {'TTL1': ['val1', 'val1', 'val1', 'val1'],
     'TTL2': ['val2', 'val2', 'val2', 'val2'],
     'TTL3': ['val3', 'val3', 'val3', 'val3'],
     'TTL4': ['val4', 'val4', 'val4', 'val4']}
)

mask = np.array([
        [0, 0, 0, 0],
        [0, 0, 1, 0],
        [0, 1, 0, 0],
        [0, 0, 0, 0],
    ])

A: I think you can omit loc, only is necessary same dimensions of array and df:
print (mask.shape)
(4, 4)
print (df.shape)
(4, 4)

print (df[mask.any(axis=1)])
  TTL1  TTL2  TTL3  TTL4
1  val1  val2  val3  val4
2  val1  val2  val3  val4

Same as:
print (df[mask.any(1)])
  TTL1  TTL2  TTL3  TTL4
1  val1  val2  val3  val4
2  val1  val2  val3  val4

Another possible problem from comment - string values instead int:
mask = np.array([[0, 0, 0, 0 ],
 [ 0, 0, 1, 0 ],
 [ 0, 1, 0, 0 ],
 [ 0, 0, 0, 0 ]]).astype(str)

mask = mask.astype(bool)
print (df[mask.any(1)])
   TTL1  TTL2  TTL3  TTL4
1  val1  val2  val3  val4
2  val1  val2  val3  val4

EDIT:
If string nan in values you can replace them:
mask = np.array(
[['0', 'nan', '0', '0'],
 ['0', '0', '1', '0'],
 ['0', '1', '0', '0'],
 ['0', '0', '0', 'nan']])

mask[mask == 'nan'] = 0
mask = mask.astype(bool)
print (mask)
[[False False False False]
 [False False  True False]
 [False  True False False]
 [False False False False]]

Or simplier:
mask = np.array(
[['0', 'nan', '0', '0'],
 ['0', '0', '1', '0'],
 ['0', '1', '0', '0'],
 ['0', '0', '0', 'nan']])

mask = mask == '1'
print (mask)
[[False False False False]
 [False False  True False]
 [False  True False False]
 [False False False False]]


text:
Q: Create a small menu in wordpress Hello i need to make a small menu like this
When i press the menu item, differend text is shown.  I am new on wordpress and html. Could somebody explai how to do that ? Maybe there is plugins ?

A: Follow this tutorial from Codex. This guide covers the basic tasks a user may carry out when using the built-in menu editor.
http://codex.wordpress.org/WordPress_Menu_User_Guide


text:
Q: Is there a LINQ-way to append the same character n-times to a string? I want to create a string repeating the same seqeuence n-times.
How I do this:
var sequence = "\t";
var indent = string.Empty;

for (var i = 0; i < n; i++)
{
    indent += sequence;
}

Is there a neat LINQ equivalent to accomplish the same result?

A: You can use Enumerable.Repeat in String.Concat:
string intend = String.Concat(Enumerable.Repeat(sequence, n));

If you just want to repeat a single character you should prefer the String-constructor:
string intend = new String('\t', n);


text:
Q: Check Duplicate Value in array javascript I need to check to 1 array value, if value duplicated, it will pop up alert.
Here is the function :
function checkDuplicateTenure(){
    var f = document.frmPL0002;
    var supplgrid = document.getElementById("mdrPymtGrid2");
    var len = (supplgrid.rows.length) - 1;

    for(var i=0;i<len;i++){
        if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
            alert("DUPLICATE LOAN TENURE IN MONTH(S)");
        }
    }

    return false;
}

That function is works if got duplicate value in array, but if all value is different, its will hit js error  if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) { Unable to get property 'value' of undefined or null reference.
Thanks

A: change it
for(var i=0;i<len-1;i++){
        if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
            alert("DUPLICATE LOAN TENURE IN MONTH(S)");
        }
    }

suppose your loop  runs 5 times and you can set i+1 inside the loop it comes 6 which is undefined index that why js error occurs

A: This is a simple out of bounds error. Fix it by using this:
for (var i=0;i<len-1;i++) {

So, i+1 will never be the same as len.

A: Try this:
function checkDuplicateTenure(){
    var f = document.frmPL0002;
    var supplgrid = document.getElementById("mdrPymtGrid2");
    var len = (supplgrid.rows.length) - 1;

    for(var i=0;i<len-1;i++){
        if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
            alert("DUPLICATE LOAN TENURE IN MONTH(S)");
        }
    }

    return false;
}


text:
Q: Java sftp file transfer for windows servers My requirements is-
To push the file into windows servers  from other windows server. Files will be near 1000s of in 1 batch and it will run these batches  to sftp locations
So i need to config multithreads to process these files
Issues :
The first thing i m picking  list of files from source directory  and that list i am iterating which is getting iterated successfully  like all the thread picking the file separately  nothing is colliding.
Then i need to connect  with sftp...
Heres the question.
I need create a separate  session for each thread right? And also separate channels to.
Is Jsch.jar SFTPConnection work for windows server to?
And the third when i am multithreading  and going to call
Channelsftp.put(src,des) its not putting  some pipe closed some time no file sometime inderoutbound exception some times input stream is closed. How to config that if possible? Like connection is created for each thread when it comes to putting  the file into sftp location its not working
Please if u have any push condition let me for multi threading it will help


text:
Q: Firebase auth JS with Flask I am struggling to understand Firebase authentication on the client/server side and have the question below.
I have a login.html page with a login-form and submit button. On the button click event, I have a JavaScript to do some client validation and perform the authentication):
btnSignIn.addEventListener('click', e => {
    // Get email/pass
    const email = inputEmail.value;
    const pass = inputPassword.value;
    /* to-do some validation and then sign in */
    // Sign in
    const promise = firebase.auth().signInWithEmailAndPassword(email, pass)
    promise.catch(e => console.log(e.message))
    }
});

This is working great so far. Now, once the user has logged in, I want to redirect to home.html page but since this page should be protected by authorized users, do I need to send the token to the server (which is a Flask app)?
How do I send the token from JS to my Flask app? I saw in the Firebase docs that the way to go is via ajax. From the documentation, this is how I should send the token but I am not sure how to implement it.
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
  // Send token to your backend via HTTPS
  // ...
}).catch(function(error) {
  // Handle error
});

My test Flask app:
@app.route('/')
@app.route('/home')
def home():
    return render_template("home.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
    return render_template("login.html")

A: You cannot simply transfer the token from your js code into flask.
What I suggest you do is implement firebase in your backend python code instead of your frontend js code. To start using the python firebase sdk, I recommend either using the docs. That link points to the authentication docs, since your question is authentication related. You should select python as the type of code you would like to work with when viewing the docs.
Here is a youtube video as well on firebase authentication with flask that I really liked:
https://www.youtube.com/watch?v=FCw5PFDb99k


text:
Q: iOS push notification with PyAPNs I'm trying to send push notification from my Python server to my iOS application, copy paste the sample code in Git.
from apns import APNs, Payload

apns = APNs(use_sandbox=True, cert_file='MyAppCert.pem', key_file='MyAppKey.pem')

# Send a notification
token_hex = MY_TOKEN_NUMBER
payload = Payload(alert="Hello World!", sound="default", badge=1)
apns.gateway_server.send_notification(token_hex, payload)

When calling the api from the browser I get the following error:
SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSLroutines:SSL_CTX_use_PrivateKey_file:system lib

*

*Where should I store the MyAppCert.pem MyAppKey.pem on the server?

*beside placing them in a folder do I need to do something else?

*should I set the entire path?


text:
Q: Getting ambiguous errors with svelte | ReferenceError: Utils is not defined I am wondering what are the best practices for debugging svelte applications. Most of the time I'm getting extremely ambiguous errors, or something referencing the compiled site.
This has lead me to find working with svelte rather stressful. Though I am maybe just doing it wrong?
Anyways, I started off from the official svelte ts degit template: https://svelte.dev/blog/svelte-and-typescript
and just as the detailed in the documentation I did:
npx degit sveltejs/template svelte-typescript-app
cd svelte-typescript-app
node scripts/setupTypeScript.js

And after making 2-3 components, I'm getting the following console error, my IDE shows nothing wrong (VSC with svelte plugin):
Uncaught ReferenceError: Utils is not defined
    at main.ts:5:2
(anonymous) @ main.ts:5

Now this is pointing to the main.ts file, let's see what's in it:
import App from './App.svelte';

const app = new App({
    target: document.body,
});

export default app;

Well, no Utils for sure and after browsing around the svelte docs, the App component shouldn't even take an argument named 'Utils'.
What am I doing wrong, how to fix it and how can I debug better with svelte.

A: Svelte does a lot of things internally, so one line of source can correspond with many lines of compiled output. This sometimes makes relying on errors referencing the original source not a viable option.
If the error references something you do not recognize, look at the actual compiled output running in the browser. Depending on what browser you use, you may have to disable source maps to have stack traces point to the real error site. I have them turned off most of the time because of how unhelpful they can be.
You may then also be able to stop the debugger on error so you can inspect the current state of the scope and see what is being referenced and read.

A: Check if your VSC has not injected an unwanted import statement in script section in any component...I had same issue until I discovered VSC had, for some reason, auto inserted code below
 import { identity } from 'svelte/types/runtime/internal/utils';


text:
Q: Is it possible make predicate from List? I use SWI-Prolog
I have lists like this
[sunny,hot,high,weak,no]

and
[outlook,temperature,humidity,wind,play_tennis]

I want to make a predicate like
run(no,  [outlook=sunny,    temp=hot,  humidity=high,   wind=weak  ]).

Is it possible?

A: Yes, but you're going to have to implement the appropriate machine learning algorithm (your example looks identical to the ones found in Mitchell's machine learning book, is this a homework assignment?).
Note that you can use the =.. operator to turn a list into a predicate, which might help you if I've misunderstood your original question. In other words, A=..[a,b,c] binds a(b,c) to A


text:
Q: AWS Cognito Accepting Any Password I am implementing AWS with an Android application for the first time.
We would like to use Cognito to authenticate our users, and selectively provide data from DynamoDB.
I have successfully set up my user pool and can see new registrations appear in the user list.  Trying to login with an email that does not exist fails.
However, Cognito always logs in with a valid email address, regardless of password input.
What is wrong with my process?
public class CognitoController extends Application {
    static CognitoUserPool pool;
    static String userEmail;
    public void onCreate(){
        super.onCreate();
        pool = new CognitoUserPool(this,
                "us-east-xxxx",
                "xxxx",
                "xxxx",
                new ClientConfiguration(),
                Regions.US_EAST_1);
    }
}

-
private void actionAdminLogin(){
        UtilityInterfaceTools.hideSoftKeyboard(AdminLoginActivity.this);
        String inputEmail = ((EditText) findViewById(R.id.input_admin_email)).getText().toString();
        String inputPassword = ((EditText) findViewById(R.id.input_admin_password)).getText().toString();
        CognitoController.userEmail = inputEmail;
        details = new AuthenticationDetails(inputEmail, inputPassword, null);

        AuthenticationHandler auther = new AuthenticationHandler() {
            @Override
            public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
                Toast.makeText(AdminLoginActivity.this, "Congratulations It Works...", Toast.LENGTH_LONG).show();
                startActivity(new Intent(AdminLoginActivity.this, AdminPortalActivity.class));
                finish();
            }

            @Override
            public void getAuthenticationDetails(AuthenticationContinuation continuation, String email) {
                continuation.setAuthenticationDetails(details);
                continuation.continueTask();
            }

            @Override
            public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
                continuation.continueTask();
            }

            @Override
            public void authenticationChallenge(ChallengeContinuation continuation) {
                continuation.continueTask();
            }

            @Override
            public void onFailure(Exception exception) {
                TextView errorMessage = findViewById(R.id.message_invalid_credentials);
                errorMessage.setText(exception.toString());
                errorMessage.setVisibility(View.VISIBLE);
            }
        };
        CognitoController.pool.getUser(inputEmail).getSessionInBackground(auther);
    }

A: I think your problem (which is not a problem by the way) is either:

*

*In your pool Cognito setting, you chose your devices to be remembered.

Remembered
devices are also tracked. During user authentication, the key and secret pair assigned to a remembered device is used to authenticate the device to verify that it is the same device that the user previously used to sign in to the application. APIs to see remembered devices have been added to new releases of the Android, iOS, and JavaScript SDKs. You can also see remembered devices from the Amazon Cognito console.

*The token is already cached:

Caching
The Mobile SDK for Android caches the last successfully authenticated user and the user's tokens locally on the device, in SharedPreferences. The SDK also provides methods to get the last successfully authenticated user.

Your Application Update
In fact for better user experience, you want the user to use the app, and don't need to login every time that she wants to use your app (e.g., look at mail apps, social media apps, etc.). However, you application need to handle that, you have two choices here:

*

*Redirect to login if necessary: If the user is already logged in and wants to use the application again, your app needs to verify the user against the Cognito user pool, and only then, redirect the user to the login page if necessary.

*Remove the token: If you really want the user to login every time that she uses the application, then remove the token if the user signs out; but I do not recommend this, for the sake of user experience.


text:
Q: Why does my program crash after entering an integer? - C I'm extremely new to C coding and i'm wondering why this is crashing like this? After I input a value and press enter, my program instantly crashes. I remember learning there are times when you use a & with an array in the scanf line and sometimes you don't. So when I remove the & it crashes instantly. I'm not sure how to troubleshoot this problem and would appreciate help.
What i'm trying to accomplish:

*

*"Write a program that asks the user to enter a sequence of integers terminated by 0 ( the last number is 0)  and prints all the numbers entered on one line."

*The program crashes before I can enter the other variables. I was not done coding but since it keeps crashing instantly I can't go further.
 int main () {
       int ru[1000];
       int read;
       int nums;
       int counts;

       printf("Enter integers, press 0 to end user input \n");

       while (nums>0) {
           scanf("%d",&ru[nums]);

           if (nums==0)
               printf("%d ", ru[nums]);
       }

      system("pause>nul");
      return 0;
 }

A: As noted by several people already, you don't ever assign a value to nums at any point in your code, but make use of it in several places.
You should populate nums and whilst it's more than zero (this should probably be not equal to zero if you want to also include negative integers), store it's value into your array. You can track where you are in the array using another variable (I've picked the read one that you'd already declared), making sure that it is first initialised to 0.
Once the while loop is terminated, either by nums being zero or you filling up the array, you can then print out the numbers you've collected.
int main (void) {
   int ru[1000];
   int read=0;
   int nums;
   int counts;

   printf("Enter integers, press 0 to end user input \n");

   scanf("%d",&nums);
   while ((nums>0)&&(read<1000)) {
       ru[read++]=nums;
       scanf("%d",&nums);
   }
   for(counts=0;counts<read;counts++) {
       printf("%d ",ru[counts]);
   }
   printf("\n");

   system("pause>nul");
   return 0;
}

A: The scanf() you are using as the following prototype:
int scanf(const char *format, ...);

you should give the de pointer to the buffer variable as a parameter but your are giving a pointer to an array (pointer to a pointer).:
scanf("%d",&ru[nums]);

A solution to your problem might be:
 #include <stdio.h>
 #include <stdlib.h>
 int main ()
 {
        int ru[1000];
        int i = 0;
        printf("Enter integers, press 0 to end user input \n");
        do
        {
            scanf("%d",&ru[i]);
        }while (ru[i]!= 0 && i++ < 1000);
        for(i = 0; ru[i] != 0 ; i++)
            printf("%d ", ru[i]);
        return EXIT_SUCCESS;
  }


text:
Q: Vertical (rotated) text in HTML table headers My table headers are much wider than the data in the table, so I am trying to rotate the text in the headers to save space.
I've been trying out the suggestions in this question, and I've also taken a look at this and this.
However, none of the answers seem to actually work: here is my attempt in a JSFiddle.

The text can rotate, but the  elements don't resize properly, which was the whole point of trying to rotate the text.
Now that it's been 2-4 years since those questions have been asked, are there any new solutions to this problem?

A: You could use CSS to select the thead and size the rows accordingly:
DEMO: http://jsfiddle.net/uo44ub6L/
CSS:
thead th {
    height: 130px;
}

Another method would be to use rowspan="5" to create a larger th but you would need to add some blank rows, and you would get the same effect. Either would work.
If you need to do this dynamically, you could use javascript to select the th and adjust the size on the span length and font size.

A: You can use
writing-mode: vertical-rl; text-orientation: mixed;
this will get the work done for you , Here is JSFiddle of it .

A: This is now possible without any browser specific transforms that you used in your attempt. Note that the wrapping span is required as of 2022 in order to get firefox in particular to center the rotated text within the column (webkit does this by default). I also suggest you rotate the text at a slight angle as demonstrated here as it (IMHO) makes it easier to read.

    Display
    Year made (TV?)
    Native Res

    Dell U2410 (game)
    2010
    1080p

    Dell U2410 (sRGB)
    2010
    1080p

     Sony 40VL130 (game)
    2008
    1080p


text:
Q: jTable jQuery plugin why is my MySQL stored procedure failing? I am trying to implement a filter in jTable.  Here is the jTable Filtering Demo.
I used the jQuery code supplied by the demo to sucessfully send POST data to the listAction php script.  I access this data and assign it to the $filter variable.  I also add two wildcards before and after the string to tell MySQL to perform a comprehensive search rather then an index search.
    $filter = '%';
    $filter .= $_POST['name'];
    $filter .= '%';
    $startIndex = $_GET['jtStartIndex'];
    $pageSize = $_GET['jtPageSize'];
    $sorting = $_GET['jtSorting'];

I then call the stored procedure and pass in each variable.  I removed actual database and procedure name, but I verified they are correct.
$mysqli->query("USE data;");
$res = $mysqli->query("CALL proced($startIndex, $pageSize, $filter);");

$res returns false here.
Calling Stored Procedures DEFINITELY works as I have other functionalities working this way.  I have other Stored Procedures working that simply return 0 to 9 records correctly. Here is the current Stored Procedure code:
CREATE DEFINER=`root`@`localhost` PROCEDURE `proced`(startIndex INTEGER, pageSize INTEGER, filter VARCHAR(255))
BEGIN
    SELECT * FROM reports
    WHERE `new`=0 AND ReportingName LIKE filter
    ORDER BY idReports ASC
    LIMIT startIndex, pageSize;
END

Passing in values in MySQL workbench works and the query returns the correct rows:
call proced(
    0,
    10,
    'Art%'
);

But jTable fails with "An error occured while communicating to the server."
Can anyone point me in the right direction?

A: Got this working by getting an error back from MySQL:
if(!$res){
    ChromePhp::log($mysqli->error);
    die('error ['. $mysqli->error . ']');

}

Error:
Unknown column 'Art' in 'field list'

Solution(copied from link):
Try using different quotes for "Art" as the identifier quote character is the backtick ("`"). Otherwise MySQL "thinks" that you point to a column named "Art".
See also MySQL 5 Documentation
So simply by adding single quotes to the passed in String parameter works:
CALL procedure('$filter');


text:
Q: apache2 not loading a php script with form upload, but can load php file without form upload i put this code at /var/www/html as index.php and i chmod 777 to this file
    <?php
if(isset($_POST['btn-upload']))
{
    $img = rand(1000,100000)."-".$_FILES['img']['name'];
    $img_loc = $_FILES['img']['tmp_name'];
    $folder="uploads/";
    if(move_uploaded_file($img_loc,$folder.$img))
    {
        echo "<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3Ealert('Upload%20Sukses!!!')%3B%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="


text:
Q: I want to write Chinese in excel by python but my system is ASCII I want to write Chinese in excel by python but my system is ASCII
        newdf["產業類別"]=df.iloc[:,0]
        newdf["公司代碼"]=df.iloc[:,1]
        newdf["公司"]=df.iloc[:,2]

The Result will like this
Can I type it by ASCII code to let it show Chinese in Excel
Or have any other way to solve that?


text:
Q: SentenceCase in Javascript I want to make sentence case with JavaScript.
Input:
hello
world
example

I have tried this so far:
   $('.sentenceCase').click(function(event) {
        var rg = /(^\w{1}|\.\s*\w{1})/gi;
        var textareaInput=$('.textareaInput').val();
        myString = textareaInput.replace(rg, function(toReplace) {
            return toReplace.toUpperCase();
        });

       $('.textareaInput').val(myString);
   });

If I input: my name is hello. i have a pen my output is alright. (Output: My name is hello. I have a pen)
But for the first example, the output of my code is:
Hello
world
example

I want the output to be:
Hello
World
Example

How can I do that? (After any fullstop "." the letter will be capital letter)

A: Try this:
$('.sentenceCase').click(function(event) {
    var rg = /(^\w{1}|\.\s*\w{1}|\n\s*\w{1})/gi;
    var textareaInput=$('.textareaInput').val();
    myString = textareaInput.replace(rg, function(toReplace) {
        return toReplace.toUpperCase();
    });
 $('.textareaInput').val(myString);
 });

In your code, you are checking for fullstop(.), but your text contains the new line character. That is the issue.

In this Regex, it will look  for the first character in the beginning as well as after '.' and '\n' in the string.

A: You only care if the letter is the first letter in a group, so...
/\b\w/g

Matches the word-character that comes after a word boundary - i.e. the first letter in each word.


text:
Q: How to handle and log error in Javascript in Large SPA I am new to Javascript ,  I was wonder like we log error in Server Side programming language in a error.log file . for example in PHP there we can set a error file to log the errors .
Is there a way to do this in Large SPA in Javascript or we just log in console using
console.log()
I have this simple app which loads some json data from API and I have just used the normal alert and console.log methods to show error I would like to know whats the best way to do this.
I understand that I can write a Web Service which can be called every time an error being thrown and using the
window.error or element.error function probably I can send error report to the server where I will write on a log file.
But is Doing rest call on every error thrown is a good way?
Thanks

A: Browsers won't allow you to write on a file in client so You have to use ajax and write a log on server.
Sending errors to server using ajax is a good solution.
Also throwing error with alert is not appreciated by any user.


text:
Q: I have an error in ubuntu 14.04 Emm... I'm Mexican, my English isn't good, but I need help, the problem is:
I can't see my apps, when I try it, I see this:

Another thing:
When I try to use sudo apt-get update or sudo apt-get upgrade the console closes.
I don't know if this problem is related. This problem appeared 3 or 2 days ago, I installed ubuntu 14.04 a... one week ago maybe

A: Try this commands:
rm ~/.cache/software-center -R

and then
unity --reset &

This should solve your problem


text:
Q: Puppet: how to add a line to an existing file Edit: The example below is correct and works perfectly. But for some reason it was not working for me at the first time and then I did vagrant provision and then everything worked perfectly.
I am trying to add a line to an existing file /etc/fuse.conf. I tried this
added a folder two folders under modules directory
sudo mkdir /etc/puppet/modules/test
sudo mkdir /etc/puppet/modules/test/manifests

Then created a test.pp file and added following lines
sudo vim /etc/puppet/modules/test/manifests/test.pp

file { '/etc/fuse.conf':
  ensure => present,
}->
file_line { 'Append a line to /etc/fuse.conf':
  path => '/etc/fuse.conf',
  line => 'Want to add this line as a test',
}

After that I ran this command
puppet apply /etc/puppet/modules/test/manifests/test.pp

Then I opened this file /etc/fuse.conf and there was no change in the file. The line was not added to the file. I don't understand what I am missing here. How can I do this? I am learning puppet. So this is only for learning purpose.

A: For file_line the Puppet Labs standard library has to be installed.
See https://puppet.com/blog/module-of-week-puppetlabs-stdlib-puppet-labs-standard-library for more information.

A: You can try this:
exec {'exec_name':
    command => 'bash -c "echo foo_bar" >> /path/to/file',
    path    => '/bin',
     }
Tried most of the of the options and they all disappointed me.

A: Try this
file { '/etc/fuse.conf':
  ensure => present,
}->
if "test `grep -q 'Want to add this line as a test' /etc/fuse.conf | wc -l` -eq 0" {
  exec { 'echo "Want to add this line as a test" >> /etc/fuse.conf':
       }
}


text:
Q: Efficient All substring counting in sorted order You are given a string find the frequency of all substring sorted(decreasing order) according to there frequency.
Eg: ababa
{"a", "b", "a", "b", "a", "ab", "ba", "ab", "ba", "aba", "bab", "aba", "abab", "baba", "ababa"}.
output:
3,2,2,2,2,1,1,1,1
explanation
3 a
2 b
2 ba
2 aba
2 ab
1 abab
1 baba
1 ababa
1 bab
solution
1)one obvious solution is to keep all the string in hash map and count it
frequency but it will take o(n^3logn) O(n^2 *n){n^2 number of substring *O(n) for comparision of string *logn(as map is maintened as Red black tree)}
2)Insert all substring in Ternary search tree then retrive frequency of each substring then sort the frequency O(n^3 logn)
I am wondering is there O(n^2) or O(nlogn) solution exsist.
like this http://www.quora.com/Given-a-string-how-do-I-find-the-number-of-distinct-substrings-of-the-string

A: An O(n^2) solution can be achieved in this way:

*

*Insert all substrings into a trie. This can be done in O(n^2).

*Obtain all frequency and sort them.
Note that the frequency of any substring can only be in range [0, n], so a bucket sort can have all of the numbers sorted in O(n^2) since in the worst case there will be n^2 numbers.


text:
Q: Eclipse: How to see methods supported by variable's type during debugging ? During editing Eclipse gives suggestions for the methods that I can call on a variable. Is there a way to see those suggestions during debugging, maybe in the variables window or maybe in some other perspective ?

A: No, there isn't...you should always use the editor and the content assistant (be careful don't change source code otherwise the debugger will complain)

A: Found the answer, I just needed to click on Show Type Hierarchy


text:
Q: Cohen algebra (generalization)
Let Bor($X$) = class of all borel subsets of $X$. Cohen algebra is defined as Bor(X) modulo the ideal of meager sets.

The Cohen algebra has a combinatorial : it is the unique atomless complete Boolean algebra with a countable dense subset, (i.e it is a completion of a countable dense Boolean subalgebra). This case is true when $X=2^\omega$.

(1)  My first question is: does this characterization true when $X=2^\kappa$ for an infinite $\kappa$.
(2)  Is there any characterization (unique like above one) for random algebra (= Bor($X$) modulo the ideal of Lebesgue measure zero set) even when when $X=2^\omega$.

Thanks in advance

A: Regarding question $1$, it seems that you want to know whether
you've got the unique complete c.c.c. Boolean algebra with density
$\kappa$. The answer is no.
On the one hand, the forcing notion $\text{Add}(\omega,\omega_1)$
to add $\omega_1$ many Cohen reals is c.c.c. and has density
$\omega_1$. This is another way to describe your algebra in the case $\kappa=\omega_1$.
But meanwhile, forcing with a Suslin tree is also c.c.c. and has
density $\omega_1$. But these two complete Boolean algebras are not
isomorphic, since forcing with the Suslin tree adds no reals and in fact is
$\leq\omega$-distributive, whereas clearly
$\text{Add}(\omega,\omega_1)$ adds reals.
Of course, there may not be a Suslin tree, but consider the
forcing to add a single Cohen real (which creates a Suslin tree),
followed by the forcing to force with that Suslin tree. This is
the iteration of two c.c.c. forcing notions, and is hence c.c.c.,
but under CH has density $\omega_1$. But this forcing is not
isomorphic to $\text{Add}(\omega,\omega_1)$, since the latter
forcing is absolutely c.c.c., but the former is not, as the branch
through the Suslin tree creates an uncountable antichain in the
extension.
One may omit the CH assumption by taking the case
$\kappa=\mathfrak{c}$. That is, compare the forcing to add
continuum many Cohen reals, versus the forcing to add this many
Cohen reals, and afterwards also to force with the Suslin tree
created by the first one. Both of these are c.c.c. and have
density $\mathfrak{c}$, but they are not isomorphic since the
former remains c.c.c. in the forcing extension and the latter does
not.

A: There is a characterization of what you call a random algebra found in [1][Ch. 15. Sec 3]. This characterization involves the notion of a measure algebra.
We define a measure algebra to be a Boolean algebra $B$ along with a function $\mu:B\rightarrow[0,\infty)$ such that $\mu(a)=0$ if and only if $a=0$ and $\mu(\bigvee_{n}a_{n})=\sum_{n}\mu(a_{n})$ whenever $a_{i}\wedge a_{j}=0$ for $i\neq j$. Clearly, the random algebra is a measure algebra.
Every measure algebra $(B,\mu)$ can be endowed a metric $d$ where $d(a,b)=\mu((a\wedge b')\vee(a'\wedge b))$ for all $a,b\in B$. This metric is always a complete metric. Since $(B,\mu)$ becomes a metric space with the metric $d$, we may talk about topological properties of $(B,\mu)$.
Let $\mathcal{A}$ denote the $\sigma$-algebra of Lebesgue measurable sets on $[0,1]$(or $2^{\omega}$) and let $\mathcal{I}$ denote the ideal of sets of measure $0$. Let $m$ be the Lebesgue measure on $(\mathcal{A}/\mathcal{I},m)$. Then $(\mathcal{A}/\mathcal{I},m)$ is up to isomorphism of measure algebras the unique atomless separable (as a metric space) measure algebra with $m(1)=1$.
One can also give a purely combinatorial characterization of the random algebra that does not refer to measures. In the paper [2], Thomas Jech gives various characterizations of the Boolean algebras $B$ such that there is a function $\mu:B\rightarrow[0,\infty)$ where $(B,\mu)$ is a measure algebra. We shall therefore add conditions to Jech's characterization of measure algebras that guarantee that the measure algebra is isomorphic to the random algebra.
$\mathbf{Theorem}$ $\mathbf{1}$ A measure algebra $(B,\mu)$ is isomorphic to the random algebra if and only if $B$ is atomless and there is a countable subset $D\subseteq B$ such that for each $b\in B$ there are $R_{n}\subseteq D$ for natural numbers $n$ where $b=\bigwedge_{n}\bigvee R_{n}$.
$\mathbf{Proof}$ $\leftarrow$. Let $\mathcal{B}$ be a countable basis for the topology on $[0,1]$. Then for each Borel set $B$ there is a sequence of open sets $U_{n}$ where $B\subseteq\bigcap_{n}U_{n}$ and $m((\bigcap_{n}U_{n})\setminus B)=0$. Since $\mathcal{B}$ is a basis, for all $n$ there is some $\mathcal{R}_{n}\subseteq\mathcal{B}$ with $U_{n}=\bigcup\mathcal{R}_{n}$. Therefore, the sets $B$ and $\bigcap_{n}\bigcup\mathcal{R}_{n}$ differ only by a set of measure zero. By taking the Borel sets modulo the measure zero sets, we conclude there is a countable subset $D$ of the random algebra $B$ such that for each $b\in B$ there is some $R_{n}\subseteq D$ for all $n$ such that $b=\bigwedge_{n}\bigvee R_{n}$.
$\rightarrow$. Assume that $(B,\mu)$ is an atomless measure algebra such that there is a countable dense subset $D\subseteq B$ where for each $b\in B$ there are $R_{n}\subseteq D$ for natural numbers $n$ where $b=\bigwedge_{n}\bigvee R_{n}$. To show that $(B,\mu)$ is isomorphic to the random algebra, it suffices to prove that $B$ is separable as a metric space. Let $E$ be the Boolean subalgebra of $D$ generated by $B$. Then $E$ is a countable subset of $B$. We claim that $E$ is a dense subset of $B$ as well.
Let $b\in B$. Then there are $R_{n}\subseteq D$ for each $n\geq 0$ such that $b=\bigwedge_{n=0}^{\infty}\bigvee R_{n}$. For all $n\geq 0$, let $S_{n}=\{a_{0}\wedge...\wedge a_{n}|a_{0}\in R_{0},...,a_{n}\in R_{n}\}$. Then $S_{n}\subseteq E$ for all $n$, and $\bigvee S_{n}=(\bigvee R_{0})\wedge...\wedge(\bigvee R_{n})$ for $n\geq 0$. Therefore the sequence $(\bigvee S_{n})_{n}$ is a decreasing sequence with $\bigwedge_{n}\bigvee S_{n}=\bigwedge_{n=0}^{\infty}\bigvee R_{n}=b$. Therefore, we have $^{Lim}_{n\rightarrow\infty}\bigvee S_{n}=b$ in the topology given by the metric defined on any measure algebra. Furthermore, for all $n$, we have $\lim_{T\subseteq S_{n},T\,\textrm{is finite}}\bigvee T=\bigvee S_{n}$, so there is a finite subset $T_{n}\subseteq S_{n}$ such that $d(\bigvee T_{n},\bigvee S_{n})<\frac{1}{n}$. Therefore, we have
$^{\lim}_{n\rightarrow\infty}\bigvee T_{n}=b$. However, since $\bigvee T_{n}\in E$ for all $n$, we conclude that $E$ is a dense subset of $B$. We conclude that $(B,\mu)$ is a separable atomic measure algebra, so $(B,\mu)$ is isomorphic to the random algebra. QED
By combining the above characterization of the measure algebras which are isomorphic to the random algebra and Jech's characterizations of the measure algebras, we have the following algebraic characterizations of the random algebra that do not make any reference to measures, but we first need to give some definitions.
A Boolean algebra $B$ is said to be weakly distributive if for every sequence $(p_{n})_{n}$ of partitions of $B$ there is a partition $p$ of $B$ such that for each $a\in p$ the set $\{b\in p_{n}|a\wedge b>0\}$ is finite for each $n$.
A subset $r\subseteq B^{+}=B\setminus\{0\}$ is said to be a cellular family if $a\wedge b=0$ whenever $a,b\in r$ and $a\neq b$ (I should note that Jech calls cellular families antichains in [2]. ).
In a $\sigma$-complete Boolean algebra, we let $\overline{\lim}_{n\rightarrow\infty}a_{n}=\bigwedge_{n=0}^{\infty}\bigvee_{k=n}^{\infty}a_{k}$.`
A $\sigma$-complete Boolean algebra $B$ is said to be uniformly concentrated if there is a function $F$ where $f(c)\in c$ for each cellular family $c$ such that if $c_{n}$ is a finite cellular family with $|c_{n}|\geq 2^{n}$ for all $n$, then $^{\lim}_{n\rightarrow\infty}F(c_{n})=0$.
$\mathbf{Theorem}$ $\mathbf{2}$ Let $B$ be a $\sigma$-complete Boolean algebra. Then the following are equivalent.
I. $B$ is isomorphic to the random algebra.
II. $B$ satisfies the following properties.
$\phantom{spa}$ i. $B$ is atomless.
$\phantom{spa}$ ii. $B$ is weakly distributive
$\phantom{spa}$ iii. there is a countable subset $D\subseteq B$ such that if $b\in B$, then there is a sequence $(R_n)_n$ of subsets of $D$ such that $b=\bigwedge_{n}\bigvee R_{n}$.
$\phantom{spa}$ iv. there is a sequence $(C_{n})_{n}$ of subsets of $B$ with $B^{+}=\bigcup_{n}C_{n}$ and where
$\phantom{spaces}$ a. For all $n$ there is an integer $K(n)$ such that every cellular family in $C_{n}$ has at most $K(n)$ elements.
$\phantom{spaces}$ b. If $a_{n}\not\in C_{n}$ for all $n$, then $\overline{Lim}_{n\rightarrow\infty}a_{n}=0$.
III. The Boolean algebra $B$ satisfies the following.
$\phantom{spa}$ i. $B$ is atomless
$\phantom{spa}$ ii. there is a countable subset $D\subseteq B$ such that if $b\in B$, then there is a sequence $(R_n)_n$ of subsets of $D$ such that $b=\bigwedge_{n}\bigvee R_{n}$.
$\phantom{spa}$ iii. there is a sequence $(C_n)_n$ of subsets of $B$ with $B^{+}=\bigcup_{n}C_{n}$ such that
$\phantom{spaces}$ a. For all $n$ there is an integer $K(n)$ such that every cellular family in $C_{n}$ has at most $K(n)$ elements.
$\phantom{spaces}$ b. If $a_{n}\not\in C_{n}$ for all $n$, then $\overline{Lim}_{n\rightarrow\infty}a_{n}=0$.
$\phantom{spaces}$ c. For all $k$, if $\overline{Lim}_{n\rightarrow\infty}a_{n}=0$, then $a_{n}\in C_{k}$ for all but finitely many $n$.
IV. $B$ satisfies the following.
$\phantom{spa}$ i. $B$ is atomless.
$\phantom{spa}$ ii. there is a countable subset $D\subseteq B$ such that if $b\in B$, then there is a sequence $(R_{n})_{n}$ of subsets of $D$ such that $b=\bigwedge_{n}\bigvee R_{n}$.
$\phantom{spa}$ iii. $B$ is weakly distributive.
$\phantom{spa}$ iv. $B^{+}=\bigcup_{n}C_{n}$ for some sequence $C_{n}$ of sets where
$\phantom{spaces}$ a. For all $n$ there is an integer $K(n)$ such that every cellular family in $C_{n}$ has at most $K(n)$ elements.
$\phantom{spaces}$ b. If $a\vee b\in C_{n}$, then $a\in C_{n+1}$ or $b\in C_{n+1}$.
V. $B$ satisfies the following.
$\phantom{spa}$ i. $B$ is atomless.
$\phantom{spa}$ ii. there is a countable subset $D\subseteq B$ such that if $b\in B$, then there is a sequence $(R_{n})_{n}$ of subsets of $D$ such that $b=\bigwedge_{n}\bigvee R_{n}$.
$\phantom{spa}$ iii. $B$ is weakly distributive.
$\phantom{spa}$ iv. $B$ is uniformly concentrated.
$\mathbf{Proof}$ Simply combine the characterizations of measure algebras in [2] with Theorem 1. QED
We may also use [2] to get similar representations of the measure algebras produced by the standard measure on $2^{\kappa}$ for all cardinals $\kappa$ using Jech's results and Maharam's theorem. In order to state Maharam's theorem we will need a couple definitions.
If $B$ is a Boolean algebra, then recall that $B\upharpoonright a$ is the relative Boolean algebra $\{b\in B|b\leq a\}$.
If $B$ is a complete Boolean algebra, then we say that $X\subseteq B$ completely generates $B$ if whenever $X\subseteq C\subseteq B$ and $C$ is a complete subalgebra of $B$, then $C=B$. Let $\tau(B)=\min\{|X|:X\subseteq B,X\,\textrm{completely generates}\,B\}$.
We say that a complete Boolean algebra $B$ is $\tau$-homogeneous if $\tau(B)=\tau(B\upharpoonright a)$ for each $a\in B^{+}$.
Let $\mu_{\kappa}$ be the standard measure on $2^{\kappa}$. Let $Bor_{\kappa}$ denote the set of Borel subsets of $2^{\kappa}$ and let $I_{\kappa}$ be the Borel subsets of $2^{\kappa}$ of measure zero. Let $P_{\kappa}=Bor_{\kappa}/I_{\kappa}$, and let $\tilde{\mu}_{\kappa}$ denote the measure on the Boolean algebra $P_{\kappa}$ induced by $\mu_{\kappa}$.
$\mathbf{Theorem}$ $\mathbf{3}$(Maharam)(see [3][Ch. 22 Sec. 3]) If $(B,\mu)$ is a $\tau$-homogeneous measure algebra with $\tau(B)=\kappa$ and $\mu(1)=1$. Then $(B,\mu)$ is isomorphic as a measure algebra to $(P_{\kappa},\tilde{\mu}_{\kappa})$.
Therefore, if we combine Maharam's theorem with the characterizations of the measure algebras given by Jech in [2], then we obtain purely algebraic characterizations of the algebras $P_{\kappa}$.
References.

*

*H.L. Royden, Real analysis, Third edition (1988).

*Jech, Thomas. Algebraic characterizations of measure algebras. Proc. Amer. Math. Soc.
136 (2008), no. 4, 1285–1294.

*Monk, J. Donald, Robert Bonnet, and Sabine Koppelberg. Handbook of Boolean Algebras. Vol. 1-3. Amsterdam: North-Holland, 1989.

A: I was skimming through the handbook of set theory, and I stumbled upon a combinatorial characterization of the Cohen algebras $Ro(2^{\kappa})$ where $\kappa$ is any infinite cardinal and $2^{\kappa}$ is given the product topology. Recall that a Boolean subalgebra $A$ of a Boolean algebra $B$ is a regular subalgebra if $\bigvee^{A}R=1$ implies that $\bigvee^{B}R=1$ as well.
Suppose that $\kappa$ is a regular cardinal and $X$ is a set with $\kappa\leq|X|$. Let $[X]^{<\kappa}=\{R\subseteq X:|R|<\kappa\}$. A set $L\subseteq[X]^{<\kappa}$ is said to be unbounded if whenever $R\in[X]^{<\kappa}$ there is some $S\in[X]^{<\kappa}$ with $R\subseteq S$. A set $L\subseteq[X]^{<\kappa}$ is said to be closed if whenever $\lambda<\kappa$, $R_{\alpha}\in L$ for $\alpha<\lambda$, and the sequence $(R_{\alpha})_{\alpha<\kappa}$ is increasing, then $\bigcup_{\alpha<\lambda}R_{\alpha}\in L$ as well. A set $C\subseteq[X]^{<\kappa}$ is said to be a closed set if it is closed and unbounded.
A Boolean algebra $B$ is isomorphic to $Ro(2^{\kappa})$ if and only if there is a club set $C\subseteq[B]^{<\aleph_{1}}$ such that each $R\in C$ is a regular Boolean subalgebra of $B$ and whenever $R,S\in C$, we have $\langle R\cup S\rangle\in C$ as well (here $\langle R\cup S\rangle$ is the subagebra generated by the union $R\cup S$.)
1 Semi-Cohen Boolean algebras, Bohuslav Balcar, Thomas Jech, Jindřich Zapletal (1997)
[2] Handbook of set theory M. Foreman - Akihiro Kanamori - Springer - 2010
[3] KOPPELBERG, S. (1993), Characterizations of Cohen Algebras. Annals of the New York Academy of Sciences, 704: 222–237. doi: 10.1111/j.1749-6632.1993.tb52525.x


text:
Q: Why this inline method with deduced return type not defined yet? #include <string>
#include <type_traits>

class C
{
    static auto func() { return std::string("hello"); }
    static_assert(std::is_same<decltype(func()), std::string>::value, "");
};

Neither GCC nor Clang accept this, saying that func is used before it is defined. Why?
Changing the deduced auto return type to std::string makes it work.

A: The decltype construction produces the declared type of an identifier or expression. When func is declared with a return type, then the type of the call expression func() is known and everything works as expected.
However, when func is declared with the return type placeholder auto, then the declaration of func depends on its definition, so the type of func, and hence of the expression func(), is not known until the function has been defined.
When you define a class member function inline in the class definition, this is as if the definition were to appear right after the end of the class definition (that is, the function bodies may make reference to names that are lexically declared later in the class definition). The consequence of this and the semantics of auto is that your function auto func is not actually fully declared until the end of the class definition, and thus the type of func() cannot be known until then.

A: In addition to other answers, a possible workaround is to defer the check to a static function and rely on the optimiser to remove all redundant code.
In a release build, this should be zero cost:
#include <string>
#include <type_traits>
#include <iostream>

struct C
{
    static auto func() {
        check_same();
        return std::string("hello");
    }

private:

    static void check_same()
    {
        static_assert(std::is_same<decltype(func()), std::string>::value, "");
    }
};

int main()
{
  std::cout << C::func() << '\n';
}


text:
Q: Null or Zero Primary Key in unit work clone sqlite Hello I have a Problem with JPA and SQLite.
I have a table called Category in SQLite. This is the Structur of this table:
Category:
catID INTEGER Primary Key
catName TEXT

Now i'm trying to insert a new Category via JPA.
This is my method to do this:
public void insertCategory(EntityManager em, String catName) {
    Category cat = new Category();
    cat.setCatName(catName);
    em.getTransaction().begin();
        em.persist(cat);
        em.flush();
    em.getTransaction().commit();
}

Now I have an Execption at em.flush().
The Exception says
Null or zero primary key encountered in UnitOfWork clone

I know this happens because of the Object cat. The catID is still null.
The class looks like:
@Entity
@Table(name="Category")
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="catName")
    private String catName;

    @Id
    @Column(name="catID")
    private Integer catID;
    + Getter and Setter
}

SQLite increments the Primary Key automatically when not given in the query. How can i inform my Program about the Primary Key to run without getting this Exception??

A: Thank you Mick Mnemonic for your help. The last answer you give helped me.
I had to generate my database new and add the autoincrement Argument to my Primary Keys. Then the sqlite_sequence Table was generated. Now i can insert Entitys in my database via JPA without getting any Exception.
This is my Generator Annotation:
@GeneratedValue(generator="sqlite")
@TableGenerator(name="sqlite", table="sqlite_sequence",
                pkColumnName = "name", valueColumnName = "seq",
                pkColumnValue = "Section", initialValue = 1,
                allocationSize = 1)

the last two Arguments are necessary because jpa seems to add +50 to the value in the sqlite_seq table and SQLite begins the Autoincrement value at 1.


text:
Q: How to register a PolymerExpression filter inside a custom element, in Polymer.dart? How do I register a PolymerExpression filter inside a custom element? I am using Polymer.dart.
I want to use this:

Uppercase: {{bob.fullName | uppercase}}

inside the template of my custom element. Where do I register uppercase ?

A: I tried Seth answer and the expressions themselves are working but somehow I am losing events on my component.
My on-click event was not working anymore when I was using:
  DocumentFragment instanceTemplate(Element template) =>
      template.createInstance(this,
          new PolymerExpressions(globals: {
            'uppercase': (String input) => input.toUpperCase()
  }));

I also tried the solution proposed on the polymer expressions page but the binding delegate is apparently missing. Because of a new version maybe?
Anyway, after looking into the code I found another way to have expressions and also to keep events working.
class MyElement extends PolymerElement {

  MainElement.created() : super.created();

  @override
  BindingDelegate syntax = new MyPolymerExpressions();
}

class MyPolymerExpressions extends PolymerExpressions {

  MyPolymerExpressions(): super(globals: {
      'uppercase': (String input) => input.toUpperCase()
  });

  @override
  prepareBinding(String path, name, node) => Polymer.prepareBinding(path, name, node, super.prepareBinding);
}

I noticed that events are working the prepareBinding method is overrided.
If anyone has a better way to do it or some thoughts about this, I am quite interested!

A: Inside the PolymerElement, override instanceTemplate:
  DocumentFragment instanceTemplate(Element template) =>
      template.createInstance(this,
          new PolymerExpressions(globals: {
            'uppercase': (String input) => input.toUpperCase()
          }));

Notice you have to create an instance of PolymerExpressions and register the filter. Then you must call template.createInstance

A: From a discussion on the dart-misc, the polymer expressions is looking for a return that accepts a single argument. So to reproduce the toFixed example of parameters you need to return a function from the filter:
class MyElement extends PolymerElement {

  MainElement.created() : super.created();

  String toFixed(int digits) => (num n) => n.toStringAsFixed(digits);
}

Also, from the polymer_expressions package, you no longer need to do a custom binding/delegate to use the expression filter: "Polymer Expressions are now the default syntax for  custom elements." It appears you can just add the function directory to your element and use it as a filter.