text:
Q: Real life usage of Benford's Law I recently discovered Benford's Law. I find it very fascinating. I'm wondering what are some of the real life uses of Benford's law. Specific examples would be great.

A: It may or may not be useful for detecting fraud in elections, for example the 2009 Iranian election.
Some links:
http://sbseminar.wordpress.com/2009/06/15/benfords-law-and-the-iranian-election
http://www.fivethirtyeight.com/2009/06/statistical-evidence-does-not-prove.html

A: You know those numbers on houses that tell you the address? Like, say, 1205 Main Street, Sometown USA. If you run a store that sells those numbers, you should probably stock more 1s and 2s than 8s and 9s. Building contractor supply stores probably know about Benford's law this way. Hardware stores (like ACE, TruValue, etc.) probably don't. In fact, the next time you go to the hardware store, try telling them you need to replace your house numbers. Tell them you live on 1129 some street.

A: Some of the data generated by Math Stack Exchange itself (and, presumably, by similar sites) ought to approximately follow Benford's law.  These would include the distribution of first digits of

*

*Frequency of tag use,

*Number of votes for questions,

*User reputation,

*Number of views for questions.

This is because Benford's law applies to exponentially growing quantities, and the total number of all of these quantities ought to be growing exponentially.  It's only approximate because of artifacts in the way that some of these quantities are determined and because you need several orders of magnitude in order to see Benford's law really kick in.
Anyway, I decided to test this for the first three.  The first digits weren't actually that hard to compile because the site allows you to sort the first three from highest to lowest.  (Unfortunately, it does not allow you to sort the fourth that way, and I don't feel like wading through 2200+ questions to collect the data.) Here are the results I got on the first three.
Tag Use
(Data collected October 25, 2010.)

Not a bad fit, especially when you consider that there are only three orders of magnitude represented in this measure.  There are a disproportionately large number of tags that were created but only used once, which explains the larger frequency of 1 as a first digit.
Votes Per Question
(Data collected October 26, 2010.)

Also not a bad fit, especially since there are currently only two orders of magnitude represented in this measure.  Also, I threw out the questions with 0 and negative numbers of votes.
User Reputations
(Data collected October 25 and 26, 2010.)

This is the worst fit of the three, as the frequency of 1 as a first digit is so much larger than the others.  However, there are a very large number of users who have never posted a question or an answer and so have a rep of 1.  And, for reasons unknown to me, there are also a large number of users who have a reputation of 101, despite never having asked or answered a question.
If you remove 1 as a possible first digit and then rescale the Benford law probabilities to consider only 2 through 9 as possible first digits then the picture looks like the following, which is a much better Benford fit.

Admittedly, none of these data sets would pass Pearson's chi-square test for goodness-of-fit with respect to the Benford probabilities at a reasonable level of significance.  However, given some of the artifacts in the data and the fact that there are relatively few orders of magnitude represented, the fit with Benford's law is really not that bad.

A: I recently attended a lecture on this. So I'll list a few interesting points that I remember.
The original discovery was by Newcomb who noticed that tables of logarithms were more worn out in the front than the back. It was rediscovered by Benford in 1938.
Areas of countries, areas of rivers and sizes of populations obey this rule. A more surprising example claims the numbers that appear in newspapers also follow this rule. In spite of the many observances of Benford's law, not a lot of instances are fully explained. I believe there have been proposals to provide simple models to associate an 'exponential-like' behavior of the areas of countries, but I don't really know anything about them.
Another note on the forensic accounting example mentioned by workmad3, I remember the lecturer pointed out that evidence pertaining to Benford's law is considered admissible in court.
There are things that don't really obey Benford's law, for example: the number of pages in books.
and that's more or less what I can recall from the talk, hope that helps :)

A: From a physics perspective you can look at how Benford's law (or devations from it) can arise from the different stastical mechanics distributions (Boltzmann, Bose-Einstein, etc...). There is a good paper on the arVix that can get you started on this topic:
Abstract:

The occurrence of the nonzero leftmost digit, i.e., 1, 2, ..., 9, of numbers from many real world sources is not uniformly distributed as one might naively expect, but instead, the nature favors smaller ones according to a logarithmic distribution, named Benford's law. We investigate three kinds of widely used physical statistics, i.e., the Boltzmann-Gibbs (BG) distribution, the Fermi-Dirac (FD) distribution, and the Bose-Einstein (BE) distribution, and find that the BG and FD distributions both fluctuate slightly in a periodic manner around the Benford distribution with respect to the temperature of the system, while the BE distribution conforms to it exactly whatever the temperature is. Thus the Benford's law seems to present a general pattern for physical statistics and might be even more fundamental and profound in nature. Furthermore, various elegant properties of Benford's law, especially the mantissa distribution of data sets, are discussed.

The Significant Digit Law in Statistical Physics

A: Forensic accountancy is a popular use, and is actually admissible as evidence in the USA.

A: I've heard of it being as a rough check to see if accounting numbers were being made up

A: I think that Benford's law is quite intuitive in "real life", but it would indeed be more suprising if it would often hold in mathematics, and in fact it does, here is a nice related student paper.

A: Here's an article from about a year ago in the German Economic Review, in which the authors use Benford's law to analyze economic data among countries using the euro.  They find that Greece's economic data just before joining the euro differed significantly from the Benford's law predictions.  The implication is that Greece may have manipulated their numbers in order to comply with the terms of the Maastricht Treaty (which sets criteria for full membership in the European Monetary Union).  See, for instance, this blog post.  I find this particularly interesting in light of Greece's recent financial troubles.
Here's the abstract from the article: "To detect manipulations or fraud in accounting data, auditors have successfully used Benford's law as part of their fraud detection processes. Benford's law proposes a distribution for first digits of numbers in naturally occurring data. Government accounting and statistics are similar in nature to financial accounting. In the European Union (EU), there is pressure to comply with the Stability and Growth Pact criteria. Therefore, like firms, governments might try to make their economic situation seem better. In this paper, we use a Benford test to investigate the quality of macroeconomic data relevant to the deficit criteria reported to Eurostat by the EU member states. We find that the data reported by Greece shows the greatest deviation from Benford's law among all euro states."  (emphasis mine)
See also this question on quant.SE (where I first learned of this).

A: There is a negative application for databases. Often record numbers in a database are assigned sequentially.
Another common thing is to want to partition records into multiple databases serving as one big database. If you don't know what the maximum value would be, you might be tempted to divide the records between databases based upon string comparison of the sequentially-assigned record number starting with the first (non-zero) digit of the sequence number for example, all starting with "1" goes into database 1, starting with "2" goes into database 2, etc. (and you can use string ranges to perform division into more or less than 9 ranges in a similar fasion) only to discover that your first database (partition) for record numbers starting with "1" now has on average 5 or 6 times as much data in it as your last database (partition) more or less, so you don't achieve the balance between partitions you wanted (even if you were dividing into more or less than 9 partitions with apparently-evenly-divided digit ranges).
There are other ways of partitioning based upon record number to disable Benford's law, such as comparing digits in reverse order, i.e. all record numbers that end in "1" go in database 1, etc.
(FWIW, in a prior post, I cannot understand why the number of pages in books (the length of books) would not follow Benford's law just like the lengths of rivers. Maybe someone was thinking of numbers in a telephone book.)


text:
Q: How to use different jest.config.js for unit and component tests? I am trying to create a separate suite of tests for component level testing of an app.
In this separate suite, I will need a custom test environment that bootstraps some persistence layer mocks and these tests will be housed in a separate folder in my project structure from my unit tests.
e.g. the unit tests will be nearby the code in __tests__ folders while the component tests will be in a top-level tests/ directory.
I already have most of my jest.config.js setup, but when I added the projects section to override some of the fields, specifically testMatch and testEnvironment it completely disregarded my configuration specified in global.
Now I've been reading that the projects configuration is mostly about monorepo setups, so I don't think that's the right approach.
Ideally I could just have a separate jest.config.js in my tests/ directory, but I don't see how to set that up if that even works.
Any insight into this problem would be helpful. Thanks ahead of time.

A: What I ended up doing was to specify separate projects in package.json
"jest": {
    "projects": [
        "<rootDir>/jest.unit.config.js",
        "<rootDir>/tests/jest.component.config.js"
    ]
}

This allowed me to run either jest on its own and it will run all projects or if I wanted to specify a specific config to run I could run jest --projects jest.unit.config.js and it will just run that specific project.
I could also add a scripts section to my package.json to run them more easily.
"scripts": {
    "test": "jest",
    "test:unit": "jest --projects tests/jest.unit.config.js",
    "test:component": "jest --projects jest.component.config.js"
}

A: To specify different config files you can use the --config option.
For example if you have a tests/jest.config.js file configuration for your component tests and a jest.config.js file for your unit tests, you can configure the scripts in your package.json so that they look something like this:
"scripts": {
    "tests:unit": "jest --config=jest.config.js",
    "tests:component": "jest --config=tests/jest.config.js"
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hybrid model using mlxtend I am trying to create a hybrid model of GRU, XGBoost, NN, and linearRegression. I am using mlxtend for stackingRegression. However, when I try to fit the final model, I get an error "cannot clone". Some help should be highly appreciated. The error and my code are below.
models = [modelG, modelD, modelX]
meta_model = LinearRegression()
model_hybrid = StackingRegressor(regressors = models, meta_regressor = meta_model)
model_hybrid.fit(X_train, y_train)

TypeError: Cannot clone object '<tensorflow.python.keras.engine.sequential.Sequential object at 0x0000019E8D6D9730>' (type <class 'tensorflow.python.keras.engine.sequential.Sequential'>): it does not seem to be a scikit-learn estimator as it does not implement a 'get_params' method.


text:
Q: How to Remove validation from left table data in django 2nd Screenshot of APIAPI Sample Screenshot
I'm New in Django, i want to help regarding validations in screenshot there is company_name, location, title and user_location fields except user info with proper validation
but i want to remove validations from  company_name, location, title and user_location fields how to do?
Please find the above api screenshot and
Please find the below scripts,
views.py
class UserRegistrationView(generics.CreateAPIView):
    """
    Register a new user.
    """
    queryset = User.objects.all()
    permission_classes = (permissions.AllowAny, )

    def get_serializer_class(self, user_type=None):
        if user_type == 'student':
            return StudentRegistrationSerializer
        return ProfessionalRegistrationSerializer

    def post(self, request, user_type=None, format=None):
        serializer_class = self.get_serializer_class(user_type)
        serializer = serializer_class(data=request.data, context={'request': request})

        if serializer.is_valid(raise_exception=True)

            user = serializer.save(work_status=user_type)
            token, created = Token.objects.get_or_create(user=user)
            data = BasicUserSerializer(user, context={'request': request}).data
            data.update({"token": token.key})
            return Response(data)

serializes.py
class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):

    password = serializers.CharField(max_length=20, write_only=True)
    experiences = ExperienceSerializer(required=False)
    email = serializers.EmailField()
    first_name = serializers.CharField(max_length=30)
    last_name = serializers.CharField(max_length=30)

    class Meta:
        model = User
        fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
        'experiences', 'headline')

    def validate_email(self, value):
        from validate_email_address import validate_email
        if User.all_objects.filter(email=value.lower()).exists():
            raise serializers.ValidationError('User with this email already exists.')
        # if not validate_email(value.lower(), check_mx=True):
        #     raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
        return value.lower()

    def create(self, validated_data):
        experiences = validated_data.pop('experiences')
        password = validated_data.pop('password')
        email = validated_data.pop('email')
        user = User.objects.create(
            username=email.lower(),
            email=email.lower(),
            role_id=1)
        user.set_password(password)
        user.save()
        user_location = experiences.pop('user_location')
        if hasattr(user, 'location'):
            user.location.location = user_location
            user.save()
        else:
            UserLocation.objects.create(user=user, location=user_location)
            Experience.objects.create(user=user)
        return user

Another serializes.py for Experiance
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
        'title', 'start_date', 'end_date', 'is_current', 'user_location')

I want to Remove Validation from company_name, company, description, location, title, start_date, end_date, user_location
actually these fields are second page means after complete the first step users move on second step so second step fields are optional
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
            'title', 'start_date', 'end_date', 'is_current', 'user_location')

        def create(self, validated_data):

            return Experience.objects.create(field_a='value', field_b='value')

in the above class, what should be do to remove validation of
"error_msg": {
        "location": [
            "Expected a dictionary of items but got type \"str\"."
        ],
        "start_date": [
            "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
        ],
        "end_date": [
            "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
        ],
        "user_location": [
            "Expected a dictionary of items but got type \"str\"."
        ]
    }

Experience Model
class Experience(models.Model):

    """
    """

    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='experiences')
    company_name = models.CharField(max_length=200, db_index=True, blank=True)
    company = models.ForeignKey('organisations.Organisation', null=True, blank=True, on_delete=models.SET_NULL)
    description = models.TextField(null=True, blank=True)
    location = models.ForeignKey('regions.Location', null=True, blank=True, on_delete=models.SET_NULL)
    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)
    title = models.CharField(max_length=200, db_index=True, blank=True)
    is_current = models.BooleanField(default=False)
    is_associated = models.BooleanField(default=False)
    created_at = models.DateTimeField(_('created at'), auto_now_add=True)
    modified_at = models.DateTimeField(_('modified at'), auto_now=True)

    class Meta:
        db_table = 'experience'
        verbose_name = _('experience')
        verbose_name_plural = _('experiences')
        ordering = ('-start_date',)

    def __str__(self):
        return getattr(self, 'title', '')

    @property
    def experience(self):
        if self.end_date:
            return (self.end_date - self.start_date).days
        else:
            return (datetime.datetime.now().date() - self.start_date).days

    def get_formated_experience(self):
        days = self.experience
        total_months = round(days/30)
        years = int(total_months/12)
        months = round(((total_months/12)%1)*12)
        year_txt = 'years' if years > 1 else 'year'
        month_txt = 'months' if months > 1 else 'month'
        return "%s %s %s %s" %(years, year_txt, months, month_txt)

Location Model
class Location(models.Model):
    """
    """
    id = models.TextField(primary_key=True)
    display_name = models.TextField(null=True, blank=True)
    latitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
    longitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = LocationManager()

A: You are getting Two types of validation error according to snapshot.

*

*Field  is required

*Expected a dictionary and got a string

The required field error occurs when you have set field as required in your model. You can change this by adding blank=True in your model for that field.
For second error, your serializer is expecting a dictionary and you are sending a string. You can remove this validation by writing your custom create method.
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
                'title', 'start_date', 'end_date', 'is_current', 'user_location')

    def create(self, validated_data):
        # you create code for that models.

Your seriailzers will be like this
class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):

    password = serializers.CharField(max_length=20, write_only=True)
    experiences = ExperienceSerializer(required=False)
    email = serializers.EmailField()
    first_name = serializers.CharField(max_length=30)
    last_name = serializers.CharField(max_length=30)

    class Meta:
        model = User
        fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
        'experiences', 'headline')

    def validate_email(self, value):
        from validate_email_address import validate_email
        if User.all_objects.filter(email=value.lower()).exists():
            raise serializers.ValidationError('User with this email already exists.')
        # if not validate_email(value.lower(), check_mx=True):
        #     raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
        return value.lower()

    def create(self, validated_data):
        experiences = validated_data.get('experiences')
        password = validated_data.get('password')
        email = validated_data.get('email')
        user = User.objects.create(
            username=email.lower(),
            email=email.lower(),
            role_id=1)
        user.set_password(password)
        user.save()
        user_location = experiences.get('user_location')
        location_object = None
        if user_location:
            location_object, created = Location.objects.get_or_create(display_name=user_location.get('display_name'), latitude= user_location.get('latitude'), longitude=user_location.get('longitude'))
        user_experience = Experience.objects.create(user=user, company_name=experiences.get('company_name'), location=location_object)
        return user

class ExperienceSerializer(serializers.HyperlinkedModelSerializer):

    user_location = LocationField()
    location = LocationField()

    class Meta:
        model = Experience
        fields = ('id', 'company_name', 'company', 'description', 'location',
                'title', 'start_date', 'end_date', 'is_current', 'user_location')


text:
Q: Send mail by using Strapi and React.js Since one month me and my team are working on a project with React as frontend and Strapi as our backend.
We need to do a form that has to automatically send e-mails by using the Strapi e-mails plugin.
However, we're still beginners with those technologies, and we aren't able to implement this kind of functionnality.
Is anyone familiar with Strapi and also this plugin ?
We don't find a lot of tutorials and documentation about it on the web.
Thank your for paying attention.

A: you can follow instructions of this guide - https://strapi.io/documentation/3.0.0-beta.x/guides/send-email.html#introduction
You can create a custom route/controller to manage your contact form.
Here is an example - https://strapi.io/documentation/3.0.0-beta.x/concepts/controllers.html#example
Make sure to create a POST route.
Then in your controller, get your form data with ctx.request.body


text:
Q: drupal_write_record doesn't take object In drupal 6 i used to do something like this:
<?php
/*
 * CLASS Example
 */
class example {
  var $id = NULL;
  var $title;
  var $body;

  .....

  // Save
  function save() {
    $primary_key = ($this->id == NULL ? NULL : 'id');
    if (drupal_write_record('mytabble', $this, $primary_key)) {
      return TRUE;
    } else {
      return FALSE;
    }
  }
}
?>

This worked quite well. But in Drupal 7, the drupal_write_record only takes an array and no longer the object $this. The new db_merge also only takes an array.
Since i want to save the properties of my object to the database, the above code was very handy and generic for all kinds of classes.
Is there an alternative way to write an object to database, or a method to place objectproperties into a an array?
Any help will be appreciated!
Robert

A: drupal_write_record does take an object or an array. Guess your problem is caused somewhere else.
drupal_write_record($table, &$record, $primary_keys = array())
$record: An object or array representing the record to write, passed in by reference. If inserting a new record, values not provided in $record will be populated in $record and in the database with the default values from the schema, as well as a single serial (auto-increment) field (if present). If updating an existing record, only provided values are updated in the database, and $record is not modified.
More info on drupal_write_record for D7.


text:
Q: Install many applications using one command after reinstall system I need install applications again. Is it possible to make bash script or own package where cancan I add needed application and after reinstall system will I install them all using one command?

A: To build a list of installed packages use:
sudo dpkg --get-selections > package.list

To restore the packages use:
sudo dpkg --set-selections < package.list
sudo apt-get dselect-upgrade

A: You can use sudo apt install app1 app2 app3 type command in order to install multiple applications from the terminal or a bash script.  Simply list all of the applications you wish to install in that command.
For example, if I wanted to install the applications gufw, libreoffice and hexchat, I would simply run the command sudo apt install gufw libreoffice hexchat.
Make sure you use the correct package name for each one because if any one of the package names in the command are misspelled or incorrect, the entire command will fail.

A: If the packages come from apt repositories , it is sufficient to provide a long list on command line
sudo apt install pkg1 pkg2 pkg3

If the list is large you may run into argument list too long error. In such case you can  create a text file with list of packages one per line and run something like
sudo xargs --arg-file packages.txt apt install

Remember to update package cache before installing
sudo apt update

For deb packages found locally on disk, you could use sudo dpkg -i ./*.deb in current working directory or sudo dpkg -R -i debfiles/ to recursively traverse debfiles/ directory ( user-defined , can be replaced with another name). However, there are issues when those packages may need dependencies first, and the linked post provides a Python script to resolve that via topological sort.


text:
Q: Microsoft Ajax Minifier and NAnt Could someone explain to me how to use the Microsoft Ajax Minifier from a nant-script as a nant-task. I've seen examples of how to use it in Visual Studio but I would like the minification to be done on our CI-server.

A: I'm not sure specifically about the MS Ajax Minifier, but here's what I did to get the Yahoo! UI Library: YUI Compressor for .Net working.

*

*Downloaded the YUI Compressor
assemblies for .NET

*Modified their Sample MSBuild.xml File

*Modified my nAnt script to run the MSBuild task (more details here: Build and publish .Net 2.0 projects with NAnt and the MSBuild task)

A: This is the code i use, it minifies all *.js and *.css in a folder using ajaxminifier
<foreach item="File" property="filename">
    <in>
        <items>
            <include name="${deployment.dir}\js\*.js"></include>
            <include name="${deployment.dir}\css\*.css"></include>
        </items>
    </in>
    <do>
        <echo message="Minifying ${filename} and overwritting file"/>
        <exec program="${ajaxminifier.exe}"
            workingdir="."
            failonerror="true"
            commandline='-clobber:true ${filename} -o ${filename}'/>
    </do>
    </foreach>

Note that this script overwrites the files with the minified version ( with -clobber:true arg). ${ajaxminifier.exe} is the path to ajaxmin.exe

A: <foreach item="File" property="Debugfile" >
    <in>
        <items>
            <include name="**\*.debug.js"/>
        </items>
    </in>
    <do failonerror="false">
        <regex pattern="^(?'filename'.*)\.(?'extension2'\w+)\.(?'extension3'\w+)$" input="${Debugfile}" />
        <regex pattern="^(?'path'.*(\\|/)|(/|\\))(?'file'.*)$" input="${Debugfile}" />
        <echo message="renaming with filename=${path},file=${file}"/>
        <exec program="${Minifie.lib}\ajaxmin.exe" commandline="${filename}.debug.js -o ${filename}.js" failonerror="true"/>
    </do>
</foreach>

A:
    description="AjaxminFilesCreation.">
    <foreach item="File" property="Debugfile" >
        <in>
            <items>
            <include name="**\*.debug.js"/>
        </items>
        </in>
        <do failonerror="false">

        <regex pattern="^(?'filename'.*)\.(?'extension2'\w+)\.(?'extension3'\w+)$" input="${Debugfile}" />
        <regex pattern="^(?'path'.*(\\|/)|(/|\\))(?'file'.*)$" input="${Debugfile}" />
        <echo message="renaming with filename=${path},file=${file}"/>
    <exec program="${Minifie.lib}\ajaxmin.exe" commandline="${filename}.debug.js -o ${filename}.js" failonerror="true"/>
        </do>
    </foreach>
</target>


text:
Q: Treepoem barcode generator unable to find ghostscript I'm trying to generate a pdf417 barcode in python using treepoem but pycharm keeps giving me the following error:
Traceback (most recent call last):
File "C:/Users/./Documents/barcodes.py", line 175, in
    image = generate_barcode(barcode_type="pdf417",data=barcode, options=dict(eclevel=5, rows=27, columns=12))
  File "C:\Users.\AppData\Local\Programs\Python\Python36-32\lib\site-packages\treepoem__init__.py", line 141, in generate_barcode
    bbox_lines = _get_bbox(code)
  File "C:\Users.\AppData\Local\Programs\Python\Python36-32\lib\site-packages\treepoem__init__.py", line 81, in _get_bbox
    ghostscript = _get_ghostscript_binary()
  File "C:\Users.\AppData\Local\Programs\Python\Python36-32\lib\site-packages\treepoem__init__.py", line 108, in _get_ghostscript_binary
    'Cannot determine path to ghostscript, is it installed?'
treepoem.TreepoemError: Cannot determine path to ghostscript, is it installed?
I've tried to install ghostcript, using both the .exe I found online and using pip install ghostscript (successfully completed the first time, and now tells me the requirement is satisfied), yet I still keep getting this error. Any ideas on how to fix it?

A: You are installing on Windows, the Windows binary differs in name from the Linux binaries and indeed differs depending whether  you installed the 64 or 32-bit version.
On Linux (and MacOS) the Ghostscript binary is called 'gs', on Windows its 'gswin32' or 'gswin64' or 'gswin32c' or 'gswin64c' depending on whether you want the 32 or 64 bit version, and the command line or windowed executable.
My guess is that your script is looking for simply 'gs' and is probably expecting the path to be in the $PATH environment variable, its not clear to me what its expecting.
You could probably 'fix' this by making sure the installation path is in the $PATH environment variable and copying the executable to 'gs.exe' in that directory.
Other than that you'll need someone who can tell you what the script is looking for. Quite possibly you could just grep it.

A: Another solution is to edit the C:\Users\Windows.UserName\AppData\Local\Programs\Python\Python37\Lib\site-packages\treepoem__init__.py
the script is looking for gs.exe, change to gswin32.exe as shown below.
Then add the GhostScriptInstallDir\bin in the PATH in windows.
def _get_ghostscript_binary():
    binary = "gswin32" # changed from 'gs' to 'gswin32'

    if sys.platform.startswith("win"):
        binary = EpsImagePlugin.gs_windows_binary
        if not binary:
            raise TreepoemError(
                "Cannot determine path to ghostscript, is it installed?"
            )

    return binary


text:
Q: Pass parameter to context menu I am currently studying Material UI 5 and specifically Context Menu subject - https://mui.com/material-ui/react-menu/#context-menu.
Can someone explain me why the handleClose function always print the last index in the array - 4?
import * as React from "react"
import Menu from "@mui/material/Menu"
import MenuItem from "@mui/material/MenuItem"
import Typography from "@mui/material/Typography"

export default function ContextMenu() {
  const [contextMenu, setContextMenu] = React.useState(null)

  const handleContextMenu = (event) => {
    event.preventDefault()
    setContextMenu(
      contextMenu === null
        ? {
            mouseX: event.clientX + 2,
            mouseY: event.clientY - 6,
          }
        : null
    )
  }

  const handleClose = (i) => {
    setContextMenu(null)
    console.log(i)
  }

  return (
    <>
      {["a", "b", "c", "d", "e"].map((item, index) => (
        <div
          key={index}
          onContextMenu={handleContextMenu}
          style={{ cursor: "context-menu" }}
        >
          <Typography variant='h6' component='h1' sx={{ padding: 4 }}>
            {item}
          </Typography>
          <Menu
            open={contextMenu !== null}
            onClose={handleClose}
            anchorReference='anchorPosition'
            anchorPosition={
              contextMenu !== null
                ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
                : undefined
            }
          >
            <MenuItem onClick={() => handleClose(index)}>one</MenuItem>
            <MenuItem onClick={() => handleClose(index)}>two</MenuItem>
            <MenuItem onClick={() => handleClose(index)}>three</MenuItem>
          </Menu>
        </div>
      ))}
    </>
  )
}

A: The way you currently have the on clicks setup is that it accesses the value index has at the time you click it, not the value it had when the function was created.
Change
onClick={() => handleClose(index)}

To
onClick={((index) => () => handleClose(index))(index)}

A: check the following code and see how you should manage user's options :
import * as React from "react";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";

export default function ContextMenu() {
  const initialState = {
    element: null,
    item: null
  };
  const [state, setState] = React.useState(initialState);

  const handleListItemClick = (element, item) => {
    setState({
      element,
      item
    });
  };

  const handleMenuItemClick = (option) => {
    setState(initialState);
    switch (option) {
      case "one":
        console.log(state.item, "one");
        break;
      case "two":
        console.log(state.item, "two");
        break;
      default:
        break;
    }
  };

  return (
    <div>
      {React.Children.toArray(
        ["a", "b", "c", "d", "e"].map((item) => (
          <Typography
            onClick={(e) => handleListItemClick(e.target, item)}
            sx={{ margin: 4 }}
          >
            {item}
          </Typography>
        ))
      )}
      <Menu open={state.element !== null} anchorEl={state.element}>
        <MenuItem onClick={() => handleMenuItemClick("one")}>one</MenuItem>
        <MenuItem onClick={() => handleMenuItemClick("two")}>two</MenuItem>
      </Menu>
    </div>
  );
}

codesandbox: https://codesandbox.io/s/great-microservice-w5jh00


text:
Q: dynamic object definition This is a serious question, It has been nagging me for a while. In JavaScript you can declare a variable which has no type. It's type is often dynamic, depends on further value assigned to it.
e.g
var text;
typeof(text); //undefined

text = 'someText';
typeof(text); //string

So as we know that Javascript can dynamically change variable's type why these assignments are invalid then?
e.g
var someObj;
someObj.a = 'hello world';
console.log(someObj) //TypeError

var someTable;
someTable[0] = 'hello world';
console.log(someTable[0]) //TypeError

where this problem can be fixed just by adding definition to variable declaration:
var someObj = {};
var someTable = [];

I'd expect a good explanation of this problem. Thanks for answers.

A: You're getting confused about where the error is thrown. In your first example:
var someObj;
someObj.a = 'hello world'; // the error is thrown here

That error is thrown because someObj is undefined (not undeclared). So, you can't access the property a on undefined.
The same explanation applies for your second example:
var someTable;
someTable[0] = 'hello world'; // the error is thrown here

You're trying to access index 0 of undefined.
The reason that defining them as {} and [], respectively, fixes your issue, is that you are then accessing property a of {} and index 0 of [].

A: There's a big difference between declaration and initialisation of variables.
When you declare a variable without initializing it with a value, its type will be undefined, so when you will try to call it or access it, it will give  undefined, because simply there were no value defined for the variable.
That's why it should be initialized:
var someObj = {};
var someTable = [];

So you can treat it as a string, an object or an array according its initialized value.
Documentation:
Please take a look at variables MDN Reference for further reading, where it says:

A var statement declares variables that are scoped to the running execution context's VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created. [...] A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.

A: 1) Data types in Javascript are not dynamic, they are mutable. This means that depending on kind of operation you are applying to them they can change from being something into another thing (e.g. a number can become a string doing something like this: 4 + 'a').
2) The "error" is a consequence of having a variable not initialized. In Javascript when you are doing this:var something = 'a'
you are doing two operations, a declaration, and an assignment. If you don't do the assignment and you try to access to a property of the object you have declared it will throw an error. In your case, you are declaring a variable but not initializing it to the "compiler" can't access the "a" property or the position 1 because it is of type undefined.


text:
Q: update_all_contenttypes seemingly not working with Django 1.8 I was getting the following error upon running a certain function:
django.contrib.contenttypes.models.DoesNotExist: ContentType matching query does not exist.

Based upon ContentType matching query does not exist on post_syncdb I tried doing
from django.contrib.contenttypes.management import update_all_contenttypes
 update_all_contenttypes() # make sure all content types exist

at the beginning of that function.
Of course, as ImportError: cannot import name update_all_contenttypes mentions, update_all_contenttypes appears to have been silently removed in Django 1.8 , so that didn't work. Next I tried removing the above snippet and instead adding the following to the beginning of that function:
from django.apps import apps
from django.contrib.contenttypes.management import update_contenttypes

def update_all_contenttypes(**kwargs):
    for app_config in apps.get_app_configs():
        update_contenttypes(app_config, **kwargs)

update_all_contenttypes()

(Other than the last line, i.e. update_all_contenttypes(), the snippet directly above this comes from https://stackoverflow.com/a/29550255/805141 ).
However, I'm still getting django.contrib.contenttypes.models.DoesNotExist: ContentType matching query does not exist.
The line I'm getting that error on is SomeObject.objects.all().delete()
Here's the full stack trace:
some_function()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/path/to/app/models.py", line XXXX, in some_function
    SomeObject.objects.all().delete()
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 536, in delete
    collector.collect(del_query)
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/deletion.py", line 197, in collect
    reverse_dependency=reverse_dependency)
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/deletion.py", line 97, in add
    if not objs:
  File /path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 166, in __bool__
    self._fetch_all()
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/path/to/virtualenv/lib/python3.4/site-packages/polymorphic/query.py", line 296, in iterator
    real_results = self._get_real_instances(base_result_objects)
  File "/path/to/virtualenv/lib/python3.4/site-packages/polymorphic/query.py", line 199, in _get_real_instances
    real_concrete_class = base_object.get_real_instance_class()
  File "/path/to/virtualenv/lib/python3.4/site-packages/polymorphic/polymorphic_model.py", line 105, in get_real_instance_class
    model = ContentType.objects.get_for_id(self.polymorphic_ctype_id).model_class()
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/contrib/contenttypes/models.py", line 136, in get_for_id
    ct = self.get(pk=id)
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 334, in get
    self.model._meta.object_name
django.contrib.contenttypes.models.DoesNotExist: ContentType matching query does not exist.


text:
Q: Split string contained in array and save into another array A little confusing however...
I have a long string somestringDIEmorestringKILLanotherstringDIEmorestring and I have split that at KILL so I have the array below:
["valueArray"]
    [0] => "somestringDIEmorestring",
    [1] => "anotherstringDIEmorestring"

Now I need to split the strings further where it says DIE, however they ideally need to be placed inside a single array so I can loop through them all and post them to their respected endpoints.
Ultimately I need something like this:
["valueArray1"]
    [0] => "somestring",
    [1] => "morestring",
    [2] => "anotherstring",
    [3] => "morestring"

OR:
["valueArray1"]
    [0] => ["Array"]
               [0] => "somestring",
               [1] => "morestring"
    [1] => ["Array"]
               [0] => "anotherstring",
               [1] => "morestring"

How is the best way to go about this? I've currently got a $.each function set up but it's not working correctly:
$.each( valueArray, function( i, val ) {
    valueArray1[i] = val.split('DIE');
});

Any help would be awesome! Or equally if there is a better way altogether to sort this out.
Thank you.
NOTE: I have to use strings as it's data coming from localStorage

A: You can simply split on a regex.
val.split(/DIE|KILL/);

Or, in context:
var val = ...; // your value read in from localStorage
var valArray = val.split(/DIE|KILL/);

This would get you a flat array like:
[
    [0] => "somestring"
    [1] => "morestring",
    [2] => "anotherstring",
    [3] => "morestring"
]

I would however suggest use of a better serialization format for storage of data in string in localStorage.  Perhaps JSON would best do the trick. Here is an example of setting and getting structured data to localStorage via JSON serialization.  You could do the same with objects, an array of objects, or whatever other data structure you might have that can be serialized to JSON.
// set value
var arrayToStore = [
    "somestring"
    "morestring",
    "anotherstring",
    "morestring"
];
localStorage.setItem('storedArray', JSON.stringify(arrayToStore));

//get value
var arrayFromStore = JSON.parse(localStorage.getItem('storedArray'));

This gives you MUCH more flexibility in terms of not having to conceive your own serialization format for any sort of data structure you might store.
Or better yet, write your own setter/getter class for working with local storage that you can use anywhere in your application. A simplified example:
var localStore = {
    var set = function (key, value) {
        localStorage.setItem(key, JSON.stringify(value));
        return this;
    }
    var get = function (key) {
        return localStorage.getItem(key);
    }
};

// usage
localStore.set('storedArray', arrayToStore);
var arrayFromStore = localStore.get('storedArray');


text:
Q: cron job to run under conda virtual environment I have a Anaconda Python Virtual Environment set up and if I run my project while that virutal environment is activated everything runs great.
But I have a cronjob configured to run it every hour. I piped the output to a log because it wasn't running correctly.
crontab -e:
10 * * * * bash /work/sql_server_etl/src/python/run_parallel_workflow.sh >> /home/etlservice/cronlog.log 2>&1

I get this error in the cronlog.log:
Traceback (most recent call last):
  File "__parallel_workflow.py", line 10, in <module>
    import yaml
ImportError: No module named yaml

That is indicative of the cronjob somehow not running the file without the virtual environment activated.
To remedy this I added a line to the /home/user/.bash_profile file:
conda activate ~/anaconda3/envs/sql_server_etl/

Now when I login the environment is activated automatically.
However, the problem persists.
I tried one more thing. I changed the cronjob, (and I also tried this in the bash file the cronjob runs) to explicitly manually activate the environment each time it runs, but to no avail:
10 * * * * conda activate ~/anaconda3/envs/sql_server_etl/ && bash /work/sql_server_etl/src/python/run_parallel_workflow.sh >> /home/etlservice/cronlog.log 2>&1

Of course, nothing I've tried has fixed it. I really know nothing about linux so maybe there's something obvious I need to change.
So, is there anyway to specify that the cronjob should run under a virutal environment?

A: This is a solution that has worked well for me.
source /root/miniconda3/etc/profile.d/conda.sh && \
conda activate <your_env> && \
python <your_application> &

I am using miniconda with Conda version 4.7.12 on a Ubuntu 18.04.3 LTS.
I am able to place the above inside a script and run it via crontab as well without any trouble.

A: Found answer on stack over flow:
https://stackoverflow.com/questions/3287038/cron-and-virtualenv
The solution is to reference the python executable within the virtual environment itself. In my case, I changed the bash file to run this executable:
/home/etlservice/anaconda3/envs/sql_server_etl/bin/python

A:
This solution works to me.

Try to use
source /path/to/conda/bin/activate my_env
instead of
conda activate my_env
in your bash script run_parallel_workflow.sh.

A: Posted a working solution (on Ubuntu 18.04) with detailed reasoning on SO.
The short form is:
1. Copy snippet appended by Anaconda in ~/.bashrc (at the end of the file) to a separate file ~/.bashrc_conda
As of Anaconda 2020.02 installation, the snippet reads as follows:
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/home/USERNAME/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/home/USERNAME/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/home/USERNAME/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/home/USERNAME/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

Make sure that:

*

*The path /home/USERNAME/anaconda3/ is correct.

*The user running the cronjob has read permissions for ~/.bashrc_conda (and no other user can write to this file).

2. In crontab -e add lines to run cronjobs on bash and to source ~/.bashrc_conda
Run crontab -e and insert the following before the cronjob:
SHELL=/bin/bash
BASH_ENV=~/.bashrc_conda

3. In crontab -e include at beginning of the cronjob conda activate my_env; as in example
Example of entry for a script that would execute at noon 12:30 each day on the Python interpreter within the conda environment:
30 12 * * * conda activate my_env; python /path/to/script.py; conda deactivate

And that's it.
You may want to check from time to time that the snippet in ~/.bashrc_conda is up to date in case conda updates its snippet in ~/.bashrc.


text:
Q: Create a data migration strategy for testers working through the app Testers are updating data through the app
I am working with an application where the app is changing rapidly, but at the same time, the testers need to build test and certification data. This data is being created by accessing the app directly, rather than writing SQL statements.
So, I have changesets coming in from the developers and data changes being applied through the application by testers at the same time.
I have wired up liquibase to handle running the changesets written by the developers, but I'm having difficulties figuring out the cleanest way to track and preserve data changes by the testers.
Possible workflow
Based on using liquibase through the entire process, I'm thinking I need a workflow like:

*

*Start with the latest clean database

*Run liquibase update

*Snapshot or tag the database for differencing later

*Let the testers hack away through the app.

*If the testers approve the changes, upon promotion:

*

*generate a data diff as a changeset

*include the data changeset in the master update list

*on this VM, record the changeset as already ran

*commit to scm

*Repeat

Questions

*

*Is there a way to use liquibase to get a true data diff, and not a full data export? It seems that generateChangeLog is the only tool in the diffs that allows setting the --diff-type="data" flag and value, but the documentation also makes that seem that it won't diff, it just dumps all of the data.

*If yes,

*

*can you provide a sample call? I have the url & referenceURL figured out and stored in a liquibase.properties file, I just need to know which command and flags to pass.

*can it be used against a tag instead of having to create a backup of the database? (step 3 in the workflow)

*If no,

*

*has anyone seen a good tutorial or howto showing the orchestration between liquibase and dbUnit updates?

*How do you handle the situation where the data export no longer fits the schema? For example, FullName split => FirstName and LastName; liquibase can handle this, but I would think that I would need to orchestrate running updates between liquibase and dbUnit, otherwise the diff of dbUnit will be invalid?
Any guidance, tips, past experiences or gotchas to watch out for would be greatly appreciated.

A: No, liquibase does not support a data diff, only a full data dump.
I have seen http://ljnelson.github.io/liquiunit/ which may help you with dbunit integration, but using dbunit or any other data load tool to manage your data will run into schema incompatibilities like you suggest.
What I would suggest doing is to have "test data load" changeSets that are added into your changeLog to build up your test data as you go along.
For example:
<changeSet id="1" author="x">
   <createTable name="a"../>
</changeSet>
<changeSet id="2" author="x">
   <createTable name="b"../>
</changeSet>

<changeSet id="3" author="x" context="test">
   <sqlFile path="data-dump.1.sql">
</changeSet>

<changeSet id="4" author="x">
   <renameColumn oldColumnName="s" newColumnName="t"../>
</changeSet>

<changeSet id="5" author="x" context="test">
   <sqlFile path="data-dump.2.sql">
</changeSet>

You see it creates an initial structure and then loads a round of QA's data into the database with the database structure as it is after changeset 2. Notice the use of contexts so the test data isn't loaded into production.
After the test data are more structure changes and then another round of additional QA data. The new data doesn't re-create data-dump.1.sql but is in addition to it. Since data-dump.1.sql is always ran before changeSet 4, it doesn't have to be updated as the schema changes.
The big problem, though, is how to extract your test data as QA is building it up. If they are adding it through your application, the easiest approach may be to use something like p6spy to automatically collect all the SQL executed in your application and then just copy it into your data-dump.X.sql files.

A: As an alternative to my other answer, you can have a full dump of your database (use liquibase generateChangeLog diffTypes=data or your standard database backup tool) which you create from the QA-built database and move along your changelog file.
Step 1:
Create your database
<changeSet id="1" author="x">
   <createTable name="a"../>
</changeSet>
<changeSet id="2" author="x">
   <createTable name="b"../>
</changeSet>

Step 2
QA creates database then makes a backup which is included in the changelog file.
<changeSet id="1" author="x">
   <createTable name="a"../>
</changeSet>
<changeSet id="2" author="x">
   <createTable name="b"../>
</changeSet>
<changeSet id="testdata-1" author="x" context="test">
    <sqlFile path="data-dump.sql">
</changeSet>

Step 3
There are schema changes that don't require new test data, keep adding to the changelog file. The test data is migrated along and matches your needed schema.
<changeSet id="1" author="x">
   <createTable name="a"../>
</changeSet>
<changeSet id="2" author="x">
   <createTable name="b"../>
</changeSet>
<changeSet id="testdata-1" author="x" context="test">
    <sqlFile path="data-dump.sql">
</changeSet>
<changeSet id="4" author="x">
   <renameColumn oldColumnName="s" newColumnName="t"../>
</changeSet>

Step 4
When QA needs additional data, they add what they want using the app then make a new full backup and move the testdata changeset to the end
<changeSet id="1" author="x">
   <createTable name="a"../>
</changeSet>
<changeSet id="2" author="x">
   <createTable name="b"../>
</changeSet>
<changeSet id="4" author="x">
   <renameColumn oldColumnName="s" newColumnName="t"../>
</changeSet>
<changeSet id="testdata-1" author="x" context="test">
    <sqlFile path="data-dump.sql">
</changeSet>

This process does require you to drop your dev/test databases to get the new test data or you will get insert conflicts, but depending on your workflow it may work for you.


text:
Q: Изменение текущей директории В моей программе использую класс QProcess для запуска других приложений. Но вот беда, приложения которые запускаются имеют "текущую директорию" расположение моей программы. Как это исправить?
// пример ф-ции для запуска других программ (и закрытии себя)
void MainWindow::runExe(QString pathToExe)
{
    QProcess *process = new QProcess();
    process->start(exe.path() + "/" + pathToExe);
    if (process->waitForStarted())
        close();
    else
        qDebug() << QString("Can't run exe: %1").arg(process->program());
}

A: У QProcess есть спецфункция - setWorkingDirectory - используйте ее, что бы выставить правильную директорию.


text:
Q: C# XML tags to csv I have dozend of XML filed in the following format (short sample):
<namespace name="Colors">
    <green>
        <en>Green</en>
        <de>Gruen</de>
    </green>
    <blue>
        <en>Blue</en>
        <de>Blau</de>
    </blue>
    <namespace name="Subcolors">
        <perlwhite>
            <en>Perl White</en>
            <de>Perlweis</de>
        </perlwhite>
        <racingblack>
            <en>Racing Black</en>
            <de>Rennschwarz</de>
        </racingblack>
    </namespace>
</namespace>

And i have to extract all the language tags and output them into a csv file in this format:
en;de;
Green;Gruen;
Blue;Blau;
Perl White;Perlweiß;
Racing Black;Renn Schwarz;

Then, I give this CSV file away for translation. After translation, there is a new language added to the CSV file, french for example:
en;de;fr;
Green;Gruen;Vert;
Blue;Blau;Bleu;
Perl White;Perlweiß;Perl Blanc;
Racing Black;Rennschwarz;Courses Noir;

Then i need to read this csv file in again, and append all  tags to all the corresponding  xml-files, like so:
<namespace name="Colors">
    <green>
        <en>Green</en>
        <de>Gruen</de>
        <fr>Vert</fr>
    </green>
    <blue>
        <en>Blue</en>
        <de>Blau</de>
        <fr>Bleu</fr>
    </blue>
    <namespace name="Subcolors">
        <perlwhite>
            <en>Perl White</en>
            <de>Perlweis</de>
            <fr>Perl Blanc</fr>
        </perlwhite>
        <racingblack>
            <en>Racing Black</en>
            <de>Renn Schwarz</de>
            <fr>Courses Noir</fr>
        </racingblack>
    </namespace>
</namespace>

And namespaces or other nodes(not listed here, like "multicolor", "colored" and many more) can be nested more then once. Not every file contains every node. And not every node is nested the same way in each xml file. Thats different from file to file. But at the end, each branch ends with couple of language tags. And these need to be read and updated.
So an xml file can look like this:
<namespace name="Colors">
    <green>
        <en>Green</en>
        <de>Gruen</de>
    </green>
    <blue>
        <en>Blue</en>
        <de>Blau</de>
    </blue>
        <namespace name="Subcolors">
            <perlwhite>
                <en>Perl White</en>
                <de>Perlweis</de>
            </perlwhite>
            <racingblack>
                <en>Racing Black</en>
                <de>Rennschwarz</de>
            </racingblack>
            <colored>
                <namespace name="Misc">
                    <fruits>
                        <apple>
                            <de>Apfel</de>
                            <en>Apple</en>
                        </apple>
                        <orange>
                            <de>Orange</de>
                            <en>Orange</en>
                        </orange>
                    </fruits>
                    <vegetables>
                        <cucumber>
                            <en>Cucumber</en>
                            <de>Gurke</de>
                        </cucumber>
                    </vegetables>
                    <namespace name="Other">
                        <othertag>
                            <entry>
                                <en>Entry</en>
                                <de>Eintrag</de>
                            </entry>
                        </othertag>
                    </namespace>
                </namespace>
            </colored>
        </namespace>
    </namespace>

So not every xml file is the same, and there are different nodes with different tag names differenty nested. But every branch ends with language tags.
Can somebody help me to do this in a simple way with C#?. Maybe two simple functions like Import(readCsvPath, appendXmlPath) and Export(readXmLPath, writeCsvPath).

A: The code basically work with issues.  The original xml has perlwhite, but the new csv has Perl-White.  How do you know  where to put the dash.  I converted the small p to upper P but do not know where to put the dash.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication103
{
    class Program
    {
        const string INPUT_XML = @"c:\temp\test.xml";
        const string OUTPUT_CSV = @"c:\temp\test.csv";
        const string INPUT_CSV = @"c:\temp\test2.csv";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(INPUT_XML);

            var colorsWithDuplicates = doc.Descendants("namespace")
                .SelectMany(ns => ns.Elements()
                .SelectMany(color => color.Elements().Select(y => new {color = color.Name.LocalName,  language = y.Name.LocalName, value = (string)y}))
                ).ToList();

            var colors = colorsWithDuplicates.GroupBy(x => new object[] { x.color, x.language }).Select(x => x.First()).ToList();

            var sortedAndGrouped = colors.OrderBy(x => x.language).ThenBy(x => x.color).GroupBy(x => x.color).ToList();

            List<string> countries = sortedAndGrouped.FirstOrDefault().Select(x => x.language).ToList();

            StreamWriter writer = new StreamWriter(OUTPUT_CSV, false, Encoding.Unicode);
            writer.WriteLine(string.Join(",",countries));

            foreach (var color in sortedAndGrouped)
            {
                writer.WriteLine(string.Join(";",color.Select(x => x.value)));
            }
            writer.Flush();
            writer.Close();

            StreamReader reader = new StreamReader(INPUT_CSV);

            List<string> newCountries = reader.ReadLine().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            string line = "";
            Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                List<string> splitLine = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                dict.Add(splitLine[0], splitLine);
            }

            //now replace colors
            foreach (XElement xNs in doc.Descendants("namespace"))
            {
                string name = (string)xNs.Attribute("name");
                if((name == "Colors") || (name == "Subcolors"))
                {
                    foreach (XElement xColor in xNs.Elements())
                    {
                        if (xColor.Name.LocalName != "namespace")
                        {

                            string checkColor = xColor.Name.LocalName;
                            checkColor = (string)xColor.Element("en");  // use english name
                            if (checkColor != null)
                            {
                                List<string> inputColors = dict[checkColor];
                                for (int index = 0; index < inputColors.Count; index++)
                                {
                                    XElement country = xColor.Element(newCountries[index]);
                                    if (country == null)
                                    {
                                        xColor.Add(new XElement(newCountries[index], inputColors[index]));
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (XElement group in xNs.Elements())
                    {
                        foreach(XElement xColor in group.Elements())
                        {

                            string checkColor = xColor.Name.LocalName;
                            checkColor = char.ToUpper(checkColor[0]) + checkColor.Substring(1);
                            if (checkColor != null)
                            {
                                List<string> inputColors = dict[checkColor];
                                for (int index = 0; index < inputColors.Count; index++)
                                {
                                    XElement country = xColor.Element(newCountries[index]);
                                    if (country == null)
                                    {
                                        xColor.Add(new XElement(newCountries[index], inputColors[index]));
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }

}

A: For importing an XML to CSV file you can use folloiwng code, which is not long and easy:
XmlDocument xml = new XmlDocument();
// xmlContent contains your XML file
xml.LoadXml(xmlContent);
// get collections of nodes representing translations in particular languages
var enNodes = xml.GetElementsByTagName("en");
var deNodes = xml.GetElementsByTagName("de");

string[] lines = new string[enNodes.Count];
for (int i = 0; i < enNodes.Count; i++)
    lines[i] = $"{enNodes[i].InnerText},{deNodes[i].InnerText}";
File.WriteAllLines(@"path to text file", lines);

The other way, CSV to XML require much more coding as you will have to detect every node to translate and add another node representing new language. This requires much more coding and is too broad for an answer - you have to write some code yourself first, then come back with more precise question about problem you would have.
Good luck.


text:
Q: How to play audio on Corona? I am trying to play audio as i used to do but it seems not working now. These are the codes I tried:
  local birdSound =  audio.loadSound("bird.mp3")
  audio.play(birdSound)

It gives an error like that:
WARNING: Failed to create audio sound
Can you help me out? Thanks.

A: *

*Don't use .mp3.  .wav works for both iphone and android.

*Make sure the .wav file is in our folder.

*Sometimes some sound file can be played on computer, but not works in simulator. In that case, use other files instead.

*If you really like that .mp3 file and can not find .wav, find some free software to convert it.

A: Changing the bit rate(increasing) of my files helped me to solve the problem. Thanks to SatheeshJM!


text:
Q: What does returning by constant reference do? [C++] Can someone explain what is the point of returning by constant reference? I know that when you just return a reference, you are returning an alias to that object you are returning. However, I am not sure what adding the word 'const' changes what it does. Thanks!

A: A good example would be std::vector::operator[].  There are two overloads of that function, a const version that returns a const reference and a non-const version that returns a regular reference.  If you use the const version you cannot assign a new value.
void func(const std::vector<int> & const_vec, std::vector<int> & vec)
{
    const_vec[0] = 906;  // will fail with compiler error
    vec[0] = 906;  // works fine if vec.size() >= 1
}

A: Most times the point in returning a "const ref" (a reference to a constant object) is to give the calling code read only access to the property of a class.
T const & (or const T &) denotes a reference to an object that can't be altered using the reference. Hence only const-qualified member functions can be called.


text:
Q: nHibernate: Fails to rollback complete operation We have a userobject split between two tables, a person table and user table.
public UserMap()
{
   Table("Person");
   Id(x => x.PersonId, "PersonId");
   Map(x => x.Name, "Name");

   Join("User", s => {
      s.Fetch.Join();
      s.KeyColumn("PersonId");
      s.Map(x => x.Username, "Username");
      s.Map(x => x.Password, "Password");
   });
}

When doing a insert, nHibernate will first insert Name into the Person table, and then Username and Password into the User table.
The problem arise when the insertion into the User-table fails (like trying to insert a user with a username that is already taken). The transaction fails, but the insertion into the Person table is not rolled back.
    public User Save(User user)
    {
        var session = SessionHelper.GetCurrent();
        using (var dbTransaction = session.BeginTransaction())
        {
            try
            {
                session.SaveOrUpdate(user);
                dbTransaction.Commit();
            }
            catch (Exception)
            {

                dbTransaction.Rollback();
                throw;
            }
        }

        return user;
    }

Our SessionFactory is also set up with Fluent NHibernate
    public ISessionFactory BuildSessionFactory(string connectionString)
    {
        return Fluently.Configure().Database(OracleClientConfiguration.Oracle10.ConnectionString(c => c.Is(connectionString))
                                             .Provider<OracleDriverConnectionProvider>()
                                             .Driver<OracleDataClientDriver>()
                                             .ShowSql)
                                             .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>())
                                             .BuildSessionFactory();
    }

I have put the logfile from a failing session in a gist. The User entity is a little more complex in real life, and there are some authentication stuff going on, so the log file want match 1:1 with the painted picture...

A: Seems like a similar problem was solved here. NHibernate will not revert you changes in the session when you rollback your transaction, i.e if you flush your session after the rollback, you will experience the problems you describe. To ensure no changes in your entities, when you rollback, you have to also close the session.

A: Add User object in Person Object and Save Person Object only. Use Cascade.All() in Mapping file. or Second option is use TransactionScope.

A: Instead of closing the session, you can use session.Clear() after you have roleld back the transaction, which will remove all pending writes and make session as good as new.
That did the trick for my application.


text:
Q: How to pass a parameter to a script in \href? This is a borderline question, but the essential point concerns the usage of the construct
\href{run:....}{....}

from the \hyperref package, which is poorly documented, so here it is. I would like to launch a compiled AppleScript script (I'm on a Mac) and it works perfectly. The line
\href{run:beep.app}{prova}

creates a clickable link 'prova' in the pdf, and clicking on it launches the script beep.app. I understand that 'run:' is more or less equivalent to 'file:', that is to say, my pdf viewer is simply trying to open the file beep.app as if I were double clicking on it (right?). Since my system defaults to launching the script when clicked on, the result is that the script is executed.
Now to my question: I would like to pass an argument (a string) to the script. How can I do this? is there any technique allowing to do this? If I were to launch the script from the command line, the syntax would be "beep.app arg", but of course the following command fails miserably, as it is obvious:
\href{run:beep.app arg}{prova}

Any ideas?


text:
Q: How to write a function whose both parameters and results are polymorphic in Haskell How can I write a function like int gog(float i) and float gog(int i) (which is usually called "overloading")? Some simple overloads can be achieved by
class PP a where
  gog :: a -> Int

instance PP Bool where
  gog _ = 1

instance PP Char where
  gog _ = 1

But the above example only makes the parameter polymorphic.  If we want to make both the parameter and result polymorphic, we have to write something like this:
class PP a where
  gog :: Uu b => a -> b

class UU a where
  -- This function can convert between different types of UU.
  fromUuToUu :: UU b => a -> b

Without fromUuToUu, the polymorphism in the result of gog is impossible.  But I can't write fromUuToUu, and that is relevant to the theme of this question, which is how to make a function whose parameter and result are both polymorphic.

A: {-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}

class Poly a b where
  gog :: a -> b

instance Poly Int String where
  gog = show

instance Poly String Int where
  gog = read

instance Poly Int Float where
  gog = fromIntegral

instance Poly Float Float where
  gog = (*) 2

gog is now "full" polymorphic.


text:
Q: undefined variable jQuery object I don't understand how to pass a variable from the init function to the bindEvent function in my object:
At the moment, I get undefined.
var Fisheye = {
    init: function () {

        $('body').hide();

        $(window).load(function() {
            $('body').fadeIn('slow');

            this.imgs = $('.pic').children('img');
            this.originalWidth = $(imgs).first().css('width');
            this.minWidth = 300;

            imgs.width(300);

            Fisheye.bindEvents();

        });

    },

    bindEvents: function() {
        $(this.imgs).toggle(this.toggleClick, this.toggleClick);
        console.log(this.imgs); // Why do I get Undefined here?
    },

    toggleClick: function() {
        //Todo
    }
}

Fisheye.init();

How to properly pass a variable from a function to another in an object?
Thanks!

A: You can do this :
var Fisheye = {

    init: function () {
        var _this = this;
        $('body').hide();
        $(window).load(function() {
            $('body').fadeIn('slow');
            _this.imgs = $('.pic').children('img');
            _this.originalWidth = $(_this.imgs).first().css('width');
            _this.minWidth = 300;
            _this.imgs.width(300);
            _this.bindEvents();
        });

    },

    bindEvents: function() {
        $(this.imgs).toggle(this.toggleClick, this.toggleClick);
    },

    toggleClick: function() {
        //Todo
    }
}

Fisheye.init();

The problem is that the "this" in you handler wasn't the instance of Fisheye but the window.
But you'll have a similar problem with the toggleClick. A solution for those could be to do this :
bindEvents: function() {
    var _this = this;
    var toggleFunction = function(){_this.toggleClick()};
    $(this.imgs).toggle(toggleFunction, toggleFunction);
},

A: rapidly just the structure , add param to the function
 bindEvents: function(imgs) {
    $(imgs).toggle(this.toggleClick, this.toggleClick);
    console.log(imgs); // Why do I get Undefined here?
},...

on init function
...
var imgs = ..
Fisheye.bindEvents(imgs);


text:
Q: can we change the shape of canvas using fabric js
I want to add objects inside shirt, by default canvas is of square shape
how can i make this type of canvas?
I have tried using css it only changes shape ,but functionality of canvas remains same like square.

A: Check this out: https://ourcodeworld.com/articles/read/1016/how-to-create-your-own-t-shirt-designer-using-fabricjs-in-javascript
If you read the blog post, and look at the last demo, you will find that it cropping image with that padding over the image. But thats not pixel perfect. For doing that read below
Pixel Perfect Shape Cropped Canvas

*

*We can clip our canvas to shape we want. This will hide rest of the canvas.
Reference: Fabric.js Clip Canvas (or object group) To Polygon

*Now you will face one more problem that your controls are also clipped which make user experience pathetic.

*Solution is use canvas.controlsAboveOverlay = true;
Creating custom svg images
There are 2 ways to this

*

*Google and download svg images that you need.

*Use Figma, by which you can create custom objects using pen tool and export them as svg.

TIP: Use figma plugin Image tracer to extract svg from images.


text:
Q: PowerShell - Merge CSVs I created a script which gets Name, CreationTime and Duration from each .mp4 file in a specific directory and than exports the data into a CSV file using the Cmdlet Export-Csv.
Now I have 3 CSV exports and I want to merge them, so I tried this:
$Data = @()
$CSVsPaths | ForEach-Object {
    $Data += Import-Csv -Path "$_" -Encoding "UTF8"
}
$Data

But for some reason, some of the objects are duplicated, and I'm sure the exports all contains different data. What am I doing wrong?

Edit:
Here are the CSVs: https://drive.google.com/drive/folders/1MbeUenLxbKdlle6rKFwc3jJNZf85AMtd

A: As mentioned in the comments, your output has duplicate rows because duplicates already exist in your data set.
To locate the duplicated rows, use Get-Content against the input files - the file system provider will attach some hidden properties to the output that we can use to identify the duplicate location(s) later:
# find all non-unique strings in the input files
$nonUniques = Get-Content '.\Export*.csv' |Group-Object |Where-Object Count -gt 1 |ForEach-Object Group

# use the PSChildName and ReadCount provider properties to identify the files that host the duplicate content,
# then use Format-Table to show output nicely grouped on the non-unique string value
$nonUniques |Select @{Name='Name';Expression='PSChildName'},@{Name='Line';Expression='ReadCount'},@{Name='Duplicate';Expression={$_}} |Format-Table Name,Line -GroupBy Duplicate

Which, given the input data you linked, will produce something like this:
   Duplicate: "QVR_06082021_141022 (PRIMA VOLTA CHE REGISTRO).mp4","06/08/2021 14:10:22","00:00:46"

Name                                      Line
----                                      ----
Export 2 (da 24-06-2022 a 31-07-2022).csv  113
Export 3 (da 06-08-2021 a 31-08-2021).csv    3

   Duplicate: "QVR_06082021_142308.mp4","06/08/2021 14:23:08","00:00:50"

Name                                      Line
----                                      ----
Export 2 (da 24-06-2022 a 31-07-2022).csv  114
Export 3 (da 06-08-2021 a 31-08-2021).csv    4

   Duplicate: "VID_20210806_220220.mp4","06/08/2021 22:02:20","00:00:20"

Name                                      Line
----                                      ----
Export 2 (da 24-06-2022 a 31-07-2022).csv  115
Export 3 (da 06-08-2021 a 31-08-2021).csv    5


text:
Q: Boostrap CDN with 16-columns instead of 12 I want to use the latest Bootstrap CDN, but it defaults to 12 column layout. Is the only way to customize into a 16 col layout is to download and host files yourself?
Edit: I'm asking how to get bootstrap through a CDN. I use the bootstrap CDN from https://cdnjs.com/ and it works great, except it is 12-col layout.

A: There is really only 2 options to do this.

*

*You override bootstraps grid system with your own css file.
<link rel="stylesheet" href="/cdn/path/to/bootstrap.css" />
<link rel="stylesheet" href="/my/path/overide_bootstrap.css" />

This can be a tedious task and I would not recommend doing it this way.

*Customize Bootstrap and use your own version
If you go to http://getbootstrap.com/customize/ you can customize and download a fully customized version of Bootstrap.  Specifically for what you are looking for is located at http://getbootstrap.com/customize/#grid-system.
Once it has been downloaded you have a few options:

*

*Serve the files yourself from your own project.

*Use a free CDN service
There are multiple CDN services that you can use, such as CloudFlare (https://www.cloudflare.com/features-cdn) or you can use cdnjs (https://github.com/cdnjs/cdnjs#adding-a-new-or-updating-an-existing-library)
I hope this helps!

A: You can customize most of Bootstrap configs and default values.In your case you can set @grid-columns value in the .less.
However you can still get customized Bootstrap from http://getbootstrap.com/customize/#grid-system
Just set Number of columns in the grid. and click "Compile and Download" at end of the page.

A: I think you can use cdn version of bootstrap and just go to customize and download only css with an adjusted grid system.
So you will have main bootstrap file from cdn, and overridden grid classes in your second file. Make sure to load cdn version first though.


text:
Q: mod_perl seems to be sharing modules across user accounts Please do ask if you need any more information. I'm just trying to work out what is going on. So I have a server with nginx as the front end, and then passing along to
Apache (2.4.18). In my Apache config file for the domain I have:
<VirtualHost *:8181>

    CustomLog /home/steampunkcom/web/uk.site.com/logs/uk.site.com.apache.log combined
    ErrorLog /home/steampunkcom/web/uk.site.com/logs/uk.site.com.apache.error.log

    LogLevel error

    RemoteIPHeader X-Forwarded-For

    # MOD_PERL
    LoadModule perl_module /usr/lib/apache2/modules/mod_perl.so

    ServerName uk.site.com
    ServerAlias www.uk.site.com
    ServerAdmin info@uk.site.com
    DocumentRoot /home/steampunkcom/web/uk.site.com/public_html

    # MOD_PERL
    PerlRequire  /home/steampunkcom/web/uk.site.com/startup.pl

    ScriptAlias /cgi-bin/ /home/steampunkcom/web/uk.site.com/public_html/cgi-bin/

    Alias /vstats/ /home/steampunkcom/web/uk.site.com/stats/
    Alias /error/ /home/steampunkcom/web/uk.site.com/document_errors/

    # Uncomment this part to make run as mod_perl - comment out above as well!
    <Directory "/home/steampunkcom/web/uk.site.com/*">

        Options +ExecCGI +FollowSymLinks +MultiViews
        AllowOverride AuthConfig

        PerlResponseHandler ModPerl::Registry
        AddHandler perl-script .cgi .pl
        Options +ExecCGI
        PerlOptions +ParseHeaders
        AllowOverride All
        Require all granted

    </Directory>

    <Directory /home/steampunkcom/web/uk.site.com/stats>
       AllowOverride All
       Require all granted
    </Directory>

    <IfModule mod_ruid2.c>
        RMode config
        RUidGid steampunkcom steampunkcom
        RGroups www-data
    </IfModule>
    <IfModule itk.c>
        AssignUserID steampunkcom steampunkcom
    </IfModule>

    IncludeOptional /home/steampunkcom/conf/web/apache2.uk.site.com.conf*

</VirtualHost>

This works fine. It runs under mod_perl well. The issue arises when I try and enable mod_perl on another user account:
<VirtualHost *:8181>

    CustomLog /home/willr/web/anothersite.co.uk/logs/anothersite.co.uk.apache.log combined
    ErrorLog /home/willr/web/anothersite.co.uk/logs/anothersite.co.uk.apache.error.log

    LogLevel error

    RemoteIPHeader X-Forwarded-For

    LoadModule perl_module /usr/lib/apache2/modules/mod_perl.so

    PerlRequire  /home/willr/web/anothersite.co.uk/startup.pl

    ServerName anothersite.co.uk
    ServerAlias www.anothersite.co.uk
    ServerAdmin info@anothersite.co.uk
    DocumentRoot /home/willr/web/anothersite.co.uk/public_html

    #####
    ScriptAlias /cgi-bin/ /home/willr/web/anothersite.co.uk/public_html/cgi-bin/
    #####

    Alias /vstats/ /home/willr/web/anothersite.co.uk/stats/
    Alias /error/ /home/willr/web/anothersite.co.uk/document_errors/

    <Directory "/home/willr/web/anothersite.co.uk/*">
        Options +ExecCGI +FollowSymLinks +MultiViews
        AllowOverride AuthConfig

        PerlResponseHandler ModPerl::Registry
        AddHandler perl-script .cgi .pl
        Options +ExecCGI
        PerlOptions +ParseHeaders
        AllowOverride All
        Require all granted

    </Directory>

    <IfModule mod_ruid2.c>
        RMode config
        RUidGid willr willr
        RGroups www-data
    </IfModule>
    <IfModule itk.c>
        AssignUserID willr willr
    </IfModule>

</VirtualHost>

At first I thought it was all working fine, but then I started getting emails from people telling me they couldn't log into the site. Upon looking into it, I found that it was sharing a module across the user accounts. I'm trying to figure out why, and what I can do about it. I know for a fact mod_perl can run across multiple user accounts without sharing the modules (as I've done it on other servers that were managed for me), but I'm not sure how/ why its doing it here.
Any ideas are much appreciated! In the meantime I've had to disable mod_perl for one of the sites, as it was causing too many issues for the other site :(
I just found something about using the +Parent and PerlSwitches config:
 <VirtualHost ...>
      ServerName dev1
      PerlOptions +Parent
      PerlSwitches -I/home/dev1/lib/perl
  </VirtualHost>

https://perl.apache.org/docs/2.0/user/config/config.html#C_Parent_
The problem though is that it still seems to cause the modules to get "shared" across other user accounts. So I have:
PerlOptions +ParseHeaders +Parent
PerlSwitches -Mlib=/home/steampunkcom/web/foo.co.uk/lib

When I look at the contents of @INC, I can see:
@INC =
    /home/steampunkcom/web/foo.com/public_html/cgi-bin/admin
    /home/steampunkcom/web/foo.com/lib
    /etc/perl
    /usr/local/lib/x86_64-linux-gnu/perl/5.22.1
    /usr/local/share/perl/5.22.1
    /usr/lib/x86_64-linux-gnu/perl5/5.22
    /usr/share/perl5
    /usr/lib/x86_64-linux-gnu/perl/5.22
    /usr/share/perl/5.22
    /usr/local/lib/site_perl
    .
    /etc/apache2

I really thought I had a solution there, but maybe not :(

A: OK so this seems to work.
PerlOptions +Parent
PerlInterpStart 2
PerlInterpMax 2
PerlSwitches -Mlib=/home/steampunkcom/web/uk.domain.com/lib
PerlRequire  /home/steampunkcom/web/uk.domain.com/startup.pl # my script to auto load modules

It seems the order is important as well. I'm not sure if this was part of the solution as well, but I gave the server a reboot. I'm wondering if maybe something got "stuck" when I was playing with the settings, and no matter how many time I restarted Apache it wouldn't fix the issue.
Anyway - I think this has sorted it! At least I'm not seeming to get clashing modules any more.


text:
Q: Path-Dependent type inside class value in Scala I would like to give a value of a type with an abstract type to a class and later use it's path dependent type. Look at the following example (using Scala 2.10.1):
trait Foo {
  type A
  def makeA: A
  def useA(a: A): Unit
}

object Test {

  class IntFoo extends Foo {
    type A = Int
    def makeA = 1
    def useA(a: Int) = println(a)
  }

  class FooWrap(val a: Foo) {
    def wrapUse(v: a.A) = a.useA(v)
  }

  val foo = new IntFoo

  /* Path dependent locally */
  val bar = foo
  bar.useA(foo.makeA)   // works

  /* Path dependent through class value */
  val fooWrap = new FooWrap(foo)

  fooWrap.a.useA(foo.makeA)  // fails
  // error: type mismatch; found : Int required: Test.fooWrap.a.A

  fooWrap.wrapUse(foo.makeA) // fails
  // error: type mismatch; found : Int required: Test.fooWrap.a.A

}

First, I do not understand the fundamental difference between the local and the class-value case (note the public, immutable value) and why the type checking fails (because obviously Test.fooWrap.a.A =:= foo.A). Is this a limitation of the Scala compiler?
Second, how can I achieve what I am trying to do?
UPDATE
It seems that this can be achieved by using generics and inline type-constraints:
class FooWrap[T](val a: Foo { type A = T }) {
  def wrapUse(v: T) = a.useA(v)
}

However, in my case, A is actually a higher-kinded type, so the example becomes:
trait Foo {
  type A[T]
  def makeA[T]: A[T]
  def useA(a: A[_]): Unit
}

object Test {

  class OptFoo extends Foo {
    type A[T] = Option[T]
    def makeA[T] = None
    def useA(a: A[_]) = println(a.get)
  }

  class FooWrap(val a: Foo) {
    def wrapUse(v: a.A[_]) = a.useA(v)
  }

  val foo = new OptFoo

  /* Path dependent locally (snip) */

  /* Path dependent through class value */
  val fooWrap = new FooWrap(foo)

  fooWrap.a.useA(foo.makeA)  // fails
  // polymorphic expression cannot be instantiated to expected type;
  // found : [T]None.type required: Test.fooWrap.a.A[_]

  fooWrap.wrapUse(foo.makeA) // fails
  // polymorphic expression cannot be instantiated to expected type;
  // found : [T]None.type required: Test.fooWrap.a.A[_]

}

A: In your original question, your problem is that the Scala compiler is unable to prove equality of the result type of foo.makeA with the argument type of fooWrap.a.useA. To do that it would need to be able to prove the identity of foo with fooWrap.a which we can intuitively see must be the case here, but which isn't straightforward for the compiler to track.
There are a couple of ways to work around this problem. First, you could use fooWrap.a uniformly in place of foo,
scala> fooWrap.a.useA(fooWrap.a.makeA)
1

Now it's simple for the compiler to recognize the prefix of A (fooWrap.a) as being the same in both occurrences.
Second, you could parametrize FooWrap in a way which captures the type of its Foo argument more precisely,
scala> class FooWrap[F <: Foo](val a: F) {
     |   def wrapUse(v: a.A) = a.useA(v)
     | }
defined class FooWrap

scala> val fooWrap = new FooWrap(foo)
fooWrap: FooWrap[IntFoo] = FooWrap@6d935671

scala> fooWrap.a.useA(foo.makeA)
1

Here the type argument of FooWrap is inferred as IntFoo rather than as bare Foo, hence A is known to be exactly Int, as it is in the result type of foo.makeA.
In your update you introduce an additional wrinkle: you change the signature of useA to,
def useA(a: A[_]): Unit

The _ here is an existential which will frustrate all attempts to coax the compiler into proving useful type equalities. Instead you need something along the lines of,
trait Foo {
  type A[T]
  def makeA[T]: A[T]
  def useA[T](a: A[T]): Unit
}

class OptFoo extends Foo {
  type A[T] = Option[T]
  def makeA[T]: A[T] = None
  def useA[T](a: A[T]) = a map println
}

class FooWrap[F <: Foo](val a: F) {
  def wrapUse[T](v: a.A[T]) = a.useA(v)
}

val foo = new OptFoo

Sample REPL session,
scala> val fooWrap = new FooWrap(foo)
fooWrap: FooWrap[OptFoo] = FooWrap@fcc10a7

scala> fooWrap.a.useA(foo.makeA)

scala>

A: The higher kinded-type can be added to FooWrap as generic parameter, too:
class FooWrap[T[V]](val a: Foo { type A[V] = T[V] }) {
  def wrapUse(v: T[_]) = a.useA(v)
}

but (in this example) the inference fails:
val fooWrap = new FooWrap[Option](foo)

Otherwise:
- type mismatch; found : Test.foo.type (with underlying type Test.OptFoo) required: Foo{type A[V] = T[V]}
- inferred kinds of the type arguments (Option[V]) do not conform to the expected kinds of the type parameters (type T) in class FooWrap. Option[V]'s type parameters do not match type T's expected
 parameters: class Option has one type parameter, but type T has one

Any other, nicer solutions?


text:
Q: I can't get the attribute name of an abstract class in c# This is the class:
public abstract class DbAttributeInstance
{
    public static DbAttribute AALLAN;

    public static DbAttribute AANGXZ;

    public static DbAttribute AANGYZ;

    public static DbAttribute ABLE;

    public static DbAttribute ABOP;
...
}

I used the following code to get the member name, but got nothing:
System.Reflection.PropertyInfo[] properties = typeof(DbAttributeInstance).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

The final purpose of this operation is to test the class DbAttributeInstance's every attributes' validity, like this:
if (elem.IsAttributeValid(DbAttributeInstance.GEOM)) then...

but there are too many attributes in DbAttributeInstance so I can't test them one by one.
I want to test every member by using the following form:
//original way to be replaced
elem.IsAttributeValid(DbAttributeInstance.member1)
elem.IsAttributeValid(DbAttributeInstance.member1)
elem.IsAttributeValid(DbAttributeInstance.member1)
elem.IsAttributeValid(DbAttributeInstance.member1)
elem.IsAttributeValid(DbAttributeInstance.member1)
...
//new
foreach (member in DbAttributeInstance's members) {
    elem.IsAttributeValid(member)
}

A: I think you need to use another flag, according to MSDN:
There is a BindingFlags.Static.


text:
Q: CSS Logged in User not recognised This code does not recognise a logged in User on my database. I've tried several things, none of which so far have affected anything. Can Someone point out the error(s)
 <?php
 session_start();
 include("dbconnect.php");
 $numrows=0;
 $sqlMember = mysql_real_escape_string($_POST["Membership_Number"]);
$sqlPassword = mysql_real_escape_string($_POST["Password"]);

 $query="SELECT First_name, Last_name, Membership_Number FROM members WHERE Membership_Number='$member' AND Password='$password'";

 $link = mysql_query($query);
 if (!$link) {
  die('login error');
 }
 $numrows=mysql_num_rows($link);
 if ($numrows>0){  // authentication is successfull
  while($row = mysql_fetch_array($query));
  $_SESSION['user']['first_name']=$row['first_name'];
  $_SESSION['user']['last_name']=$row['last_name'];
  $_SESSION['user']['Membership_Number ']=$row['Membership_Number '];
  echo $_SESSION['user']['fname'].' '.$_SESSION['user']['lname'];
  header("location:members_area.php");
 } else {
  header("location:../invalid.php");  // authentication was unsuccessfull
 }
?>

HTML
<form id="jjjj" action="Send_log_details.php" class="register" method="POST">

        Membership Number:

        <input type="text" id="Membership_Number" name="Membership_Number">

        Password:

        <input type="password"  id="Password" name="Password" value="Log in">

        <input type="submit" name="register" value="Login" onclick="logMeIn()">

        </form>

Thanks for your help

A: you have $link variable containing MYSQL query and you are using $query variable.
if ($numrows>0){
  while($row = mysql_fetch_array($link)) {
      $_SESSION['user']['first_name']=$row['first_name'];
      $_SESSION['user']['last_name']=$row['last_name'];
      $_SESSION['user']['Membership_Number']=$row['Membership_Number'];
  }
  echo $_SESSION['user']['fname'].' '.$_SESSION['user']['lname'];
  header("Location: members_area.php");

 } else {
  header("Location: ../invalid.php");
 }

A: Could the this line be the problem:
$_SESSION['user']['Membership_Number ']=$row['Membership_Number '];

It should be:
$_SESSION['user']['Membership_Number']=$row['Membership_Number'];

I have removed the space from the end of the array key name.


text:
Q: How to return a character set after matching a specific string in a regular expression I'm actually using using a command line tool called sox to retrieve information about an audio file. This returns the following output:
Samples read:            449718
Length (seconds):     28.107375
Scaled by:         2147483647.0
Maximum amplitude:     0.999969
Minimum amplitude:    -0.999969
Midline amplitude:     0.000000
Mean    norm:          0.145530
Mean    amplitude:     0.000291
RMS     amplitude:     0.249847
Maximum delta:         1.316925
Minimum delta:         0.000000
Mean    delta:         0.033336
RMS     delta:         0.064767
Rough   frequency:          660
Volume adjustment:        1.000

I'd like to extract the values out of this using a regular expression. So far I have /^Length \(seconds\):\s*[0-9.]*/m which matches Length (seconds):     28.107375 but I just want the value.
What do I need to do?

A: Two options (I'm not familiar with sox, so I'm not sure how exactly this would work in sox):

*

*You can use lookbehind to match the first part. This works in case the regex engine allows variable length lookbehind: /(?<=^Length \(seconds\)\:\s*)[\d.]*/

*You can capture the value in a group to reference it later: /^Length \(seconds\):\s*([\d.]*)/. this will work if sox has a capture group functionality. In this case, the value will be held in the first capture group ($1 in ruby)

A: "soxi -D filename" returns the length of filename in seconds. Just the number, nothing else. Information about SoXI can be found here

A: awk '/^Length \(seconds\):/ { print $NF }'


text:
Q: Program hangs if thread is created in static initializer block I have come across a situation where my program hangs, looks like deadlock. But I tried figuring it out with jconsole and visualvm, but they didn't detect any deadlock. Sample code:
public class StaticInitializer {

private static int state = 10;

static {
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            state = 11;
            System.out.println("Exit Thread");
        }
    });

    t1.start();

    try {
        t1.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("exiting static block");
}

public static void main(String...strings) {
    System.out.println(state);
}
}

When I execute this in debug mode then I could see control reaching
                        @Override
            public void run() {
                state = 11;
but as soon as state=11 is executed it just hangs/deadlocks. I looked in different postings in stackoverflow and I thought that static initializers are thread-safe but in that case jconsole should report this. About main thread, jconsole saying that it is in waiting state, and that's fine. But for the thread created in static initializer block, jconsole says that it is in RUNNABLE state and not blocked. I am confused and here lacking some concept. Please help me out.

A: I was able to get your program to run by commenting out the line state = 11;
You can not set state=11 until you have completed initialization.  You can not complete initialization until t1 finishes running.  T1 can not finish running until you set state=11.  Deadlock.

A: Here is what I think happens:

*

*The main thread tries to initialize StaticInitializer. This involves locking the corresponding Class object.

*While still holding the lock, the main thread spawns another thread, and waits for it to terminate.

*The other thread's run() method attempts to access state, which requires StaticInitializer to be fully initialized; this involves waiting on the same lock as in step 1.

End result: a deadlock.
See the JLS for a detailed description of the intialization procedure.
If you move t1.join() into main(), everything works.

A: You're not just starting another thread - you're joining on it. That new thread has to wait for StaticInitializer to be fully initialized before it can proceed, because it's trying to set the state field... and initialization is already in progress, so it waits. However, it's going to be waiting forever, because that initialization is waiting for that new thread to terminate. Classic deadlock.
See the Java Language Specification section 12.4.2 for details about what's involved in class initialization. Importantly, the initializing thread will "own" the monitor for StaticInitializer.class, but the new thread will be waiting to acquire that monitor.
In other words, your code is a bit like this non-initializer code (exception handling elided).
final Object foo = new Object();
synchronized (foo)
{
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (foo) {
                System.out.println("In the new thread!");
            }
        });
    t1.start();
    t1.join();
});

If you can understand why that code would deadlock, it's basically the same for your code.
The moral is not to do much work in static initializers.

A: classloading is kind of a sensitive time in the jvm.  when classes are being initialized, they hold an internal jvm lock which will pause any other thread trying to work with the same class.  so, your spawned thread is most likely waiting for the StaticInitializer class to be fully initialized before proceeding.  however, your StaticInitializer class is waiting for the thread to complete before being fully initialized.  thus, deadlock.
of course, if you are truly trying to do something like this, the secondary thread is superfluous since you are joining it right after you start it (so you might as well just execute that code directly).
UPDATE:
my guess as to why the deadlock is not detected is because it is occurring at a much lower level than the level at which the standard deadlock detection code works. that code works with normal object locking, whereas this is deep jvm internal stuff.