text:
Q: Jquery leaflet map with icons based on json data keeps showing undefined I've been reading through all the previous examples on setting custom icons based on json data, but I'm striking out.  I keep getting errors that the icon i'm defining is undefined. But when I do console.log, I can see that what I am pointing to is defined.
My goal is to use a different icon.png depending on what the Classification is for each map point.
If I do console.log(markers[i]["Classification"]) I can see what the classification is.
but {icon: icons[markers[i]["Classification"]]} results in undefined.
I've tried different variations of declaring the icons in the var icons block like suggested in most of the solutions I have found. But that hasn't gotten me anywhere.
Pointing directly to icons["Source"] results in the Source icon being displayed for everything. I just can't get icons[markers[i]["Classification"]] to work.
html:
<!DOCTYPE html>

    <title>Sample Locations</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/>

    <link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.css" />
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.Default.css" />

  <select name="basemaps" id="basemaps" onChange="changeBasemap(basemaps)">

    <option value="Topographic">Topographic</option>
    <option value="Streets">Streets</option>
    <option value="NationalGeographic">National Geographic</option>
    <option value="Oceans">Oceans</option>
    <option value="Imagery">Imagery</option>
    <option value="ImageryClarity" selected>Imagery (Clarity)</option>
    <option value="ImageryFirefly">Imagery (Firefly)</option>
    <option value="Gray">Gray</option>
    <option value="DarkGray">Dark Gray</option>

    <option value="ShadedRelief">Shaded Relief</option>
    <option value="Physical">Physical</option>
  </select>

jquery:
var map = L.map( 'map', {
  center: [10.0, 5.0],
  minZoom: 1,
  zoom: 1
});

var layer = L.esri.basemapLayer('ImageryClarity').addTo(map);
  var layerLabels = L.esri.basemapLayer('ImageryLabels');
      map.addLayer(layerLabels);

  function setBasemap(basemap) {
    if (layer) {
      map.removeLayer(layer);
    }

    layer = L.esri.basemapLayer(basemap);

    map.addLayer(layer);

    if (layerLabels) {
      map.removeLayer(layerLabels);
    }

    if (basemap === 'ShadedRelief'
     || basemap === 'Oceans'
     || basemap === 'Gray'
     || basemap === 'DarkGray'
     || basemap === 'Terrain'
   ) {
      layerLabels = L.esri.basemapLayer(basemap + 'Labels');
      map.addLayer(layerLabels);
    } else if (basemap.includes('Imagery')) {
      layerLabels = L.esri.basemapLayer('ImageryLabels');
      map.addLayer(layerLabels);
    }
  }

  function changeBasemap(basemaps){
    var basemap = basemaps.value;
    setBasemap(basemap);
  }

var myURL = jQuery( 'script[src$="JS/maptest.js"]' ).attr( 'src' ).replace( 'JS/maptest.js', '' );

var markers;

jQuery.ajax({
url: myURL +  "map_json.php",
type: "JSON",
async: false,
success: function(data){
       markers = jQuery.parseJSON(data);
       jQuery(markers).each(function( index, element ) {

       });
}
});

var MapIcon = L.Icon.extend({
    options: {
        iconSize:     [50, 60],
        iconAnchor:   [22, 94],
        popupAnchor:  [-3, -76]
    }
});

var Source = new MapIcon({iconUrl: myURL + 'images/source.png'}),
    Blank = new MapIcon({iconUrl: myURL + 'images/background.png'}),
    Unknown = new MapIcon({iconUrl: myURL + 'images/unknown.png'}),
    Background = new MapIcon({iconUrl: myURL + 'images/background.png'});

var icons = {
    Source: Source,
    Blank: Blank,
    Unknown: Unknown,
    Background: Background};

var markerClusters = L.markerClusterGroup();

for ( var i = 0; i < markers.length; ++i )
{
  var popup = '
Sample Name: '+ markers[i]["Sample Name"] +
              '
Location Description: ' + markers[i]["Location Description"] +
              '
Date Taken: ' + markers[i]["Date"] +
              '
Classification: ' + markers[i]["Classification"]

  var m = L.marker( [markers[i].Lattitude, markers[i].Longitude], {icon: icons[markers[i]["Classification"]]})
                  .bindPopup( popup );

                  console.log(markers[i]["Classification"]);

  markerClusters.addLayer( m );
}

map.addLayer( markerClusters );

map.flyTo([39.8333333, -98.585522], 4);

basic json format:
[ { "Sample Name": "EquipmentBlank", "Date": "2017-02-14", "Lattitude": "40.3126", "Longitude": "-94.0277", "Location Description": "Place 2\/17", "Classification": "Blank\r" }, { "Sample Name": "B0517", "Date": "2017-05-23", "Lattitude": "39.1421", "Longitude": "-95.4795", "Location Description": "Place 5\/17", "Classification": "Unknown\r" }]

A: The database was incorrect and had added /r to the end of each data set. Likely when I imported the data.   ": "Unknown\r"
Reloading the database fixed the problem.


text:
Q: Are HList/KList suitable as method parameter? How to refer to? Type List? I discovered HList / KList, they are pretty cool. I have an actual use case, in which heterogenously typed and variable length containers with conserved type information would be very useful (for more info, see background below). However, I haven't understood the usage of a H/KList as method parameter, where I'm forced to fully type-annotate the parameter or loose type information.
Can H/KLists even be used as a parameter, if the full type is, of course, not known?
How to refer to a H/KList without loosing the type information?
Could "type lists"  be used to refer to a tuple of heterogenous & variable length type parameters? Here it says:
... the types of the elements can be tracked separate from the actual element values. To do this we create an purely abstract type (it has no instances) which models a list of types, let's call it TList.
I played around with it, but haven't not yet understood how to use it for type annotation of an HList as parameter.
Basically, I want something like this:
implicit def hlistToTypedLink[TL](a: HList[TL]):TypedLink[TL] = new TypedLink[TL](a.map(a:X => new TypedHandle[X]))

where TL refers to the Type List and X to the type of the current element. So here a HList should be mapped to another Tuple-like container, TypedLink, parametrized by the type list TL. The elements are to be wrapped each in yet another parametrized container TypedHandle, typed with the current type X.
Is this possible?
I saw Shapeless' HList and its "unify" method but the problem remains the same: I don't know how to refer to it in the parameter list, besides variable length.
My second hope was to use KList. It applies in my case, because TypedHandle is a common container with same constructor. With KList it appears easier to type annotate, according to apocalisp:
 val m = List(1, 2, 3, 4) :^: List("str1", "str2") :^: KNil

would be of type:
 KCons[Int,java.lang.String :: HNil,List]

However, the problem remains the same: In the method definition, I cannot know whether it will be a
KCons[String, Int :: HNil, TH]

or a
KCons[Foo, Bar, Baz :: HNil, TH]

so I don't know how to type annotate the KList as method parameter either.
Thanks for any hints!
Background:
I'm writing scala convenience extensions for the excellent OO- & graph database hypergraphdb. Hypergraphdb's hyperedges, HGLink, are basically tuples of HGHandle's. HGHandle refer to atoms which per se are typed.
Hence HGLink per se would be heterogenously typed and of variable length. However, HGLink's implementations are till now untyped, and constructed by untyped implementations of HGHandle's. I guess java's typesystem is not expressive enough to reflect the (far superior) typesystem of hypergraphdb (which for example, also has higher kinded types).
Basically, I'm trying to bridge scala's with hypergraphdb's type systems, I'm learning a lot and till now this has been real fun. TypedHandle works great already, besides numerous other hacks.
thanks for any advice.

A: It's not completely clear to me what you're asking for, but your hlistToTypedLink looks like it could be handled using shapeless's HList and polymorphic function values,
scala> import shapeless._ ; import TypeOperators._
import shapeless._
import TypeOperators._

scala> class TypedHandle[T]
defined class TypedHandle

scala> class TypedLink[L <: HList](l : L)
defined class TypedLink

scala> object MkTypedHandle extends (Id ~> TypedHandle) {
     |   def apply[T](t : T) = new TypedHandle[T]
     | }
defined module MkTypedHandle

scala> def hlistToTypedLink[L <: HList, M <: HList](a: L)
     |   (implicit mapper: MapperAux[MkTypedHandle.type, L, M]) =
     |     new TypedLink[M](a map MkTypedHandle)
hlistToTypedLink: [L <: HList, M <: HList](a: L)
  (implicit mapper: MapperAux[MkTypedHandle.type,L,M])TypedLink[M]

scala> hlistToTypedLink(23 :: "foo" :: true :: HNil)
res0: TypedLink[TypedHandle[Int] :: TypedHandle[String] ::
  TypedHandle[Boolean] :: HNil] = TypedLink@51fb5716

Essentially it looks like you want to map over your argument HList a, wrapping each element in a TypedHandle and then wrapping the resulting HList in a TypedLink. In all cases the wrappers are to be parametrized precisely on the types of their contents.
As seen above, this is possible using shapeless's HList map. There are two key ingredients here. First, the definition of the polymorphic function-like value MkTypedHandle which can be mapped across the HList a creating an HList of TypedLink-wrapped elements. And second, the implicit witness mapper which drives the map operation.

A: I better respond as you refer to my blog post. A TList is simply a HList without value storage, i.e. there is only a type representation of the list, no runtime representation. One advantage is that it facilitates different, possibly more efficient, types of value storage, for example arrays (HArray in Metascala). TLists can also be used to model union types (basically type sets), however Scala's type system is not powerful enough to do this solely on the type level (Haskell's type system is I think).

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happens if the earth stops rotating? I was wondering what would happen to all the components on the surface of the Earth if the Earth suddenly stops rotating but does not stop revolving.

A: The earth rotates on its own axis, revolves around the center of mass between the earth and moon, and revolves around the sun. If the earthed stopped rotating around its axis, there would obviously be no Coriolis effect and the climate would be significantly different. No more Hurricanes or rotating air masses. Only temperature differences would move air masses. The largest effect would be that the day is over 6 months and since there is no cooling effect of the night, the portion of earth exposed the sun would heat up significantly. We can roughly calculate this using the stefan boltzmann law if we consider that the earth recieves about $1300\ \mathrm{W/m^2}$ of radiation and the atmosphere reflects about $100\ \mathrm{W/m^2}$. The remaining $1200\ \mathrm{W/m^2}$, rather than being absorbed by the ground, heating it up slightly, and being radiated out at night, would now heat the ground up until it was able to rereadiate that energy away. Using an emmisivity of .9 yields an equlibrium temperature of $(1200/(.9*5.67*10^.8)$ or 391 kelvin which is 240 degrees fahrenheit. This is above boiling so it is fair to say that all life would stop. On the unilluminated side of earth just the opposite would happen, and that poriton would cool down to a very low temperature. This is unless the earth surface would take so long to heat up that by the time the earth revolved around the sun it was able to reradiate all that heat. Either way, the earth would be very hot or cold and there would be no life!

A: Another effect depends on what you consider the Earth.  If you only mean the core, mantle, and crust, the atmosphere and organic objects (and things made by said organic objects) would still have angular momentum.  If the Earth suddenly stops, most of us would be at least flung to the ground, and would probably slide along it for a short distance.  Most tall things (skyscrapers, bridges, and perhaps even some trees) would break.  The atmosphere would continue to rotate for a length of time, causing severe winds until it stopped.  The effects would be most severe along the equator because the linear momentum would be the greatest.  Even excluding the effects @aPhysicist discussed, it would still be catastrophic if the earth suddenly stops.  (Note, though, that the effects given here only apply if the stop is sudden.  If it is gradual, none of these effects would happen.)


text:
Q: Are Drupal theme settings cached? i want to change theme_username, a core theme function that outputs that dreadful "not verified" string on users who are not logged in (when they comment, for example). i want a checkbox in admin/build/themes/settings/MYTHEME to change that. but since that theme function gets called a lot, will it hurt the performance of any site using my theme or are theme settings cached?

A: Theme settings are cached as specified in the Drupal API page for theme_get_setting($setting_name, $refresh = FALSE).

A: Theme settings is usually stored with variable_set. So you need a query to check it. But you can cache the result yourself, with a static variable.


text:
Q: Setting variables with spaces within .env I have a .env file with a bunch of variables and I just came across an error.
One of the variables has spaces.
TEST="hello world"

So when I run this, learned about in this answer here.
env $(<.env)

I get this error.
env: world"': No such file or directory

How do I set variables with spaces within .env?

A: If your command is just a shell command, you could run your command in a subshell like this:
( . .env ; echo "$TEST" )

The source or . builtin has no problem with assignments containing spaces. It will set the variables in the .env file in the current shell's environment.
In the more likely case of calling an external program, you'll also have to add 'export' to each assignment in your env file like this:
export TEST="hello world"

This is necessary because source does not export assigned variables as env does, i.e. they are set inside the subshell only but not in the environment of another process started inside that subshell.

A: juste put the word that contains the space between " ".


text:
Q: The genus of an algebraic curve is invariant under isomorphisms I would like to know how to prove (or even better to see a full proof) of the following "fact".

Let $C_1$ and $C_2$ be two smooth curves and let $\phi : C_1 \rightarrow C_2$ be an isomorphism. Then
    $$
\text{genus}(C_1) = \text{genus}(C_2)
$$

I am not completely sure this is true since I haven't seen this result explicitly stated, but I Imagine it has to be true.
The motivation for this comes from an exercise from Silverman's book The Arithmetic of Elliptic Curves. I was doing the following exercise and I found that I needed the above mentioned fact in order for my argument for $(i) \implies (ii)$ to work.

2.5 Let $C$ be a smooth curve. Prove that the following are equivalent (over $\bar{K}$):
(i) $C$ is isomorphic to $\mathbb{P}^1$.
(ii) $C$ has genus $0$.
(iii) There exist distinct points $P, Q \in C$ satisfying $(P) \sim (Q)$

I've thought about it but unfortunately I don't really see how to easily relate the dimensions of the Riemann Roch spaces associated to each curve.
I would really appreciate some help with this.
Thank you.

A: The notation $\text{genus}(C_1)$ doesn't even make sense unless you know that the genus is invariant under isomorphism; if it isn't, the genus must depend on information other than $C_1$ which you haven't provided.
In any case, the definition of genus you are given implies that it is unique, and since the various dimensions $\ell(D)$ are defined independently of any choices they are automatically invariant under isomorphism, so the definition you have been given already comes with a guarantee that $g$ is invariant under isomorphism. But if you want a "proof" anyway, then setting $D = 0$ gives $\ell(K_C) = g$, so it suffices to show that the canonical divisor is invariant under isomorphism (that's why it's called the canonical divisor!).

A: The genus of a curve, viewed as the dimension of the space of holomorphic form $H^0(C,\Omega_C^1)$ is even invariant under birational morphisms. Indeed, if $f:X \to Y$ is a birational morphism between smooth complex projective varieties, then $f^*$ induces an isomorphism $H^0(Y,K_Y^{\otimes m}) \to H^0(X,K_X^{\otimes m})$ for each integer $m \geqslant 0$, where $K_X = \Lambda^{\dim X} T_X^*$ is the canonical bundle on $X$.


text:
Q: Why do du and Perl's -s give different values for the file size? Updated According to comments:
I have outlog.txt file which contains multiple filenames, e.g: 2345_535_Dell&HP_3PAR_DEAL.txt, similarly there are many filename but not the actual folder where the files are located and so in code am appending filenames to folderpath to get actual file location. Now,I want to get disk usage of all the files present in outlog.txt and also total disk usage of all files present in outlog.txt.
I have tried two approaches perl -s and my ($size) = split(' ', du `"$folderpath/$_"`) but both approaches are giving me different values and also when I am using du than am getting some numeric value but it does not give me unit, is there a way I can get human readable without using -h option as it is not working on my system ?
Background Information
My goal is to get the size of a file, and currently I am using perl -s to get filesize. I have also tried du and am getting different values for the size of the same file. I am not able to understand how this works.
Q: Why do du and perl -s give different values for size? How do they internally work? Which of the two different values is the more accurate one? Also, I'm not sure why du -h filename gives me an illegal expression error:
bash-2.03$ du -h test.txt
/usr/bin/du: illegal option -- h
usage: du [-a][-d][-k][-r][-o|-s][-L] [file ...]

Code:
my $folderpath = 'the_path';
open my $IN, '<', 'path/to/infile';
my $total;
while (<$IN>) {
    chomp;
    my $size = -s "$folderpath/$_";
    print "$_ => $size\n";
    $total += $size;
}
print "Total => $total\n";

Courtesy: RickF
Update:
Q:
How can I get the disk usage value instead of file size for each file present, meaning how can I get du value for each files rather than perl -s values for file ?
OS Information
uname :SunOS
uname -v :Generic_117350-39
Updated Code: According to brain's approach but still du value prints as zero only and not the actual value, any suggestions ?
Update:
If I use my ($size) = split(' ', du "$folderpath/$_"); than I am getting du value but it gives me some number, how can I get it into human readable without using -h option  ?
 #!/usr/bin/perl
 use strict;
 use warnings;

my $folderpath = '/Project/upload';
open my $IN, '<', 'outlog.txt';
my $total;
while (<$IN>) {
    chomp;
    #my( $block_size, $blocks ) = ( stat( "$_" ) )[11,12];
    #my $du_size = $block_size * $blocks;
    my ($size) = split(' ', `du "$folderpath/$_");
    #my $size = -s "$folderpath/$_";
    print "$_ => $size\n";
    $total += $size;
}
print "Total => $total\n";

A: du reports actual disk usage, Perl's -s reports the size of the file.  So, if a file is four bytes long it will have a size of four bytes, but disk usage of four kilobytes (depending on how your filesystem is setup).
You will also see a difference in the sizes of sparse files.  Sparse files take up less space than they claim to have in them.

A: By default, du displays the number of blocks used by a file (where each block is 512 bytes on most systems), while perl's -s displays bytes.
As to why your copy of du doesn't have a -h option, you don't tell us what operating system you're using; it appears to include a horribly outdated version of the program.
UPDATE: to get disk usage in perl, you can use the Filesys::DiskUsage module.

A: du stands for "Disk Used", and reports the physical size of the file on disk.  If the file is sparse, this may be much smaller than its logical size, which is what -s reports.  Both are "accurate", they're just measuring different things.
The error message indicates that the version of du installed on your machine doesn't understand the -h option.

A: If you want du to give the same results as Perl's -s, try du -b. If your du supports it, this gives the "apparent size", which is different from disk usage, as others have stated.
But to do this you'll have to update your du.
Update for OP's updated code: Make sure that the file exists within your current working directory. You may have to prepend the directory to make sure that Perl is finding the file.
It may also clarify things if you get away from using $_ everywhere:
while( my $line = <$IN> ) {
  chomp $line;
  my( $block_size, $blocks ) = ( stat( $line ) )[11,12];
  ...
}

This way you're safe from unintentional changes to $_.


text:
Q: How to grep and treat meta character as normal character? I am trying to recursively find some pattern which contains meta character.
Pattern that I searching for is template <int N>
I have tried :
grep -F -lir "template <int N>"  *    # trying to find "template <int>"
                                      # -F treat meta char as normal char

I get:
     grep: \<int: No such file or directory
     grep: N\>: No such file or directory
     ..
     ...

A: Try using fgrep (or the -F option to grep that does the same), and write your query without escaping the "<" and ">".  I'd also suggest using single-quotes ' rather than double-quotes ", since the shell may expand what it think is variables and such when you use double-quotes.
fgrep -i 'template <int N>' *


text:
Q: Crash on line "remainingData = [data subdataWithRange:NSMakeRange(size, data.length - size)];" I am facing a crash "Terminating app due to uncaught exception 'NSRangeException', reason:

'* -[NSSubrangeData subdataWithRange:]: range {8, 565316237} exceeds
  data length 210204'"

If someone can help me in finding the solution of this.
-(NSData *) parseAtom:(MP4Atom **) pAtom fromData:(NSData *) data {
        // Assume it all remains
        NSData *remainingData = data;

        // Data must not be nil
        if( data != nil ) {

            // Length must be at least 8 bytes
            if( data.length > 8 ) {

                // Read type and size
                UInt32 size = [data uint32AtOffset:0];
                NSString *type = [data fourByteStringAtOffset:4];

                // The rest is data
                NSData *atomData = [data subdataWithRange:NSMakeRange(8, size - 8)];

                // Read the atom
                MP4Atom *atom = [MP4Atom mp4AtomWithType: type data:atomData];

                // Get the remaining data
                if( size < data.length) {
                    remainingData = [data subdataWithRange:NSMakeRange(size, data.length - size)];
                } else {
                    remainingData = nil;
                }

                // If we got a valid result...
                if( atom != nil ) {
                    // ... and pAtom was not nil,
                    if( pAtom != nil ) {
                        // assign the atom
                        *pAtom = atom;
                    } else {
                        DDLogCritical( @"pAtom is nil in parseAtom:fromData:");
                    }
                } else {
                    DDLogCritical( @"Failed to parse atom from data in parseAtom:fromData:");
                }
            } else {
                DDLogCritical( @"data is too short (%d) expected at least 8 bytes in parseAtom:fromData:", data.length);
            }
        } else {
            DDLogCritical( @"data is nil in parseAtom:fromData:");
        }
        return remainingData;
    }


text:
Q: Golang Couchbase integration throwing errors on setting/getting Implementing https://github.com/couchbase/go-couchbase
However - no matter what I do - with various types of connections - I get errors when setting/getting keys.
vbmap smaller than vbucket list: 18119 vs. []

Code Example below (have tried many variations)
b, err := couchbase.GetBucket("http://somebucket:somepassword@myserver:8091/",
       "default", "somebucket")
mf(err,"con")

err = b.Set("somekey", 0, map[string]interface{}{"x": 1})
  mf(err, "set")

A: You are probably trying to connect to a memcached bucket. go-couchbase doesn't support buckets of type memcached.


text:
Q: Spliting dataframe into chunks by the rows that satisfy the given condition I have a dataframe similar to:
 col1   col2
 1      10
 1      30
 2      60
 3      20
 3      12
 3      51
 3      11

I want to divide this dataframe into chanks when the value in col2 is bigger than 50:
dataframe #1
col1   col2
1      10
1      30
2      60

dataframe #2
col1   col2
3      20
3      12
3      51

dataframe #3
col1   col2
3      11

I have tried split function but it would not serve for this task. I wonder if there is a generic function to achieve this?

A: You can use cumsum in split, with a lot of reving to include the rows where col2 > 50 in the previous group
rev(split(df, rev(cumsum(rev(df$col2 > 50)))))
#@joran method, (same result, except for names):
split(df, cumsum(df$col2 > 50) - (df$col2 > 50))

Output:
# $`2`
#    col1 col2
# 1:    1   10
# 2:    1   30
# 3:    2   60
#
# $`1`
#    col1 col2
# 1:    3   20
# 2:    3   12
# 3:    3   51
#
# $`0`
#    col1 col2
# 1:    3   11

without all the revs you get this
split(df, cumsum(df$col2 > 50))

# $`0`
#    col1 col2
# 1:    1   10
# 2:    1   30
#
# $`1`
#    col1 col2
# 1:    2   60
# 2:    3   20
# 3:    3   12
#
# $`2`
#    col1 col2
# 1:    3   51
# 2:    3   11


text:
Q: Unable to fetch api from rest api and get results in react function App() {
  const [state, setState] = useState([{}]);
  const [resultstate, setResultState] = useState([{}]);

  function handleSubmit() {
    const uri = "/?${form.one}&${form.two}";
  }

  function handleChange(e) {
    const { nodeName, name, value } = e.target;
    if (nodeName === "INPUT") {
      setState({ ...FormData, [name]: value });
    }
  }

  useEffect(() => {
    fetch(uri)
      .then((res) => res.join())
      .then((data) => {
        setResultState(data);
        console.log(data);
      });
  }, []);

  return (
    <div className="App">
      <state onChange={handleChange}>
        <fieldset>
          <legend>Solute</legend>
          <input name="one" value={state.one} />
        </fieldset>
        <fieldset>
          <legend>Solvent</legend>
          <input name="two" value={state.two} />
        </fieldset>
        <button type="button" onClick={handleSubmit}>
          Submit
        </button>
      </state>
    </div>
  );
}

export default App;

I am building an app where the flask rest API takes two strings and gives a floating value as a prediction. Now I am trying to connect to the react app so that the predictions can be shown on a webpage.
Now I was able to fetch the URL but unable to get the prediction result using useEffect. can someone point out where I am doing wrong
I am getting error as 'uri' is not defined  no-undef

A: You have not defined uri as part of the state, it is defined in a function locally. Hence the error.
To resolve, you need to add it to the state.
const [uri, setUri] = useState('');

in handleSubmit, you can use the setUri() method to set the state.
uri will now be accessible as part of the App state.


text:
Q: Get the descriptor histogram from images using BOW in openCV I have the cluster centers (vectors) which I calculated using Kmeans. And I can calculate the feature vectors of an image and store it in a matrix. My problem is, how to get the histogram of occurrences of visual words of a particular image using the data I have. Im using OPENCV.
Can someone help please?


text:
Q: Interactive Brokers Python API ERROR -1 322 Processing request I am trying to cancel all orders but receive this error message
openOrder id: 62 ES FUT @ GLOBEX : BUY STP 13.0 PreSubmitted
orderStatus - orderid: 62 status: PreSubmitted filled 0.0 remaining 13.0 lastFillPrice 0.0
openOrder id: 63 ES FUT @ GLOBEX : BUY LMT 13.0 PreSubmitted
orderStatus - orderid: 63 status: PreSubmitted filled 0.0 remaining 13.0 lastFillPrice 0.0
openOrder id: 61 ES FUT @ GLOBEX : SELL STP LMT 13.0 Submitted
orderStatus - orderid: 61 status: Submitted filled 0.0 remaining 13.0 lastFillPrice 0.0
ERROR -1 2104 Market data farm connection is OK:usfuture
ERROR -1 2106 HMDS data farm connection is OK:ushmds
ERROR -1 2158 Sec-def data farm connection is OK:secdefil
ERROR -1 322 Error processing request:-'bt' : cause - jextend.bt.l(bt.java:59)
unhandled exception in EReader thread
Traceback (most recent call last):
class IBapi(EWrapper, EClient):
                    posns = []
                    fname = 'OpenPos.txt'
                    def __init__(self):
                        EClient.__init__(self, self)

                    def nextValidId(self, orderId: int):
                        super().nextValidId(orderId)
                        self.nextorderId = orderId

                    def orderStatus(self, orderId, status, filled, remaining, avgFullPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice):
                        print('orderStatus - orderid:', orderId, 'status:', status, 'filled', filled, 'remaining', remaining, 'lastFillPrice', lastFillPrice)

                    def openOrder(self, orderId, contract, order, orderState):
                        print('openOrder id:', orderId, contract.symbol, contract.secType, '@', contract.exchange, ':', order.action, order.orderType, order.totalQuantity, orderState.status)

                    def execDetails(self, reqId, contract, execution):
                        print('Order Executed: ', reqId, contract.symbol, contract.secType, contract.currency, execution.execId, execution.orderId, execution.shares, execution.lastLiquidity)

                def run_loop():
                    app.run()

                app = IBapi()
                app.connect('127.0.0.1', 7497, 123)
                time.sleep(2)

                app.nextorderId = None
                api_thread = threading.Thread(target=run_loop, daemon=True)
                api_thread.start()
                app.reqGlobalCancel()
                time.sleep(3)
                done=True
                time.sleep(1)
                app.disconnect()


text:
Q: Macro to an other macro with arguments from first macro I'm trying to make this macro work:
#define InitProperty(Name, Type) DefineMethods ( ##Name.Mode, Type, Name )

Now this doesn't seem to be working this gets me:
DefineMethodsLenght.Mode(caller, Lenght)

instead of
DefineMethods(Lenght.Mode, caller, Lenght);

What's going on here; isn't this possible?

A: If you want the result that you say you want, then you don't need to use any preprocessing operators; you just need:
#define InitProperty(Name, Type) DefineMethods ( Name.Mode, Type, Name )

The ## operator is used to concatenate tokens.  Given your current macro definition, I don't see why you'd get the result you say you get, but your use of ## is definitely incorrect.  The result of the concatenation is required to be a single preprocessing token, and (Lenght is two preprocessing tokens--( and Lenght--not one.

A: Well, the title of your question implies that there are TWO macros involved, but your example only shows one macro.  So I'll go ahead and guess that you have:
#define InitProperty(Name, Type) DefineMethods ( Name.Mode, Type, Name )
#define DefineMethods(Name, Type, Arg)  DefineMethods##Name( Type, Arg )

Now if you invoke this with
InitProperty(Lenght, caller)

you will get (after macro expansion)
DefineMethodsLenght.Mode(caller, Lenght)

which is what you describe.  You say you want
DefineMethods(Lenght.Mode, caller, Lenght)

which does exist midway through the macro expansion process, but after expanding the DefineMethods macro you'll get what you see.  If that's NOT what you want, the problem is in the DefineMethods macro and not the InitProperty macro, but as you don't show it in your question, we can't really tell what is going on.

A: I think
#define InitProperty(Name, Type) DefineMethods ( Name.Mode, Type, Name )

should be correct.
But to be safer, it's better to use:
#define InitProperty(Name, Type) DefineMethods ( (Name).Mode, (Type), (Name) )

If the problem remains, why not try this?
template<TName, TType>
void InitProperty(TName Name, TType Type) {
    DefineMethods (Name.Mode, Type, Name);
}

InitProperty(Length, caller);

If "Name", "Type" are not also macros.


text:
Q: Match list elements from two lists that sum to the same amount I have two lists of numbers (A and B), and some combination of elements in A should sum to the same total as some
combination of elements in B.
As groups are matched, the matched elements would be removed from their lists to continue until all combinations are matched.
For example, with the two lists:
A = [7, 8, 12, 300, 350]
B = [3, 4, 20, 150, 500]

The combined sum totals of the matched groups would be:
{7: [{'A': [7], 'B': [3, 4]}],
 20: [{'A': [8, 12], 'B': [20]}],
 650: [{'A': [300, 350], 'B': [150, 500]}]}

The naive way I've addressed this so far is to get the sum of all possible combinations from each list (pow(2, len(mylist))-1), do a set intersection between the two sets of all combinations, and remove elements sequentially until all elements are accounted for.
Does anyone know of a more efficient algorithm to accomplish this?  Expanding to all possible combinations for each list to then do a set intersection can get large.
Here's the naive way:
def getCombos(stuff):
    res = []
    for L in range(1, len(stuff) + 1):
        for subset in itertools.combinations(stuff, L):
            res.append(subset)
    return res

Acombo = getCombos(A)
Bcombo = getCombos(B)
AcomboSum = [sum(tup) for tup in Acombo]
BcomboSum = [sum(tup) for tup in Bcombo]

sumint = sorted(set(AcomboSum).intersection(set(BcomboSum)))

Arem = [a for a in A]
Brem = [b for b in B]

d = collections.defaultdict(list)

for s in sumint:
    idx = sumint.index(s)
    Avals = Acombo[AcomboSum.index(s)]
    Bvals = Bcombo[BcomboSum.index(s)]

    if set(Avals).issubset(set(Arem)) and set(Bvals).issubset(set(Brem)):
        d[s].append([Avals, Bvals])
        for v in Avals: Arem.pop(Arem.index(v))
        for v in Bvals: Brem.pop(Brem.index(v))
    else:
        continue

print(d)

A: Sort both arrays in reverse descending order.
Then calculate all sums in array A and Sort that in reverse descending order.
if A[n] represents all elements in array A
and B[m] represents all elements in array B
and sum_A[n!] represents all possible sums of elements in A.
and sum_A.sorted(reverse=True) represents that array sorted in descending order.
create a new array
B_start[n!] and store the index i of the first element in B that is smaller than the sum_A[i].
Now for any sum_A[i] element  you only have to consider elements in B from B[ B_start[i] ] to B[m] for combinations of sums
Note: this only works if all numbers in the arrays are positive.


text:
Q: How fast are different types of SSD storage (SLC, MLC, TLC, QLC)? I would like to buy an SSD which I regularly plan on writing large files (RAW video files). I am trying to decide between an QLC, TLC, and MLC SSD, but the prices increase in that order.
What are the speeds of SLC, MLC, TLC, and QLC NAND storages? This will help me decide what type of drive I want. I am thinking of going with the TLC storage, but if my file transfer speeds will throttle significantly I will consider going for the MLC storage, but I want to know first how much of an advantage this will bring me.
An example of what I mean: Samsung produces a few lines of SATA SSDs—the Pro, the Evo, and the Qvo. They use MLC, TLC, and QLC storage respectively. However, in each of their specifications it is listed that their read and write speeds are around ~550 MB/s. I am looking to understand the actual speed that I will experience after the buffer has been used up, which will undoubtedly be different for each type of SSD.
I also noticed that one of my SSDs throttles to about 20 MB/s when copying large files over. This seems extremely low to me, and I'm wondering if it is faulty or if the slower NAND storage is just that slow.

A: The speeds of a specific SSD will be listed by the manufacturer, but this is mainly affected by the overall design and interface that it uses. A SATA SSD for example will be slower than an m2 NVME pcie SSD.
The channel design with SLC, MLC, TLC, and QLC can instead affect the overall lifespan of sectors on the storage drive. Each cell in an SSD has a number of times that data can be written to it; think of it as an odometer. In these different channel designs, different numbers of bits can be stored in a cell. SLC can store one bit, MLC 2 bits, TLC 3 bits, QLC 4 bits. The more bits that can be written to a cell means that the cell takes more millage, and then it's lifespan is shorter.
The TBW rating of a drive can tell you how many terabytes can most likely be written to the device. Some brands like Samsung devices can communicate with a software to tell what the TBW is at any time, so like an odometer, you know how much of the lifespan you have used up.
The channel doesn't affect the speed so much, but the more bits in a cell can mean that it takes longer to write. But this isn't the biggest factor for the speed rating of a drive.


text:
Q: Swag Request Delays for April/May I've been receiving a lot of requests for swag due to contests, conferences, elections, and many other reasons. This includes swag/prizes from the most recent Gaming event, as well. Many of you have noticed there have been significant delays in getting our users any swag at all.
I have to apologize; I should have made this announcement weeks ago, but I kept hoping things would work out before I had to write this post. Unfortunately, it seems that this strategy has backfired.
For some time, we've been experiencing a major warehouse move that coincided with our company's office move. The storage setup and taking inventory of our various and sundry swag has taken longer than expected, and I have been waiting for the all-clear before I can put in swag orders.
I have to thank all the users who have been patient with these delays so far, and I appreciate everyone who has been understanding and patient for the last several weeks. The most recent news I heard is: everything should be sorted out by the end of next week at the latest, after which point you will all begin receiving shipments in a more timely manner once more.
Please feel free to comment/answer here if you have specific questions about any requests you've made. Again, thank you all for your patience!
Update
As of July 2013 - we should be all caught up. Yay, us!!
If we were supposed to send you something and you didn't receive it, contact us and let us know. Be sure to tell us:

*

*What you were supposed to get

*Why you were supposed to get it (e.g. won a contest, someone from the team offered you a shirt, etc)

*If it can be worn, we need your size.

*If you live on planet Earth, we need your complete address (as it should be printed on the package). Interplanetary delivery is still down, we're sorry for the inconvenience!

We'll get it sorted out quickly!

A: I was supposed to receive an unspecified piece of swag back in March that never arrived. This isn't a complaint about the physical item — it's the thought that counts, really! — but I thought you might want the follow-up, since nobody else has posted. I don't know whether everyone else also forgot about pending swag requests, or if I'm the only one who had a problem; hopefully, this bump will lead to us finding out.


text:
Q: A class of self-similar infinitely divisible distributions For $\alpha\in (0,2]$ denote $F_{\alpha}$ the class of all probability measures $\mu$ on $\mathbb{R},$ such that for any Borel set $A\subset \mathbb{R}$
$\mu(A)=\int_{\mathbb{R}^2}\mathbf{1}_A(\frac{x+y}{2^{1/\alpha}})\mu(dx)\mu(dy).$
Every $\mu\in F_{\alpha}$ is infinitely divisible. For $\alpha=2$ $F_2$ is the class of all centered Gaussian measures. I'm interested in the case $\alpha\in (1,2).$ In this case Gaussian component of $\mu\in F_{\alpha}$ is zero and Levy-Khintchine formula has following form:
$\hat{\mu}(\xi)=\exp(\frac{i\xi}{1-2^{1-1/\alpha}}\int_{2^{-1/\alpha}<|y|\leq 1}yM(dy)+\int_{\mathbb{R}}(e^{i\xi x}-1-i\xi \mathbf{1}_{[0,1]}(|y|)y)M(dy)),$
where Levy measure $M$ satisfies relation
$M(2^{-1/\alpha}A)=2M(A), \ A\subset \mathbb{R}.$
The problem is to construct for each $\varepsilon>0$ a measure $\mu\in F_{\alpha}$ such that $\mu(-\infty,-\varepsilon)=0.$
Actually the problem is to define suitable measure on the set $\{y: 2^{-1/\alpha}<|y|\leq 1\}$ for it uniquely defines a Levy measure $M$ with needed properties. But even in the simplest case when I start from Dirac measure at point 1 and, respectively, Levy measure $M=\sum_{m\in \mathbb{Z}}2^m \delta_{2^{-m/\alpha}}$ I can't produce all the calculations.

A: Let me try to understand.
With your candidate for the L\'evy measure, for $\alpha\in(1,2)$, the integral
$\int_0^1 x^2dM=\sum_{m=0}^\infty 2^m (2^{-m/\alpha})^2 < \infty$
converges, since $1-\frac{2}{\alpha}<0$, but the integral
$\int_0^1 xdM=\sum_{m=0}^\infty 2^m 2^{-m/\alpha}$
diverges, since $1-\frac{1}{\alpha}>0$, right?
So $M$ is a L\'evy measure, and there exists a L\'evy process. But your L\'evy process is not a subordinator, because the second integral diverges. Since each part of the L\'evy triple is uniquely determined, you can not add a drift that would turn your process into subordinator, either. Doesn't this mean that the support of your L\'evy process is neither bounded below, nor bounded above? I.e.,you can not have $\mu((-\infty,-\varepsilon))=0$ for any $\varepsilon$?


text:
Q: jQuery CSS magicline https://css-tricks.com/examples/MagicLine/
That's the one I do use, but it requires
But some other scripts requires
So what I tried was simply to use them both, but then it crashes.
This is the MagicLine code:

And this is the other:

If I use 1.5.2 the last wont work, so if I delete that one it works but the MagicLine. How do I get both to work together?

A: You're having this problem, because as you say, you have scripts which require different versions of jQuery.
You can run multiple versions of jQuery alongside each other using the noConflict method as described here.
However, the bad news is, you need to edit the scripts you are using - and that can be either impossible or a major headache.  In either case, it's a maintenance headache.

A: Just use the newer version of jQuery - 2.1.4 - and then, if needed, also add the jQuery Migrate script to support the code that may rely on an older version of jQuery


text:
Q: What is the proper way to raise exception and handle certain exception type in C++ I know theoretically how to create and handle exception. But in a big project a function can throw a lot of different exception.
How do I manage to parse all the exceptions I can receive?
For example:
I am currently implementing a database client. And if a query ask for a bad table or a bad column I throw exception in the low level driver as follow:
throw MySQLException("message");

And this will result in throwing a std::runtime_error exception in the client's top level. So I added the following code to catch the exception:
try {
  execute(query);
}
catch(std::exception &e) {
  // How do I parse exception content?
}

But is there a better way than excrating info from the e.what() to figure out what kind of exception it is?
The objective is to make each sort of exception correspond to an error code (without modifiying the exception message).
Link to tutorial will be weclome.

A: You can have multiple catch statements, like this:
try {
    execute(query);
}
catch (const my_custom_exception_type& e) {
}
catch (const std::runtime_error& e) {
}
catch (const std::exception& e) {
}
catch (...) {
    // fallback - exception object is not any of the above types
}

Control will flow into the first catch block whose parameter type is compatible with the exception object type. If none match and there is no ... catch-all, the exception will propagate out of that try/catch block. A more precise explanation of the exact try/catch behavior can be found here:

When an exception of type E is thrown by any statement in compound-statement, it is matched against the types of the formal parameters T of each catch-clause in handler-seq, in the order in which the catch clauses are listed. The exception is a match if any of the following is true:

*

*E and T are the same type (ignoring top-level cv-qualifiers on T)

*T is an lvalue-reference to (possibly cv-qualified) E

*T is an unambiguous public base class of E

*T is a reference to an unambiguous public base class of E

*T is (possibly cv-qualified) U or const U& (since C++14), and U is a pointer or pointer to member (since C++17) type, and E is also a pointer or pointer to member (since C++17) type that is implicitly convertible to U by one or more of

*

*a standard pointer conversion other than one to a private, protected, or ambiguous base class

*a qualification conversion

*a function pointer conversion (since C++17)

*T is a pointer or a pointer to member or a reference to a const pointer (since C++14), while E is std::nullptr_t.

You can also use RTTI to determine the type of e but avoid that if at all possible.

A: I am not 100% sure if this is what you are directly looking for, but in regards to the statement that you made:

But in a big project a function can throw a lot of different exception.

I have used this kind of design in a large project when building a 3D Graphics Engine. This does require a handful of classes though. Another thing to note is that my code was designed with windows specific in mind. I've commented parts that are window specific code that can be replaced with your specific OS implementation. Another thing is I've used __FUNCTION__ in many of the output messages, you can replace that with __PRETTY_FUNCTION__ as for some reason windows and visual studio doesn't like it... You can also replace the namespace I used with your own namespace name. If this doesn't directly help you maybe at least the overall design might be of use. You can create a new project and use this as is just to see the generated console messages and the written log file. You can take some of the concepts from this, or you can expand and integrate your own specific error messages and exception types that are thrown into these classes that would make it suitable for your own purposes.

The following classes are integrated together where some of them can be used independently or in combination and should be thread safe for multithreading purposes.

*

*ExceptionHandler - It uses the Logger class and is used to handle messages that are thrown and or sent to the Logger.

*Logger - A derived class from Singleton. It logs to either the console, a text file or both. It uses the TextFileWriter to write to a text file.

*Singleton - A base class that all Singleton Type classes are derived from.

*TextFileWriter - A derived class from FileHandler. It writes to a text file.

*FileHandler - A base class that all file handling type classes derive from.

Example Program Using The Above Classes:
#include "Logger.h"
#include "ExceptionHandler.h"

#include <sstream>
#include <iostream>

enum ReturnCode {
    ReturnError = -1,
    ReturnOkay = 0
};

// helper function
void quitMessage() {
    std::cout << "\nPress any key and enter to quit.\n";
    std::cin.get();
}

// Example Class that uses the Logger & ExceptionHandler.
class Foo {
public:
    Foo() = default;

    void printFooUsingExceptionHandler() {
        using namespace linx;
        throw ExceptionHandler( __FUNCTION__ + std::string( " using ExceptionHandler" ) );
        // Or can be used this way
        // std::ostringstream stream;
        // stream << __FUNCTION__ << " using ExceptionHandler";
        // throw ExceptionHandler( stream );
    }

    void printFooNotUsingExceptionHandlerButUsingLogger() {
        using namespace linx;
        std::ostringstream stream;
        stream << __FUNCTION__ << " logging to logger, but not using ExceptionHandler";
        Logger::log( stream, Logger::TypeWarning ); // Can use TypeInfo, TypeWarning or TypeError pending on the use case.
    }
};

int main() {
    namespace lx = linx;
    using namespace lx;

    try {
        Logger logger( "logger.txt" );

        // last param is ommited as it is defaults to TypeInfo
        Logger::log( "This is basic info" );
        Logger::log( "This is a warning", Logger::TypeWarning );
        Logger::log( "This is an error", Logger::TypeError );
        Logger::log( "Basic console message", Logger::TypeConsole );

        // Example of a class using the ExceptionHandler & Logger classes
        Foo f;
        // call this first; log to message but don't throw excpetion
        f.printFooNotUsingExceptionHandlerButUsingLogger();
        // call this to throw exception
        f.printFooUsingExceptionHandler();

    } catch( ExceptionHandler& e  ) {
        std::cout << "Exception Thrown: " << e.getMessage() << std::endl;
        quitMessage();
        return ReturnError;
    } catch( ... ) {
        std::cout << __FUNCTION__ << " Caught Unknown Exception" << std::endl;
        quitMessage();
        return ReturnError;
    }

    quitMessage();
    return ReturnOkay;
}

The Classes:

ExceptionHandler.h
#ifndef EXCEPTION_HANDLER_H
#define EXCEPTION_HANDLER_H

#include <string>
#include <sstream>

namespace linx {

class ExceptionHandler final {
private:
    std::string _message;

public:
    explicit ExceptionHandler( const std::string& message, bool saveInLog = true );
    explicit ExceptionHandler( const std::ostringstream& streamMessage, bool saveInLog = true );

    ~ExceptionHandler() = default;
    ExceptionHandler( const ExceptionHandler& c ) = default;
    ExceptionHandler& operator=( const ExceptionHandler& c ) = delete;

    const std::string& getMessage() const;
};

} // namespace linx

#endif // !EXCEPTION_HANDLER_H

ExceptionHandler.cpp
#include "ExceptionHandler.h"
#include "Logger.h"

namespace linx {

ExceptionHandler::ExceptionHandler( const std::string& message, bool saveInLog ) :
_message( message ) {
    if( saveInLog ) {
        Logger::log( _message, Logger::TypeError );
    }
}

ExceptionHandler::ExceptionHandler( const std::ostringstream& streamMessage, bool saveInLog ) :
_message( streamMessage.str() ) {
    if( saveInLog ) {
        Logger::log( _message, Logger::TypeError );
    }
}

const std::string& ExceptionHandler::getMessage() const {
    return _message;
}

} // namespace linx

Logger.h
#include <sstream>
#include <array>

// For Windows Console Output
#define VC_EXTRALEAN
#include <Windows.h>

namespace linx {

class Logger final : public Singleton {
public:
    enum LoggerType {
        TypeInfo = 0,
        TypeWarning,
        TypeError,
        TypeConsole
    };

private:
    std::string _logFilename;
    unsigned    _maxCharLength;

    std::array<std::string, 4> _logTypes;
    const std::string _unknownLogType;

    // This is for Windows Console Output - Can substitue with OS type
    HANDLE _hConsoleOutput;
    WORD   _consoleDefualtColor;
    // ---------------------------------------------------------------

public:
    explicit Logger( const std::string& logFilename );
    virtual ~Logger();

    static void log( const std::string& text, LoggerType logType = TypeInfo );
    static void log( const std::ostringstream& text, LoggerType logType = TypeInfo );
    static void log( const char* text, LoggerType logType = TypeInfo );
};

} // namespace linx

#endif // !LOGGER_H

Logger.cpp
#include "Logger.h"
#include "TextFileWriter.h"

#include <iostream>
#include <iomanip>
#include <mutex>
// #include <shared_mutex>

namespace linx {

static Logger* s_pLogger = nullptr;

std::mutex  g_mutex;  // also removed the static storage qualifier.
//static std::shared_mutex s_mutex; // this was a wrong implementation

// White Text On Red Background
static const WORD WHITE_ON_RED = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_RED;

Logger::Logger( const std::string& logFilename ) :
Singleton( TypeLogger ),
_logFilename( logFilename ),
_maxCharLength( 0 ),
_unknownLogType( "UNKNOWN" ) {
    // Order must match types defined in Logger::LoggerType enum
    _logTypes[0] = "Info";
    _logTypes[1] = "Warning";
    _logTypes[2] = "Error";
    _logTypes[3] = ""; // Console

    // Find widest log type string
    _maxCharLength = _unknownLogType.size();
    for ( const std::string& logType : _logTypes ) {
        if( _maxCharLength < logType.size() ) {
            _maxCharLength = logType.size();
        }
    }

    // this was wrong
    //std::shared_lock<std::shared_mutex> lock( s_mutex );

    { // scope for lock_guard
        std::lock_guard<std::mutex> lock( g_mutex );

        // Start Log File
        TextFileWriter file( _logFilename, false, false );

        // Prepare Console  - Windows Console (can substitute with your OS)
        _hConsoleOutput = GetStdHandle( STD_OUTPUT_HANDLE );

        CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
        GetConsoleScreenBufferInfo( _hConsoleOutput, &consoleInfo );
        _consoleDefualtColor = consoleInfo.wAttributes;
        // End - Windows Console specific

        s_pLogger = this;
    } // end scope: lock_guard must be destroyed here

    // Must destroy lock_guard to unlock mutex before calling this function
    // this function is derived from Singleton but it calls Logger::log() static method which in turn uses the same mutex to lock.
    logMemoryAllocation( true );
}

Logger::~Logger() {
    logMemoryAllocation( false );
    s_pLogger = nullptr;
}

void Logger::log( const std::string& text, LoggerType logType ) {
    log( text.c_str(), logType );
}

void Logger::log( const std::ostringstream& text, LoggerType logType ) {
    log( text.str().c_str(), logType );
}

void Logger::log( const char* text, LoggerType logType ) {
    if( nullptr == s_pLogger ) {
        std::cout << "Logger has not been initialized, can not log " << text << '\n';
        return;
    }

    // this is wrong
    //std::shared_lock<std::shared_mutex> lock( s_mutex );

    std::lock_guard<std::mutex> lock( g_mutex );

    std::ostringstream stream;

    // Default White Text On Red Background
    WORD textColor = WHITE_ON_RED;

    // Choose log type text string, display "UNKNOWN" if logType is out of range
    stream << std::setfill( ' ' ) << std::setw( s_pLogger->_maxCharLength );

    try {
        if( TypeConsole != logType ) {
            stream << s_pLogger->_logTypes.at( logType );
        }
        if( TypeWarning == logType ) {
            // Yellow
            textColor = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN;
        } else if( TypeInfo == logType ) {
            // Green
            textColor = FOREGROUND_GREEN;
        } else if( TypeConsole == logType ) {
            // Cyan
            textColor = FOREGROUND_GREEN | FOREGROUND_BLUE;
        }
    } catch( ... ) {
        stream << s_pLogger->_unknownLogType;
    }

    // Date & Time
    if( TypeConsole != logType ) {
        SYSTEMTIME time;
        GetLocalTime( &time );

        stream << " [" << time.wYear << '.'
            << std::setfill( '0' ) << std::setw( 2 ) << time.wMonth << '.'
            << std::setfill( '0' ) << std::setw( 2 ) << time.wDay << ' '
            << std::setfill( ' ' ) << std::setw( 2 ) << time.wHour << ':'
            << std::setfill( '0' ) << std::setw( 2 ) << time.wMinute << ':'
            << std::setfill( '0' ) << std::setw( 2 ) << time.wSecond << '.'
            << std::setfill( '0' ) << std::setw( 3 ) << time.wMilliseconds << "] ";
    }
    stream << text << '\n';

    // Log Message
    SetConsoleTextAttribute( s_pLogger->_hConsoleOutput, textColor );
    std::cout << stream.str();

    // Save same message to file
    try {
        TextFileWriter file( s_pLogger->_logFilename, true, false );
        file.write( stream.str() );
    } catch( ... ) {
        // Ignore, not saved in log file
        std::cout << __FUNCTION__ << " failed to write to file: " << stream.str() << '\n';
    }

    // Reset to default color
    SetConsoleTextAttribute( s_pLogger->_hConsoleOutput, s_pLogger->_consoleDefualtColor );
}

} // namespace linx

Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H

namespace linx {

class Singleton {
public:
    enum SingletonType {
        TypeLogger = 0, // MUST BE FIRST!
    };

private:
    SingletonType _type;

public:
    Singleton( const Singleton& c ) = delete;
    Singleton& operator=( const Singleton& c ) = delete;
    virtual ~Singleton();

protected:
    explicit Singleton( SingletonType type );
    void logMemoryAllocation( bool isAllocated ) const;
};

} // namespace linx

#endif // !SINGLETON_H

Single.cpp
#include "Singleton.h"
#include "Logger.h"
#include "ExceptionHandler.h"

#include <string>
#include <array>

namespace linx {

struct SingletonInfo {
    const std::string singletonName;
    bool  isConstructed;

    SingletonInfo( const std::string& singletonNameIn ) :
        singletonName( singletonNameIn ),
        isConstructed( false ) {}
};

// Order must match types defined in Singleton::SingletonType
static std::array<SingletonInfo, 1> s_aSingletons = { SingletonInfo( "Logger" ) };

Singleton::Singleton( SingletonType type ) :
_type( type ) {
    bool saveInLog = s_aSingletons.at( TypeLogger ).isConstructed;

    try {
        if( !s_aSingletons.at( type ).isConstructed ) {
            // Test Initialize Order
            for( int i = 0; i < type; ++i ) {
                if( !s_aSingletons.at( i ).isConstructed ) {
                    throw ExceptionHandler( s_aSingletons.at( i ).singletonName +
                                            " must be constructed before constructing " +
                                            s_aSingletons.at( type ).singletonName,
                                            saveInLog );
                }
            }
            s_aSingletons.at( type ).isConstructed = true;
        } else {
            throw ExceptionHandler( s_aSingletons.at( type ).singletonName +
                                    " can only be constructed once.",
                                    saveInLog );
        }
    } catch( std::exception& ) {
        // type is out of range
        std::ostringstream stream;
        stream << __FUNCTION__ << " Invalid Singleton Type specified: " << type;
        throw ExceptionHandler( stream, saveInLog );
    }
}

Singleton::~Singleton() {
    s_aSingletons.at( _type ).isConstructed = false;
}

void Singleton::logMemoryAllocation( bool isAllocated ) const {
    if( isAllocated ) {
        Logger::log( "Created " + s_aSingletons.at( _type ).singletonName );
    }  else {
        Logger::log( "Destroyed " + s_aSingletons.at( _type ).singletonName );
    }
}

} // namespace linx

TextFileWriter
#ifndef TEXT_FILE_WRITER_H
#define TEXT_FILE_WRITER_H

#include "FileHandler.h"

namespace linx {

class TextFileWriter : public FileHandler {
public:
    explicit TextFileWriter( const std::string& filename, bool appendToFile, bool saveExceptionInLog = true );
    virtual ~TextFileWriter() = default;

    void write( const std::string& str );

    TextFileWriter( const TextFileWriter& ) = delete;
    TextFileWriter& operator=( const TextFileWriter& ) = delete;
};

} // namespace linx

#endif // !TEXT_FILE_WRITER_H

TextFileWriter.cpp
#include "TextFileWriter.h"

namespace linx {

TextFileWriter::TextFileWriter( const std::string& filename, bool appendToFile, bool saveExceptionInLog ) :
    FileHandler( filename, saveExceptionInLog ) {
    _file.open( _filenameWithPath.c_str(),
                std::ios_base::out | (appendToFile ? std::ios_base::app : std::ios_base::trunc) );
    if( !_file.is_open() ) {
        throwError( __FUNCTION__ + std::string( " can not open file for writing" ) );
    }
}

void TextFileWriter::write( const std::string& str ) {
    _file << str;
}

} // namespace linx

FileHandler.h
#ifndef FILE_HANDLER_H
#define FILE_HANDLER_H

#include <string>
#include <sstream>
#include <fstream>

namespace linx {

class FileHandler {
private:
    bool _saveExceptionInLog;

protected:
    std::fstream _file;
    std::string  _filePath;
    std::string  _filenameWithPath;

public:
    virtual ~FileHandler();

    FileHandler( const FileHandler& c ) = delete;
    FileHandler& operator=( const FileHandler& c ) = delete;

protected:
    FileHandler( const std::string& filename, bool saveExceptionInLog );
    void throwError( const std::string& message ) const;
    void throwError( const std::ostringstream& message ) const;

    bool getString( std::string& str, bool appendPath );
};

} // namespace linx

#endif // !FILE_HANDLER_H

FileHandler.cpp
#include "ExceptionHandler.h"
#include "Logger.h"

namespace linx {

ExceptionHandler::ExceptionHandler( const std::string& message, bool saveInLog ) :
_message( message ) {
    if( saveInLog ) {
        Logger::log( _message, Logger::TypeError );
    }
}

ExceptionHandler::ExceptionHandler( const std::ostringstream& streamMessage, bool saveInLog ) :
_message( streamMessage.str() ) {
    if( saveInLog ) {
        Logger::log( _message, Logger::TypeError );
    }
}

const std::string& ExceptionHandler::getMessage() const {
    return _message;
}

} // namespace linx


text:
Q: Sending javascript variable axios to php Im trying to send a post request with axios to php. Im a bit lost, still new to this stuff.
in my react.js I have this. Im trying to send the value of searchTerm
axios.post(`http://www.fake.com/script.php`,{
  searchTerm:'test',
})
.then(function(response){
  console.log(response)
})
.catch(function(error){
  console.log(error);
})

In the script.php file which I have hosted on my site, I have this:
if(!empty($_POST)) {
    $searchTerm = $_POST["searchTerm"];
    echo $searchTerm;
    echo '<script>console.log('.$searchTerm.')</script>';
}

nothing is echoed on the actual page.
On the console, I have 3 things.

*

*XHR finished loading: OPTIONS "http://www.fake.com/script.php"

*data object, which includes config,data,headers,etc.

*XHR finished loading: POST "http://www.fake.com/script.php"


text:
Q: forLoop & joinField & different names I have a folder with an output (shapefiles) from an iteration. On this output, I want to perform a join between two attributetables.
So far so good. Here comes the tricky part.
There are different shapefiles (lets say 20), all with different names. Each attributetable has exactly the same amount of fields (maybe the numbers of rows differs).
What I want the script to do is: pick two specific attributetables which belong together (based on the name), join them and then go on to the next two attributetables until there are no more tables to join.
All shapefiles have different names, but where the %Name% stands in the script, the name is the same.
For example:
abc_clip_diss JOIN abc_full_diss
def_clip_diss JOIN def_full_diss
ghi_clip_diss JOIN ghi_full_diss

What I got so far and is not much because I am very new to python is that:
import arcpy

#set workspace
arcpy.env.workspace =

#set variables
inFeatures = "%Name%_clip_diss"
joinField = "WLType"
joinTable = "%Name%_clip_full"
fieldList = ["area_ha"]

#JoinField "JoinField_management (in_data, in_field, join_table, join_field, {fields})"
JoinField_management ("inFeatures" , "joinField" , "joinTable" , "fieldList")

I think a loop would be good here? But I did not understand that good how a loop works. I dont understand what that for XX in YY means. And I am not sure if I can do that thing: %Name%.
Any ideas, hints, suggestions?
EDIT 7/8/14 4:00 pm
import arcpy
import os

#set workspace
arcpy.env.workspace = "C:\\Users\\Documents\\Wetland\\New_Folder"
ws = arcpy.env.workspace

#create a list of features
fcl = arcpy.ListFeatureClasses()

#loop through the list
for fc in fcl:
    basename = fcl.split("_")[0] #split name of features and only take the first word as a basename

    inFeatures = os.path.join(ws, basename + "_clip_diss") #The table or feature class to which the join table will be joined.
    joinField = "WLType" #The field in the input table on which the join will be based.
    joinTable = os.path.join(ws, basename + "_clip_full") #The table to be joined to the input table.
    fieldList = "WLType" #The field in the join table that contains the values on which the join will be based.

    #JoinField "JoinField_management (in_data, in_field, join_table, join_field, {fields})"
    arcpy.JoinField_management(inFeatures , joinField , joinTable , fieldList)

Running this code I run into several problems. The biggest was the Error 000732 which said 'files do not exist'.
I converted all my shapefiles into a geodatabase which did the trick. The Geodatabase is in the folder "New_Folder".
But running the code now, still does not work. It does not Join one table to another.
I am wondering, where the problem is. Can anyone see it?

A: The attached (untested) script takes the name of a feature class, splits it by "_" and uses that as a basename for the join operations.  The general idea is to use:
basename = fc.split("_")[0]

which converts, for example, abc_clip_diss to abc
Then, you can use that basename to create new variables with os.path.join():
inFeatures = os.path.join(ws, basename + "_clip_diss")
joinTable = os.path.join(ws, basename + "_clip_full")

Finally, combine this syntax in a for loop so that you can iterate over a series of feature classes.

import arcpy, os

#set workspace
arcpy.env.workspace = r'C:\path\to\your\fcs'
ws = arcpy.env.workspace

fcs = arcpy.ListFeatureClasses()

for fc in fcs:
    basename = fc.split("_")[0]

    #set variables
    inFeatures = os.path.join(ws, basename + "_clip_diss")
    joinField = "WLType"
    joinTable = os.path.join(ws, basename + "_clip_full")
    fieldList = ["area_ha"]

    #JoinField "JoinField_management (in_data, in_field, join_table, join_field, {fields})"
    arcpy.JoinField_management (inFeatures , joinField , joinTable , fieldList)


text:
Q: Docker container with Nginx and Angular and other container with Asp.net core cannot get the rever proxy via nginx working I am building two conatiners with one container having the .net core api running and another with nginx and angular application running. Happy to receive feedback if this approach is not a right one.
Angular is using uri of localhost:4000/api to invoke the api.
Nginx is listening on port 4000 and proxies them to port 5000 where the API is listening.
I can get my two docker services both noticeapi and the reverseproxywithui up and running. But when I browse the ui and click the search button on the UI which invokes the api, i get connection refused error for the api invocation, which means nginx is rejecting the calls to the api.
Here is my docker-compose.yml
version: '3.4'

networks:
  corp:
    driver: bridge

services:

  reverseproxyandui:
    image: ${DOCKER_REGISTRY-}reverseproxyandui
    build:
     context: ./notice-ui-app
     dockerfile: ui.prod.dockerfile
    container_name: reverseproxyandui
    networks:
      - corp

    ports:
      - "80:80"
    restart: always
    depends_on :
      - noticeservice

  noticeservice:

    image: ${DOCKER_REGISTRY-}noticeservice
    build:
      context: .\noticeService
      dockerfile: noticeService/Dockerfile
    container_name: noticeservice
    networks:
      - corp
    ports:
      - "5000:5000"
    restart: always

My docker file for the api is as follows
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app

EXPOSE 1433
EXPOSE 5000

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["NotificationService/NotificationService.csproj", "NoticeService/"]
RUN dotnet restore "NoticeService/NoticeService.csproj"
COPY . .
WORKDIR "/src/NoticeService"
RUN dotnet build "NoticeService.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "NoticeService.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .

ENV ASPNETCORE_ENVIRONMENT=Development
ENV ASPNETCORE_URLS=http://*:5000

ENTRYPOINT ["dotnet", "NoticeService.dll"]

The docker file for my angular UI is as follows:
###Stage 1
FROM node as node
WORKDIR /webclientapp
COPY package.json package.json
RUN npm install

#Angular CLI
RUN npm install -g @angular/cli@8.3.3

COPY . .

RUN npm run build -- --prod

FROM nginx:alpine

## Remove default Nginx website
RUN rm -rf /usr/share/nginx/html/*

VOLUME /var/cache/nginx
COPY --from=node /webclientapp/dist/Notice-ui-app /usr/share/nginx/html
COPY ./config/nginx.conf /etc/nginx/nginx.conf

CMD ["nginx", "-g", "daemon off;"]

And the final file which is the nginx config as follows:
worker_processes auto;

events { worker_connections 1024; }

http {

    sendfile on;

    upstream noticeservice {
        server noticeservice:5000;
    }

    server {
        listen 80;
        listen 4000;
        server_name  localhost;

        gzip                    on;
        gzip_comp_level         6;
        gzip_vary               on;
        gzip_min_length         1000;
        gzip_proxied            any;
        gzip_types              text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
        gzip_buffers            16 8k;
        client_max_body_size    256M;

        root /usr/share/nginx/html;

        index  index.html index.htm;
        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        location / {
            try_files $uri $uri/ /index.html =404;
        }

         location /api {
            proxy_pass         http://localhost:5000;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Proto $scheme;
            proxy_set_header   X-Forwarded-Host $server_name;

        }
    }

}

Appreciate your help with this.

A: The issue is with the Nginx config.
Found the answer on the following link
"When this is hosted in AWS Fargate task, we need change the value of 'upstream app_servers' to '127.0.0.1:5000'. Because when the Fargate task runs in Awsvpc networking mode (which is default) it will use the local loopback interface of 127.0.01 to connect to the other container (service) defined as a part of the Fargate task which will be covered in the later sections."
So my Ngnix config is now different for dev and Prod.
In Prod I have update proxy pass to use local loop back address of 127.0.0.1:5000 and use service name when running on my dev machine.


text:
Q: how to round up currency to the nearest 50 cent in java? I created a simple android currency converter app where the user enters the value in euro and the converted price is displayed in other currencies.
But how do I round up the numbers to the nearest 50 cent? so if 1 euro is equal to 1.3395 dollars how do I get the app to display 1.50 dollars?
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText editEuro = (EditText) findViewById(R.id.editEuro);
        final EditText editAud = (EditText) findViewById(R.id.editAud);
        final EditText editCad = (EditText) findViewById(R.id.editCad);
        final EditText editNzd = (EditText) findViewById(R.id.editNzd);
        final EditText editGbp = (EditText) findViewById(R.id.editGbp);
        final EditText editUsd = (EditText) findViewById(R.id.editUsd);

        Button buttonConvert = (Button)findViewById(R.id.buttonConvert);

        buttonConvert.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                double euro = Double.valueOf( editEuro.getText().toString());

                double aud = euro *  1.4471 ;
                double cad = euro *  1.4635 ;
                double nzd = euro *  1.5835 ;
                double gbp = euro *  0.7965 ;
                double usd = euro *  1.3395 ;

                editAud.setText(String.valueOf(aud));
                editCad.setText(String.valueOf(cad));
                editNzd.setText(String.valueOf(nzd));
                editGbp.setText(String.valueOf(gbp));
                editUsd.setText(String.valueOf(usd));

            }
        });
    }

A: There is code-snippet for such things.
double value = 1.3395; // your value
double roundTo = 0.5; // number that you round to

value = roundTo * Math.round(value / roundTo);

A: One way is to multiply your input by 2, round that to zero decimal places, and divide by 2.
If your rounding function returns an integral type, then take care not to divide by an integral literal else the division will take place in integer arithmetic and you'll lose any fraction. Multiplying the final result by 0.5 instead of dividing by 2 will circumvent this.


text:
Q: Linux Server Socket to Windows Client Socket Hi im writing a code that will connect a windows client to a linux server socket.
I can already established a connection but it seems like the linux server are always cutting my connection after a few seconds without sending me back the response i needed.
Also i already tried using telnet but again after a few seconds the linux server cut my connection.
Is there a problem connecting to a linux server socket using windows socket?
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("IPADDRESS"), 6004);
            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint. Catch any errors.
            try
            {
                if (!sender.Connected)
                    sender.Connect(remoteEP);

                string data = new Client().Test();

                DE_ISO8583 de = new ISO8583().Parse(data);

                data = data.Length.ToString().PadLeft(4, '0') + data;
                byte[] msg = Encoding.ASCII.GetBytes(data);

                int bytesSent = sender.Send(msg);

                //// Receive the response from the remote device.
                int bytesRec = sender.Receive(bytes);
                Console.WriteLine("Received = {0}",
                    Encoding.ASCII.GetString(bytes, 0, bytesRec));

                //sender.Disconnect(true);

                //sender.Shutdown(SocketShutdown.Both);
                //sender.Close();
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

A: The server may be closing the connection due to no activity.  Enabling the keepalive option will send an empty datagram to the server periodically to keep the connection alive.  See code below

            TcpClient client = new TcpClient();
            client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);


text:
Q: Google's Mentality: ListView in ScrollView I'm one of the poor noobs who wanted to put a ListView inside a ScrollView.
Now I understand that they don't want nested scrollable elements - I'm not sure that I agree with their design but I can understand it. What I cannot understand is why I can't make a non-scrollable ListView and nest it into another Scrollable element.
listView.setScrollContainer(false) seemed like the solution (because I thought it could turn off the scrollability of the ListView) but no luck.
So can someone explain why Google won't let listViews not scroll - is there a way to do this that this numpty is just oblivious to?

A: You could use a LinearLayout as your non-scrollable ListView.  A lot of the power of ListView is how it deals with lazy-loading of elements.  This doesn't really make sense in the context of a non-scrollable version.
But really, you most likely need to rethink your UI.  Why do you need multiple scrolling sections?  That seems really unfriendly from a user's perspective.  You can easily place things above and below a ListView via a header or footer.

A: Like Mayra said, you should rethink your UI.
Unless you have multiple ListViews, I can see a solution to your problem. Since you seem to have only one list view in your scroll view. That means that you wanted to put something above or below.
You there have setHeader, setFooter. There you just have to put anything you want. You have to add theses views before setAdapter().
If you have multiple ListViews in your scrollview. I have a second solution for you. I can't really elaborate. But you'd have to create a custom adapter and override ViewTypeCount so you can handle multiple types of items. That way you can load everything you want through the adapter. And all you really need is a ListView.
If you want to handle multiple types of items (multiple listviews) here is an example "untested"
You have to subclass adapter and override getView. Habitually we should have something similar to that for view recycling
if(view == null){
    //inflate view
}

In your case, you'll need to do that.
package com.neutrino.lvt;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Main extends Activity {
    private ListView lv;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lv = (ListView)findViewById(R.id.lv);

        ArrayList<Items> items = new ArrayList<Items>();

        items.add(new ItemA("Une"));
        items.add(new ItemA("Une3"));
        items.add(new ItemA("Une4"));
        items.add(new ItemA("Une5"));
        items.add(new ItemA("Une6"));
        items.add(new ItemA("Une7"));
        items.add(new ItemA("Une8"));
        items.add(new ItemA("Une9"));
        items.add(new ItemA("Une0"));
        items.add(new ItemA("Une0-"));
        items.add(new ItemB("bbb", "cc1c"));
        items.add(new ItemB("bbb3", "c2cc"));
        items.add(new ItemB("bbb4", "c2cc"));
        items.add(new ItemB("bbb5", "c1cc"));
        items.add(new ItemB("bbb6", "cc5c"));
        items.add(new ItemB("bbb7", "cc4c"));
        items.add(new ItemB("bbb7", "c2cc"));
        items.add(new ItemB("bbb8", "c1cc"));
        items.add(new ItemB("bbb9", "cc6c"));
        items.add(new ItemB("bbb0", "cc8c"));
        items.add(new ItemB("bbb0", "cc0c"));
        items.add(new ItemB("bb3b", "cc6c"));
        items.add(new ItemA("Une"));
        items.add(new ItemA("Une3"));
        items.add(new ItemA("Une4"));
        items.add(new ItemA("Une5"));
        items.add(new ItemA("Une6"));
        items.add(new ItemA("Une7"));
        items.add(new ItemA("Une8"));
        items.add(new ItemA("Une9"));
        items.add(new ItemA("Une0"));
        items.add(new ItemA("Une0-"));
        items.add(new ItemB("bbb6", "cc5c"));
        items.add(new ItemB("bbb7", "cc4c"));
        items.add(new ItemB("bbb7", "c2cc"));
        items.add(new ItemB("bbb8", "c1cc"));
        items.add(new ItemB("bbb9", "cc6c"));
        items.add(new ItemB("bbb0", "cc8c"));
        items.add(new ItemB("bbb0", "cc0c"));
        items.add(new ItemB("bb3b", "cc6c"));

        SpecialAdapter b = new SpecialAdapter(this, items);
        lv.setAdapter(b);

    }

    private class SpecialAdapter extends BaseAdapter{

        List<Items> list;
        Context context;

        public SpecialAdapter(Context context, List<Items> list) {
            this.list = list;
            this.context = context;
        }

        public Context getContext(){
            return this.context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Items getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return list.get(position).hashCode();
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            Items b = getItem(position);
            if(b instanceof ItemA){
                return 0;
            }else{
                return 1;
            }
        }

        @Override
        public View getView(int position, View v, ViewGroup parent) {
            Items o = getItem(position);
            if(v == null){
                LayoutInflater vi = (LayoutInflater)this.getContext()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                if(getItemViewType(position) == 0){
                    v = vi.inflate(
                                     android.R.layout.simple_list_item_multiple_choice,
                                     null
                                    );
                    Log.i(this.getClass().getName(),
                                        "Inflate two line"
                                    );
                }else{
                    v = vi.inflate(
                                     android.R.layout.two_line_list_item,
                                     null
                                    );
                    Log.i(this.getClass().getName(),
                                     "Inflate one line"
                                    );
                }
            }

            switch (getItemViewType(position)) {
            case 0:
                ItemA oa = (ItemA)o;
                ((TextView)v.findViewById(android.R.id.text1)).setText(oa.toString());
                break;
            case 1:
                ItemB ob = (ItemB)o;
                ((TextView)v.findViewById(android.R.id.text1)).setText(ob.toString());
                ((TextView)v.findViewById(android.R.id.text2)).setText(ob.getClasse());
                break;
            }
            return v;
        }

    }

    private abstract class Items {}

    private class ItemA extends Items {
        String name;

        public ItemA(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "ItemA: " + name;
        }
    }

    private class ItemB extends Items {
        private String name;
        private String classe;

        public ItemB(String name, String classe) {
            this.name = name;
            this.classe = classe;
        }

        public String getClasse(){
            return classe;
        }

        @Override
        public String toString() {
            return "ItemB: " + name;
        }
    }
}

I'll try to write a sample and come up with an update soon. I think I'm missing something because when views are recycled you need to check if the recycled view correspond to the ItemType. But you can definitely do it through a ListView alone. No scrollable needed.


text:
Q: How to read dynamic/changing keys from JSON in Python I am using the UK Bus API to collect bus arrival times etc.
In Python 3 I have been using....
try:
    connection = http.client.HTTPSConnection("transportapi.com")
    connection.request("GET", "/v3/uk/bus/stop/xxxxxxxxx/live.json?app_id=xxxxxxxxxxxxxxx&app_key=xxxxxxxxxxxxxxxxxxxxxxxxxxx&group=route&nextbuses=yes")

    res = connection.getresponse()
    data = res.read()
    connection.close()

    from types import SimpleNamespace as Namespace
    x = json.loads(data, object_hook=lambda d: Namespace(**d))

    print("Stop Name : " + x.stop_name)

Which is all reasonably simple, however the JSON  data returned looks like this...
{
   "atcocode":"xxxxxxxx",
   "smscode":"xxxxxxxx",
   "request_time":"2020-03-10T15:42:22+00:00",
   "name":"Hospital",
   "stop_name":"Hospital",
   "bearing":"SE",
   "indicator":"adj",
   "locality":"Here",
   "location":{
      "type":"Point",
      "coordinates":[
         -1.xxxxx,
         50.xxxxx
      ]
   },
   "departures":{
      "8":[
         {
            "mode":"bus",
            "line":"8",
            "line_name":"8",
            "direction":"North",
            "operator":"CBLE",
            "date":"2020-03-10",

Under "departures" the key name changes due to the bus number / code.
Using Python 3 how do I extract the key name and all subsequent values below/within it?
Many thanks for any help!

A: You can do this:
for k,v in x["departures"].items():
    print(k,v) #or whatever else you wanted to do.

Which returns:
8 [{'mode': 'bus', 'line': '8', 'line_name': '8', 'direction': 'North', 'operator': 'CBLE', 'date': '2020-03-10'}]
So k is equal to 8 and v is the value.


text:
Q: Out of memory when using android bitmaps I am trying to get inputstream by passing url of the image, but when i have more images requested it says out of memory and after sometimes the server restarts.
public InputStream getBitmap(String imagePath, int THUMBSIZE ){
        Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath), THUMBSIZE, THUMBSIZE);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ThumbImage.compress(CompressFormat.PNG, 0 , bos);
        ThumbImage.recycle();
        byte[] bitmapdata = bos.toByteArray();
        InputStream bs = new ByteArrayInputStream(bitmapdata);
        return bs;
    }

this is where i use above method, why it is giving out of memory error ?
String query_file = parameters.get("fname");
String Mime = get_mime(query_file);
String original_path = root.getAbsolutePath()+query_file;
InputStream br = this.getBitmap(original_path, 96);

A: Have a good look at this documetation: Documentation

This lesson walks you through decoding large bitmaps without exceeding the per application memory limit by loading a smaller subsampled version in memory.

scale your Image to the needed size and alloc your memory.

A: welcome to the error called
java.lang.OutOfMemoryError: bitmap size exceeds VM budget

that happens when you load high resolution heavy image or images from the url.
The Android Training class, "Displaying Bitmaps Efficiently" or try "Universal Image Loader", offers some great information for understanding and dealing with the exception.


text:
Q: App android siempre vertical? Quiero que mi APP solo se ejecute verticalmente pero no lo consigo, he implementado lo siguiente sin éxito.
Manifest:
< application
        ...
        android:configChanges="orientation"
        android:screenOrientation="portrait">

Actividad:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:orientation="vertical">

A: En su archivo Mainfest.xml encuentre las etiquetas de las actividades que desea bloquear en una rotación determinada.
Necesita agregar a toda su actividad no solo para uno, es decir, establezca esto para todas sus actividades:
<activity android:name=".SuActivity"
android:configChanges="orientation"
android:screenOrientation="portrait"/>

Explicación:

*

*android:configChanges="orientation" será responsable de los cambios de orientación.

*android:screenOrientation="portrait" configura el modo de orientación predeterminado.

Otra forma es:
Usar setRequestedOrientation() como se muestra aquí:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
setContentView(R.layout.main);

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


text:
Q: Convert festival tts to flite tts i currently have a tts which is built using festival and festvox. i need to convert these voices and build a TTS in flite. apparently you can do the conversion using festvox (the festvox and flite websites say so but no proper steps on how to do it). can some one please help me out with it as i am new to this area?
thanx in advance ..

A: Just in-case anyone else was wondering the same i found the steps mentioned in this document useful and also subscribe to the mailing lists and feel free to ask question.
although i must mention i never implemented to TTS using "flite". i went ahead with "espeak"


text:
Q: Sorting in gridview is not working I am trying Sorting functionality in Grid view but its not working.Can some body help?
Code:
  private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
    string newSortDirection = String.Empty;

    switch (sortDirection)
    {
        case SortDirection.Ascending:
            newSortDirection = "ASC";
            break;

        case SortDirection.Descending:
            newSortDirection = "DESC";
            break;
    }

    return newSortDirection;
}
protected DataSet FillDataSet()
{
    string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
    con = new SqlConnection(source);
    cmd = new SqlCommand("proc_mygrid", con);
    ds = new DataSet();
    da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();

    return ds;

}
 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    DataTable dt = GridView1.DataSource as DataTable;
    if (dt != null)
    {
        DataView dv = new DataView(dt);
        dv.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
        GridView1.DataSource = dv;
        GridView1.DataBind();
   }

Here dt is coming null.why? pls help thanks.
EDIT:
enter code here  <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
    GridLines="None" AllowPaging="true" AllowSorting="true" PageSize="12"
    onpageindexchanging="GridView1_PageIndexChanging"
    onsorting="GridView1_Sorting">

EDIT(Total code)
public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    DataSet ds;
    SqlDataAdapter da;
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private string ConvertSortDirectionToSql(SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;

        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;

            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }

        return newSortDirection;
    }
    protected DataSet FillDataSet()
    {
        string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
        con = new SqlConnection(source);
        cmd = new SqlCommand("proc_mygrid", con);
        ds = new DataSet();
        da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();

        return ds;

    }
    protected void GetValues(object sender, EventArgs e)
    {
        FillDataSet();
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
       int newPagenumber = e.NewPageIndex;
       GridView1.PageIndex = newPagenumber;
       GridView1.DataSource = FillDataSet();
       GridView1.DataBind();

    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {

        DataSet ds = FillDataSet();
        DataTable dt = ds.Tables[0];
        if (dt != null)
        {
            dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

A: CODE:
private string GetSortDirection(string column)
{
       string sortDirection = "DESC";
       string sortExpression = ViewState["SortExpression"] as string;

       if (sortExpression != null)
       {
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "DESC"))
                {
                    sortDirection = "ASC";
                }
            }
       }

       ViewState["SortDirection"] = sortDirection;
       ViewState["SortExpression"] = column;

       return sortDirection;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
   DataTable dt = ((DataSet)Session["myDataSet"]).Tables[0];
   dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
   GridView1.DataSource = dt;
   GridView1.DataBind();
}

A: Because you're setting a DataSet as DataSource and then casting it to DataTable with the operator as.
The 'as' operator in C# is a tentative cast - if it's impossible to cast (types are not compatible) instead of throwing an exception as the direct cast the 'as' operator sets the reference to null.
If you only have one datatable in your dataset then you can get the first element like this:
ds.Tables[0];

... or use the name of the table:
ds.Tables["myTable"];

in your case you can try...
DataTable dt = GridView1.DataSource.Tables[0] as DataTable;

Hope it helps!
EDIT:
with regards to your sorting problem (once you get the datatable):
if (dt != null)
{
   dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
   GridView1.DataBind();
}

You can do this because dt is a reference to the exact same object that's already set as DataSource for your grid. It should do the trick - if not there's smt else I am missing (such as we're sorting the wrong table meaning you have more than one table in the DataSet).
EDIT:
had a look at your code. I don't know exactly when GetValues gets fired but I suspect it's causing your problem (I think it might be overriding your sorting or smt along those lines).
If you comment out FillDataSource from getValues and modify your PageLoad to do this:
  void Page_Load(Object sender, EventArgs e)
  {

     // Load data only once, when the page is first loaded.
     if (!IsPostBack)
     {
        Session["myDataSet"] = FillDataSet();
     }

  }

then in your sort method you retrieve the DataSource like this:
DataTable dt = ((DataSet)Session["myDataSet"]).Tables[0];

Also you can retrieve the DataSet from session in your pagination handler method.
You should also notice an improvement in performance since you're retrieving the stuff form the db just once.
Give it a shot!

A: In Testing.aspx.cs
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    if (dataset != null)
    {
        datatable = dataset.Tables[0];
        DataView dataView = new DataView(datatable);
        dataView.Sort = e.SortExpression;
        GridView1.DataSource = dataView;
        GridView1.DataBind();
    }
}

In Testing.aspx
<asp:GridView ID="GridView1" runat="server"
              AllowSorting="True" OnSorting="GridView1_Sorting">


text:
Q: Model update with Eloquent causes out of memory I'm trying to update my item models with a new description, but when the ConsoleCommand is executed it will throw an out of memory. If I create a new item model, there are no issues. My suspicion goes to that it tries to update all records instead of the item I pointed out.
$items = Item::query()->where('description', '=', '')->get();
foreach ($items as $item) {
    if ($item->exists()) {
        $item->description = "new description";
        $item->save();
   }
}

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes) in ..\vendor\illuminate\support\Str.php on line 2710
PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes) in ..\vendor\illuminate\support\Str.php on line 2710
count($items) = 3255
count($item) = 1

$items->count() = 3255
$item->count() = 3255

EDIT1:
This question focusses on why the call of $item->save() causes an out of memory. When only one model is trying to be saved/updated.
EDIT2:
Why would the following code still throw an out of memory?
$item = Item::where('description', '=', '')->first();
$item->description = "new description";
$item->save();

but not when the following is used instead of ->save():
Item::where('item_id', '=', $item->item_id)->update($item->toArray());

A: You're querying for all items, that's why you get an error. It's like copying all data from the table into memory. If descriptions are different in each row, try to use update() method instead to update rows one after the other:
foreach ($data as $row) {
    Item::where('description', 'old description')
        ->update(['description' => 'new desccription']);
}

Don't forget to add description to a $fillable array.
If for some reason you really want to use save() instead of update(), you can use chunk() method to load data.

Using the chunk method will conserve memory when working with large result sets

A: Your can use update() function to update multiple rows in single query as:
Item::where('description', '=', '')
    ->update(['description' => 'new description']);

A: Not sure if this helps but I had the exact same issue... it was because the Model I was called "save" on did not have a primary key.


text:
Q: Setting Flask configuration values doesn't seen to work I'm trying to set app.config['FLASK_ENV'] = 'development' but when I run the app it starts runs with default configs (production environment).
My code is as simple as possible:
from flask import Flask
app = Flask(__name__)
app.config['FLASK_ENV'] = 'development'

@app.route('/')
def hello_world():
    return 'Hello, World!'

I'm kind of frustrated with Flask at this point as growing from a single file app example to a more structured small app is not covered in documentation. Every single example I found goes from hello world to a full large app, which makes the learning kind of a pain.

A: It seems that you're setting configurations correctly, but from the Flask configuation docs, you won't be able to set the environment in the code.

The ENV and DEBUG config values are special because they may behave
  inconsistently if changed after the app has begun setting up. In order
  to set the environment and debug mode reliably, Flask uses environment
  variables.

You can run development mode by calling the following:
$ export FLASK_ENV=development
$ flask run

Or, the answer here has other alternatives to set environment variables for your flask application.