How do I write migrate group files?

Question: I'm trying to create a Migrate group with following code. But it is not detected & listed in admin/structure/migrate. Both migrate plus & Migrate tools modules are installed.  I"m trying to create migration from WordPress tables. The module is called migrate_wordpress & migrate group is defined in config/install with the name migrate_wordpress. migrate_group.wordpress.yml
id: wprdpress
label: WordPress Imports
description: Import from WordPress blog
source_type: Custom tables

What is wrong with above Migrate group configurations? What is the correct way to write an migrate group configuration file in Drupal 8?
Answer: I believe that groups are a feature of the migrate_plus module. In order for them to be recognised, the file needs to be named migrate_plus.migration_group.<group_name>.yml. The actual migrations also need to be formatted like this migrate_plus.migration.<migration_name>.yml.
One other issue I see is that your id: wprdpress should be id: wordpress. (Just in case that typo is in your code :) )
The last thing is that migrations are only defined on module install. This means that you have to uninstall and re-install every time. (Or you can implement some drush commands to do it for you. Check out this tutorial.)
Comment: Glad it helped! This is all fresh in my brain as I've been working my way through my own D8 migration. Banged my head against the wall for quite a while on this one.
Comment: It worked wonderful , I'm able to see Migration groups and actual migrations listed too.  Also thanks for the nice tutorial.
Comment: The [Devel](https://www.drupal.org/project/devel) module has the command `drush dre my_module` to reinstall a module.
Answer: In .yml file we define four major parts for Migration. These are id, source, process and destination. Id is to identify this Migration process Id to identify. Source is defined with the data source. Process define basically the mapping of fields in between destination and source.
It seems you are missing process and destination.
To define Migration group you can define it like this
migration_group: custom
destination:
      plugin: entity:file
You can refer this Migrate Module as well.

How do I write migrate group files?


Add text to user login page

Question: I'm attempting to add text to user login page, with general info about accounts rather than only displaying the login form.
I have a page.html.twig template like so
{{ page.header }}

This is my page template

{{page.content}}
{{ page.footer }}

I then can create content in page--user--login.html.twig like so.
{{ page.header }}

This is my page template

Enter your login information here

{{page.content}}
{{ loginform }}
{{ page.footer }}

But is there anyway to just add text to the login form without recreating page.html.twig. Since it would just be a copy I'd rather consolidate everything so any change wouldn't have to be made to both. Is there a template I could use like node--user--login.html.twig. So that the content would use page.html.twig and use the page.content block?
I understand that you can make changes to the form using a theme_form_alter hook but I'm not sure how to add html to the form from there. I can only change things like placeholder text, and submit values.
Comment: Cant you use form alter and show the text
Comment: I am using form alter but I'm not sure how to add text using it. I know I can change things like the submit value, but I don't see a way to just add html.
Comment: @Matt please check the answer, how to do easily using hook.
Answer: You can do this very simple way using hook_form_FORM_ID_alter.
Paste following code in your themename.theme file and clear the cache
function YourThemeName_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
    $form['newline'] = array(
      '#type' => 'markup',
      '#markup' => t('
Enter your login information here!
'),
      '#weight' => -10,
    );
}

Image output:
Before:

After:

This way you do not need to worry about anything, it will only show in Login page.
Answer: You can create a custom block that appears only on /user.
After you create the custom block, configure it to appear in the content region. You could also need to set a condition for anonymous users.
Comment: You would also need to set a Condition for the anonymous user role.
Answer: Place this hook in your .theme file and replace HOOK with your theme name. You can change your heading and paragraph text accordingly.
/**
 * Implements hook_form_alter().
 */

function HOOK_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#form_id'] == 'user_login_form') {
    $form['forgot'] = array(
      '#type' => 'markup',
      '#weight' => -10,
      '#markup' => '
This is my page template

Enter your login information here
',
    );
    }
}

This hook will work properly. That is working fine for me.
Thank you

Add text to user login page


Why isn't my 3D collision detection working?

Question: I have several objects in my world, there are three primary types. The first is self, which is the player, the player does not move, but they do rotate. The second are bullets which fly out away from the user in a straight line. And the third are targets, these just sit somewhere and wait to be hit.
Here's the code I'm using to do collision detection and it isn't working:
<code>        foreach (GameObject go in bullets) {
            float goRadius = go.Model.Meshes.Sum((x) => x.BoundingSphere.Radius) * go.Scale;
            EnemyObject last = null;

            Vector3 goRealPos = Vector3.Transform(go.Position, Matrix.CreateScale(go.Scale) * Matrix.CreateTranslation(go.Position) * Matrix.CreateRotationY(go.Rotation.Y));

            foreach (EnemyObject eo in targets) {
                float eoRadius = eo.Model.Meshes.Sum((x) => x.BoundingSphere.Radius) *eo.Scale;

                if (Vector3.Distance(eo.Position, goRealPos) < eoRadius + goRadius) {
                    //collision has occured
                    if (!eo.TakeHit()) {
                        last = eo;
                    }

                    //remove bullet
                    toBeRemoved.Add(go);

                    break;
                }
            }

            if (last != null) {
                targets.Remove(last);
            }
            if (go.Position.Z > 2000 || go.Position.Z < -2000) {
                toBeRemoved.Add(go);
            }
        }
</code>
Can anyone tell me why it isn't working?
Answer: Note that if the bullets are moving too fast, they might sweep through your targets without hitting them. Use sweep-through-safe hittesting technologies for example with rays.
Comment: That isn't the case. I've slowed my bullets down to a crawl and my targets are rather large but the collision never happens (According to my math), although my eye's see it
Answer: Did you check that your calculation for goRealPos is getting approximately the coordinate you expect?  Why are you transforming goRealPos from go, but not doing anything similar for eo?  It could be that you are testing for collisions between object that aren't on the same coordinate system.
Comment: It seems that this is the case, but the goRealPos may or may not be accurate. The reason I did not do anything to eo is because it's not moving so it should be on the same position as it says it is.


When a player first signed in using com.google.android.gms.plus

Question: My current Android application allows users to signin using the Google Plus button.
A feature of my application is that i would like to reward users who return within a month of first signing in.
Do i have to remember when they first signed in using Google Plus?
Or does the com.google.android.gms.plus API expose this detail? e.g. initial Sign In date cross referenced to my Application.
I have searched the com.google.android.gms.plus docs but couldnt see anything.
Did i miss something?
Answer: I'm not aware of a G+ API that tells you when a user first authorized an application. I would recommend using Androids app data storage. That should be pretty lightweight. You can also open a feature requests.
Comment: abraham, thanks for your time, i believe you are correct. i have raised a feature request.


SwiftUI ForEach asks that items are Hashable and Equatable for some reason?

Question: I am following the CS193P Stanford class, in which we are supposed to build a ForEach view with an array of Cards, defined in this struct :
struct MemoryGame<CardContent> {
    private(set) var cards : [Card]

    init(pairCount : Int, createCardContent : (Int) -> CardContent){
        cards = []
        for i in 0 ..< pairCount {
            let content = createCardContent(i)
            cards.append(Card(content : content, id : i*2))
            cards.append(Card(content : content, id : i*2 + 1))
        }
    }

    func choose(_ card: Card) {

    }

    struct Card : Identifiable {
        var isFaceUp : Bool = true
        var isMatched : Bool = false
        var content : CardContent
        var id: Int
    }
}

As you can see, this struct conforms to the Identifiable protocol, which according to the documentation should be enough for it to work in a ForEach (Provided the type of id is Hashable, which Int is)
Yet I get the following error :
Generic struct 'ForEach' requires that 'MemoryGame<String>.Card' conform to 'Hashable'

Why is it asking that ? The only thing the docs say is that the type of id should be Hashable, nothing about the entire struct being Hashable
The error hints also want me to add Equatable but I can't seem to understand why, there is no reported error linked to that
NB : I am building in XCode 13 on macOS Monterey 12.0.1 with iOS 15 as a target

Here is then the ViewModel code for EmojiMemoryGame :
class EmojiMemoryGame {
    static let emojis = ["", "", "", "", "", "", "", ""]
    private(set) var model = MemoryGame<String>(pairCount: 4) {i in emojis[i]}

    var cards: Array<MemoryGame<String>.Card> {
        model.cards
    }
}

And the ContentView :
struct ContentView: View {

    let viewModel : EmojiMemoryGame

    var body: some View {
        VStack {
            ScrollView {
                LazyVGrid(columns : [GridItem(.adaptive(minimum : 65))]) {
                    ForEach(viewModel.cards) { card in // Error happens here
                        CardView(card)
                            .aspectRatio(2/3, contentMode: .fit)
                    }
                }
            }
            .foregroundColor(.red)
        }
        .padding(.horizontal)
    }
}

Comment: I hope you are not doing `id: \.self` in your ForEach
Comment: Can you show _how_ you are using your struct in `ForEach`?
Comment: I am not using \.self, adding the foreach code to the post...
Comment: What is your `CardContent`? I suspect it needs to be `Identifiable` as well.
Comment: @Yrb I have added every line of code of the project to the post (safe for CardView which I think is irrelevant to the issue at hand)
Comment: The reason it is important is this: [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). I found someone else's `CardView` and put the app together. I see no errors. I get a grid of emoji pairs when it runs. This may be a phantom error. Clean your build folder, delete the apps folder in Derived Data and rebuild it. See if that works.
Comment: Post may be dated, but wondering why using id: \.self would know an error?
Answer: I copied pasted your code without modifying  anything, it ran without any error.
That ForEach is not the problem here. If you still face the error, try this:
ForEach(viewModel.cards, id: \.id) { }

Comment: Honestly I'm way past that point right now, I think it's just the random kinda errors Xcode like to throw sometimes
Answer: I have implemented a var id = UUID() on the Card struct, made it conform to Identifiable and removed the id: .self from the ForEach loop. It's valid now.
   struct Card: Identifiable {
        var id = UUID()
        var isFacedUp: Bool = false
        var isMatched: Bool = false

        var content: CardContent

    }

    LazyVGrid(columns: [GridItem(.adaptive(minimum: 65))]) {
        ForEach(viewModel.cards) { card in
            CardView(card: card)
                .aspectRatio(2/3, contentMode: .fit)
        }
    }


Executing an exec() or system() in PHP and do not wait for output

Question: I want to trigger a shell command in eider exec() or system() from PHP script but it is a task that take a while to complete, is there a way to trigger it and continue running the PHP page load without delay?
Edit: I am on CentOS 6, PHP 5.3
Answer: Depends on the OS you are using.
For linux:
pclose(popen("php somefile.php &","r"));

notice the amperstand at the end (very important).
For windows:
pclose(popen("start php.exe somefile.php","r"));

here the start keyword is important.
Hope this helps.
Comment: I tried `exec("php video_processor.php &");` and delay is the same, then also if I set a `sleep(10)` inside video_processor.php then my parent script also waits for 10 seconds.
Comment: Windows specific comment:
I used to use: pclose(popen("start /B php.exe somefile.php","r"));
as of Windows 10 Creators Update (1703) - the "/B" background switch for "start" command doesnt work. Glad to see that it isnt needed.
Comment: Try with `pclose(popen("php video_processor.php &","r"));` or `pclose(popen("/usr/bin/php video_processor.php &","r"));` (I assume your PHP is installed in the default location)
Comment: It worked with this one: `pclose(popen("php video_processor.php &","r"));` so then I edited mine and it worked: `pclose(popen("ffmpeg -i 'videos/sample.mp4' -qmax 1 -vframes 1 -ss 80 videos/images/1.jpg &","r"));` Thank you. :party: :)
Comment: Wow, I can't believe how easy and simple this is to do!  Brilliant solution!  I have researched this at some length before and every other solution recommended complex strategies for forking or threading a PHP process.
Answer: This doesn't answer your question directly, but you should consider doing your video conversion work in a background process with either a cron job or using a queue such as Beanstalkd.
This way you can stack up your ffmpeg work in the background without blocking your webserver.
I've had a lot of success with both methods (cron / queue) in the past.
Some other posts about background processes:
php execute a background process
Run a ffmpeg process in the background
Using ffmpeg, PHP and beanstalk
Some tools you might find useful:
http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/
PEAR System_Daemon
Pheanstalk, a Beanstalkd library for PHP
Answer: What I do:
public function post_create()
{
    ob_end_clean();
    header("Connection: close");
    ignore_user_abort(); // optional
    ob_start();
    echo "Tell ajax to gtfo!";

    $size = ob_get_length();
    header("Content-Length: $size");
    ob_end_flush(); // Strange behaviour, will not work
    flush();            // Unless both are called !
    // Do processing here
}

Comment: Seems to work with just `header('Content-Length:0');flush();` for me
Answer: This should work:
shell_exec("nohup yourcommand > /dev/null 2> /dev/null &");

Edit: sorry, dunno why I excluded the & to put it to bg
2> redirects STDOUT and STDERR to /dev/null.
Comment: Command runs but the delay is there, this is the full command: `shell_exec("ffmpeg -i 'videos/sample.mp4' -qmax 1 -vframes 1 -ss 80 videos/images/1.jpg 2> /dev/null");`
Comment: try: shell_exec("nohup ffmpeg -i 'videos/sample.mp4' -qmax 1 -vframes 1 -ss 80 videos/images/1.jpg > /dev/null 2> /dev/null")
Comment: Same delay, command executed fine. Maybe ffmpeg just acts differently?
Comment: Just tested this myself with PHP and ffmpeg and now it works.
Answer: Well use an ajax request to activate the exec part ...then continue with the other tasks
Comment: It would probably work but there should be an easier and more reliable way, like a parameter at the end of exec() or system();
Comment: I don't get the -1 level. Guy gave a short answer. Maybe disliked, but still a fair one.
Comment: After trying any other solution finally managed to make it work using your suggestion. Thank you very much!


Archiva / Maven as corporate repository

Question: I am setting up Maven corporate repository using Apache Archiva for my company.
Our requirements for now are quite basic - have an internal repo for our jar files and dependency management.
I want to make sure that Archiva does not upload any of our proprietary code / jar files to Central Repo (Public), but we would like to be able to download public libs from central repo if needed by the project.
(Our desired configuration: IDE/Developer <Download/Upload> Internal Repository <DOWNLOAD ONLY> Public Central Repo.)
My question is, by default, does Archiva upload my jar files to central repo if its configured as a proxy/mirror? if so, how do I prevent publishing to central/external repo while keeping the option to download from central when needed?
Appreciate any answers.
Answer: If you configure the local/managed repository which is linked to Central as read-only, then nobody can upload to it. This is done by only giving the "Repository Observer" role but not the "Repository Admin" (in fact you will most likely add additional roles, just make sure none of them is assigned for any developer to one of the mirrored repos).
BTW: you can also disallow re-deploy (aka overwrite of artifact versions) for a repository. This is generally a good idea. This is done in the repository settings (not by roles).
One additional thing you might want to look for: if you configure a repo to be Snapshot only, it still will accept SNAPSHOT uploads. This can be quite confusing, make sure nobody does that.
Comment: Thanks you very much for your answer!
Just one more thing to clarify - as an admin - if I add an internal-use jar file to my internal repo (which is linked to central), will it automatically be synced up?
What is the process to sync to central?

Just trying to understand the default behavior of internal repo.

Thanks again!
Comment: No syncing to Central is a process outside of Archiva. I think Central no longer accepts single sources, so you need to pick one of the forges which actually offer that feature. I know [Bintray](https://bintray.com/docs/usermanual/uploads/uploads_syncingartifactswithmavencentral.html) offers this, but it requires some paperwork.

Archiva / Maven as corporate repository


cordova.fileTransfer not updating page template Ionic2+Cordova

Question: I have created an Ionic2 App using cordova FileTransferplugin, i am downloading remote server file.
Everything is working perfectly, but when I try to update template while fileTransfer.OnProgress event, the template is not updating the % downloaded.
Pleas see this video for my problem.
Ionic_youtube_link
My Code is, logic is in downloadFile function
import {Component, AfterViewInit, ViewChild} from '@angular/core';
import {NavController, NavParams, ViewController, Nav} from 'ionic-angular';

import {Page, Platform} from 'ionic-angular';
import {File, Device, Cordova, Transfer} from 'ionic-native';

import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';

@Component({
  templateUrl: 'build/pages/video-download-modal/video-download-modal.html',
  providers: [File, Transfer]
})
export class VideoDownloadModal {
  selectedItem: any;
  @ViewChild(Nav) nav: Nav;

  videoPathUrl: string;
  isPlatformReady: boolean;
  platformName: string;
  directoryName: string = "socialAppDir";

  totalVideoSize:number;
  totalDownloaded:number;
  totalPercent:string = "0%";

  constructor(public navCtrl: NavController, navParams: NavParams, private _viewController: ViewController, platform: Platform, private transfer:Transfer) {
    // If we navigated to this page, we will have an item available as a nav param
    if (platform.is('core')) {//if on dekstop
      console.log('dektop');
    } else {
      this.videoPathUrl = navParams.get('videoPath');
      console.log(this.videoPathUrl);
      platform.ready().then((readySource) => {
        this.isPlatformReady = true;
        console.log('ready 1234');
        const fs: string = cordova.file.externalRootDirectory;
        console.log(cordova.file.dataDirectory);
        this.platformName = Device.device.platform;

        File.checkDir(cordova.file.externalDataDirectory, this.directoryName).then(() => {
          console.log('directory exists');
          this.downloadFile();
        }, (error) => {
          console.log('directory not exists');
          this.createDirectory();
        })

      })
    }
  }
  dismiss() {
    let data = { 'foo': 'bar' };
    this._viewController.dismiss(data);
  }

  createDirectory():void{
    File.createDir(cordova.file.externalDataDirectory, this.directoryName, true).then(() => {
      console.log("created externalDataDirectory");
      this.downloadFile();
    },(error) => {
      console.log('some error happen')
    })
  }

  downloadFile = () => {
    console.log(this);
    let fileName: string = this.videoPathUrl.split("/").pop();
    let targetPath = cordova.file.externalDataDirectory + this.directoryName + "/" + fileName;
    console.log(targetPath);
    this.transfer.download(this.videoPathUrl, targetPath, true, {}).then(() => {
      console.log('video downloaded')
    }, (error) => {
      console.log(error)
    })
    this.transfer.onProgress((progress) => {
      console.log(this);
      this.totalVideoSize = progress.total;
      this.totalDownloaded = progress.loaded;
      this.totalPercent = ((progress.loaded / progress.total) * 100).toString();

      console.log(this.totalPercent);
    })
  }

  ionViewDidEnter() {
    console.log("enter login1");
  }
}

And HTML is
<ion-content>

    <ion-spinner></ion-spinner>

    {{**totalPercent**}}

    <button dnager block (click)="dismiss()">Exit</button>

</ion-content>

The totalPercent value either has 0 or 100.But not updating.
Please help.
Answer: This is because the totalPercent of this inside the handler was set to the global Window object instead of the object itself.
I have finally got it to work
import { NgZone } from '@angular/core';
fileTransfer.onProgress((progressEvent: ProgressEvent) => {
  this.ngZone.run(() => {
    if (progressEvent.lengthComputable) {
      let lp = progressEvent.loaded / progressEvent.total * 100;
      this.loadingPercent = Math.round(lp * 100) / 100;
    }
  });
})


Can I make bazel java_binary rule replace default jar with with _deploy.jar

Question: I'd like to make Bazel always build the _deploy jar and replace it with the default created jar.
The reason is that I'd like to use the pomgen plugin to install the "uber" jar into the .m2 repo, for use in a maven project I am in the process of migrating.
With this config:
java_library(
    name = "foo-lib",
    srcs = glob(["src/main/java/**/*.java"]),
    resources = glob(["src/main/resources/**"]),
    deps = [
        "@maven//:junit_junit",
    ]
)

java_binary(
    name = "foo",
    main_class = "FooMain",
    runtime_deps = [":foo-lib"]
)

The foo_deploy.jar is created only when I call bazel build //foo:foo_deploy.jar, but I did not see a way to specify to pomgen to deploy this jar instead of the foo.jar file.
Answer: Actually, after digging in a bit to the pomgen plugin, it seems that they automatically deploy the foo-deploy.jar if no libfoo.jar found...
https://github.com/salesforce/pomgen/blob/a54506845c554ef2ef795146bb662701f33c52d2/maven/maven_functions.sh


SQLAlchemy gives "MetaData not bound to Engine or Connection"

Question: I have this code to create a database:
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, Float, MetaData, ForeignKey
from sqlalchemy.sql import select, and_
from PyQt4 import QtGui, QtCore

class DbUtils(object):
    def __init__(self, db_file = None, parent = None):

        self.db = None
        self.db_connection = None
        self.db_file = str(db_file)

    def db_open(self):
        self.db = create_engine('sqlite:///' + self.db_file)
        self.db_connection = self.db.connect()

    def db_close(self):
        self.db_connection.close()

    def db_create_voltdrop(self):
        metadata = MetaData()

        tb_cable_brands = Table('cable_brands', metadata,
            Column('id', Integer, primary_key=True),
            Column('brand', String)
            )
        tb_cable_types = Table('cable_types', metadata,
            Column('id', Integer, primary_key=True),
            Column('brand_id', None, ForeignKey('cable_brands.id')),
            Column('type', String),
            Column('alpha', String)
            )
        tb_cable_data = Table('cable_data', metadata,
            Column('id', Integer, primary_key=True),
            Column('type_id', None, ForeignKey('cable_types.id')),
            Column('size', String),
            Column('resistance', Float)
            )
        metadata.create_all(self.db) # db_utils.py", line 67

When it was part of my GUI's QMainWindow class, it worked fine, no errors. But when I separated it from GUI into a separate module, it started giving me that error. Here's a traceback:
Traceback (most recent call last):
File "C:\Temp\xxx\applications\voltdrop\mainwindow.py", line 52, in __init__
    self.main_ui()
File "C:\Temp\xxx\applications\voltdrop\mainwindow.py", line 212, in main_ui
    self.db_utils.db_create_voltdrop()
File "C:\Temp\xxx\scripts\db_utils.py", line 67, in db_create_voltdrop
    metadata.create_all(self.db)
File "C:\Temp\PortablePython\App\lib\site-packages\sqlalchemy\schema.py", line 2511, in create_all
    bind = _bind_or_error(self)
File "C:\Temp\PortablePython\App\lib\site-packages\sqlalchemy\schema.py", line 3124, in _bind_or_error
    raise exc.UnboundExecutionError(msg)

sqlalchemy.exc.UnboundExecutionError:
The MetaData is not bound to an Engine or Connection.
Execution can not proceed without a database to execute against.
Either execute with an explicit connection or assign the MetaData's .bind to enable implicit execution.

    self.db_utils = DbUtils(self.cabledata_db, self)
    self.main_ui() # mainwindow.py", line 52

def main_ui(self):
...
    if not self.find_data_file(self.cabledata_db):
        file = self.select_data_file("cable")
        if file:
            self.cabledata_db = file
            self.db_utils.db_open()
        else:
            self.db_utils.db_create_voltdrop() # mainwindow.py", line 212

What am I doing wrong? Thank you.
[SOLVED]
Thank you. It works like this: if there's no DB file, open dialog and select one, if the dialog is cancelled, create an empty DB. If the dialog selects a file, use that DB. Otherwise, use the found DB file.
This works now:
    if not self.find_data_file(self.cabledata_db):
        file = self.select_data_file("cable")
        if file:
            self.cabledata_db = file
            self.db_utils.db_open()
        else:
            self.db_utils.db_open()
            self.db_utils.db_create_voltdrop()
    else:
        self.db_utils.db_open()

Comment: will you please write the code which create problem? I copy past the code but its working for me. From where this execute that I want.
Answer: You are not calling db_utils.db_open() before calling db_utils.db_create_voltdrop() if not file.
Hence the value of the db_utils.db is None when metadata.create_all(self.db) is called. Ensuring that you call db_utils.db_open() before you call db_utils.db_create_voltdrop() should fix your problem.
The reason that metadata.create_all(None) raises a sqlalchemy.exc.UnboundExecutionError, rather than an ValueError is that they allow you to do this:
metadata.bind = self.db
metadata.create_all()


Is Sobolev limit of bijective maps surjective?

Question: Let $\Omega_1,\Omega_2 \subseteq \mathbb R^2$ be open, connected, bounded, with non-empty $C^1$ boundaries. Let $f_n:\bar\Omega_1 \to \bar\Omega_2$ be $C^1$ be bijective maps with $\det(df_n)>0$, and suppose that $f_n$ converges to a continuous function $f: \bar\Omega_1 \to \bar\Omega_2$ strongly in $W^{1,2}$.

Question: Must $f$ be surjective?

Note that $f$ is surjective if and only if $|f^{-1}(y)| \le 1$ a.e. on $\Omega_2$:
By the area formula
$$
 \int_{\Omega_1} \det df_n  = \int_{\Omega_2} |f_n^{-1}(y)|=\text{Vol}(\Omega_2),
$$
so
$$
\int_{\Omega_2} |f^{-1}(y)|= \int_{\Omega_1} \det df  =\lim_{n \to \infty} \int_{\Omega_1} \det df_n=\text{Vol}(\Omega_2).
$$
This implies the claim.
Comment: Ok, I see what you are aiming for.
Comment: I don't get how you are applying the area formula. You should have $$ \mathrm{Vol}(\Omega_2) = \int_{\Omega_2} 1 \cdot \mathrm{d}x = \int_{\Omega_1} \underbrace{1 \circ f_n(x)}_{= 1} \det \mathrm{d}f_n(x) ~\mathrm{d}x $$  Are you using $|f^{-1}(y)|$ to denote the Cardinality of the set $f^{-1}(y)$? If that case, surjectivity would also require $|f^{-1}(y) | \geq 1$ by definition, and hence you see that $f$ is surjective if and only if $|f^{-1}(y) | = 1$ almost everywhere.
Comment: Yes, exactly. $|f^{-1}(y)|$ denotes the cardinality of the set $f^{-1}(y)$. I agree with your conclusion. My point was only that in this case surjectivity and "almost everywhere injectivity on the codomain" imply each other.
Answer: Suppose for contradiction that $f$ misses a point $q\in\Omega_2.$ It must miss some neighborhood $U\subset \Omega_2$ of $q.$ Choose a bump function $\alpha$ with $\int \alpha=1$ whose support lies in $U.$
The Jacobians $\det f_n$ converge in $L^1$ to $\det df.$ The functions $\alpha\circ f_n$ are uniformly bounded and converge in measure to $\alpha\circ f.$
By the result at Convergence in measure and $L_p$ implies product converges in $L_p$,
$$\int \alpha(f_n(x))\det df_n\to \int \alpha(f(x))\det df$$
The right hand side is zero because $\alpha\circ f\equiv 0.$ But by the change of variables formula along the orientation-preserving diffeomorphisms $f_n,$ the left hand side is $\int_{\Omega_2}\alpha = 1.$ This is a contradiction.
Comment: Thanks, that's a very nice argument! One question: Do you need the assumption that $\det df$ is a bounded function for getting estimate $(2)$? I understand why  $\alpha\circ f_n$ converges to $\alpha\circ f$ in $L^1$. I am asking why this remains true after multiplying pointwise by $\det df$. If I am not mistaken, I think that you need to assume that $\det df$ is bounded for that. (I actually don't have a problem with this additional assumption; I just wanted to be sure if you are actually relying on it, implicitly).
Comment: Oh I think I get it now-you are using Holder's inequality: $\int |f_n-f| |Jf|\le \|f_n-f\|_{L^2} \|Jf\|_{L^2} \to 0$.
Comment: @AsafShachar: I was thinking $f$ was $C^1.$ I have added a link to a fact about product convergence that works without any assumption on $f.$ That Holder's inequality argument seems to need to assume $Jf$ is in $L^2.$
Comment: I wanted to thank you again for your great answer. I forgot to mention that I posted a cross-post on mathoverflow here: https://mathoverflow.net/questions/370461/is-sobolev-limit-of-bijective-maps-surjective . I think you can just copy your answer here to there, and I will accept it there as well.


Can you insert a line break in text when using d3.js?

Question: I'm looking for a way to use a line break within a tooltip text element using d3.js.
<code>.text("test" +  "</br>" + "test")
</code>
The above, and other similar efforts, don't seem to work.
There's a thread here that seems to answer it:
https://groups.google.com/forum/?fromgroups=#!topic/d3-js/GgFTf24ltjc
but the solution isn't very clear.  How would .html be used in the above situation?
.text(.html("test" +  "" + "test"))
didn't work?
Thanks
Comment: What worked for me was to use .html (instead of .text, or .text(.html...):  .on('mouseover', function(d) {
      return (
        tooltip
          .html(
              d.country +
              ' - population ' +
              d.population...
Comment: Consider the solution I gave the link in the comment to the answer below.
Comment: The solution is different if you talk about a  element in an svg figure, or about any other text block (, , ..) outside svg. The accepted solution is for the later, see Sergei Basharov's link for the former.
Comment: [This](http://stackoverflow.com/a/16701952/837229) answer had what I was looking for.
Answer: Since you already know where you want to  break the text, you could consider just adding separate elements.
<code>.append("text")
  .attr("dy", "0em")
  .text("line 1")   // "line 1" or whatever value you want to add here.
</code>
And then for the second line, just add an offset
<code>.append("text")
  .attr("dy", "1em") // you can vary how far apart it shows up
  .text("line 2")   // "line 2" or whatever value you want to add here.
</code>
Comment: Can you provide any successful example? I just follow your way and can't make any expected results.
Comment: In my condition, only line 1 can be shown, and others are disappeared
Answer: Better to use 'tspan' for line 1 and line 2 both with attribure dy = 0em and dy = 1.2em


Sum of an irreducible representation.

Question: I am trying to prove the following statement:

Let $\mathfrak{X}$ be an irreducible $F$-representation of $G$ over an arbitrary field. Show that $\sum\limits_{g\in G}\mathfrak{X}(g) = 0$ unless $\mathfrak{X}$ is the principal representation.

I know that there are many different proofs of this fact, but I wanted to prove this statement on my own, and I have not yet seen a proof similar to mine (although I may be wrong). But is this proof correct?
Unfortunately, as it has already turned out, this proof doesn't work for an arbitrary field, but it is probably true for a field with characteristic $0$!!!
Proof:
Let $\mathfrak{X}$ be the principal representation, then by definition $\forall g\in G\Rightarrow \mathfrak{X}(g) = 1_{F}$. Then $$\sum\limits_{g\in G}\mathfrak{X}(g) = \sum\limits_{g\in G}1_{F} =|G|\cdot 1_{F}$$
Now let $\mathfrak{X}$ not be the principal representation. Let $T = \sum\limits_{g\in G}\mathfrak{X}(g)$. Note that $\forall a \in G$
$$\mathfrak{X}(a)T = \mathfrak{X}(a)\sum\limits_{g\in G}\mathfrak{X}(g) = \sum\limits_{g\in G}\mathfrak{X}(ag) = T.$$
Then it follows that $T^2 = |G|\cdot T$. Then the polynomial $x^2 -|G|x$ is annulling for $T$. Then the Jordan form of $T$ (up to permutations of Jordan cells) can take the following forms:
Either $|G|\cdot I$ ; or zero matrix; or a matrix with several units diagonally (not completely filling it), and the rest of all values are zero, and multiplied by $|G|$. Note that only the zero matrix among all these types of matrices has a trace equal to zero!
Let $\chi$ be the character associated with $\mathfrak{X}$. Consider the following expression $$S = \sum\limits_{g\in G}\chi(g) = [\chi, 1_G] = 0.$$
The last equality holds because $\chi\in Irr(G)$ and $\chi \neq 1_G$.
Since $\chi(g) = tr(\mathfrak{X}(g))$ and $tr(A + B) = tr(A) + tr(B)$ for any matrices $A$ and $B$, we get that $S = tr(T) = 0$. But only the zero matrix among the possible candidates for the role of $T$ had a zero trace. So $T = 0$, which was required to be proved. $\blacksquare$
Comment: If $F$ is an arbitrary field, then it may have nonzero characteristic. How would you be sure that the zero matrix is the only matrix having a trace of zero in that case?
Comment: Yes, I really jumped to conclusions. In this case, my reasoning is not entirely correct.
Comment: I have a module-theoretic proof that I cooked up if you'd like to see that.
Comment: I know one proof that exactly works for absolutely any field. It would be interesting to see how you proved this statement.
Answer: I think the module-theoretic approach works nicely here. Let $V$ be the corresponding $F[G]$-module to this representation. If you are reading Isaacs' book, then this equivalence between $F$-representations and $F[G]$-modules is explained in the first chapter. We have that the set
$$
I := \{ \lambda \cdot \sum_{g \in G} g \; | \; \lambda \in F \}
$$
is a subalgebra of the group algebra $F[G]$ (routine to verify). Now, since $\mathfrak{X}$ is irreducible, we have that $VI$ is either $0$ or all of $V$. We see that $VI = 0$ implies that right multiplication by $\sum_{g \in G} g$ is the zero linear transformation, and the matrix of this linear transformation is zero, that is, $\sum_{g \in G} \mathfrak{X}(g) = 0$. Otherwise, $VI = V$, and it follows that right multiplication by any $g \in G$ on $V$ is the identity transformation, so when $VI = V$, the representation is the principal representation.
Comment: Yes, my other proof is pretty similar to yours!

Sum of an irreducible representation.


How to align the labels to the middle / center in a donut chart

Question: I'm using geom_textpath to add labels to a double donut chart but the labels are not aligned to the middle.
How can I align the labels in the middle or the center of each segment?
library(magrittr)
library(ggplot2)
library(geomtextpath)
pie_data <- data.frame(category=c('A','B','C','A','B','C'),
                       year=c(2020,2020,2020,2021,2021,2021),
                       sales=c(40,30,20,10,15,10))

pie_data %>% ggplot(aes(x=year,y=sales,fill=category))+
  geom_col(position='fill',width=1,color='white')+
 lims(x=c(2018,2023))+
  geom_textpath(position='fill',angle=90,hjust=2,alpha=1,
                aes(color=factor(year),
                    label=paste0(category,':',sales)))+
 coord_polar(theta = 'y')+

  theme_void()

Answer: To position the labels when using position="fill" it's good to know that position_fill has a argument vjust to position the labels in the middle of the bars using vjust = .5:
library(magrittr)
library(ggplot2)
library(geomtextpath)

pie_data <- data.frame(
  category = c("A", "B", "C", "A", "B", "C"),
  year = c(2020, 2020, 2020, 2021, 2021, 2021),
  sales = c(40, 30, 20, 10, 15, 10)
)

pie_data %>% ggplot(aes(x = year, y = sales, fill = category)) +
  geom_col(position = "fill", width = 1, color = "white") +
  lims(x = c(2018, 2023)) +
  geom_textpath(
    position = position_fill(vjust = .5), angle = 90, alpha = 1,
    aes(
      color = factor(year),
      label = paste0(category, ":", sales)
    )
  ) +
  coord_polar(theta = "y") +
  theme_void()


Bringing infinite limit inside integral

Question: I want to find $$\lim_{R \to \infty} \int_{0}^{\pi} e^{-R\sin (t)}dt.$$ Since $\sin(t)$ is nonnegative on $[0,\pi]$ the integrand vanishes as $R \rightarrow \infty$. So I want to bring the limit under the integral to conclude that the limit is zero, but I'm not sure if it's justified here. I'm not particularly well-versed in this kind of problem so I would appreciate any relevant results/theorems that would help here too. Thanks!
Comment: Maybe here: https://math.stackexchange.com/questions/614941/continuity-of-parameter-dependent-integral-source-needed
Comment: Are you familiar with the Lebesgue dominated convergence theorem?  That could be useful here.
Comment: @JordanGreen I am not. This integral came up in a course in complex analysis I am taking.
Answer: As mentioned in the comments, the dominated convergence theorem is probably the fastest way to justify the interchange of limit and integral. In this particular case that is not necessary, however, as there is an easier method:
You can use the inequality $\sin(x) \geq \frac{2}{\pi} x $ for  $x \in [0,\pi/2]$ (which holds since the sine function is concave on this interval) to find
$$ \int \limits_0^\pi \mathrm{e}^{-R \sin(x)} \, \mathrm{d} x = 2 \int \limits_0^{\pi/2} \mathrm{e}^{-R \sin(x)} \, \mathrm{d} x \leq 2 \int \limits_0^{\pi/2} \mathrm{e}^{-R \frac{2}{\pi} x} \, \mathrm{d} x \, .$$
The latter integral can be computed explicitly and will lead to the desired limit.
Comment: I wouldn't have thought to write the integral over $[0, \pi]$ as twice the integral over $[0, \pi/2]$.  This was very clever.
Answer: Here is an elementary solution that does not involve the dominated convergence theorem but instead uses the fact if $f_n \to f$ uniformly on $[a,b]$, then
$\int_{a}^{b} f_n \to \int_{a}^{b} f$.
To show that
$$
\lim_{R \to \infty} \int_{0}^{\pi} e^{-R \sin(t)} \, dt = 0,
$$
we will show that for all $\varepsilon > 0$, there exists $R_0$ so that if $R \geq R_0$, then
$$
\int_{0}^{\pi} e^{-R \sin(t)} \, dt  \leq \varepsilon.
$$
Note: the family of functions $\{ e^{-R \sin(t)} \}_{R > 0}$ converges uniformly to $0$ on the interval $[\varepsilon/4, \pi - \varepsilon/4]$, so
$$
\lim_{R \to \infty} \int_{\varepsilon/4}^{\pi - \varepsilon/4} e^{-R \sin(t)} \,dt = 0.
$$
That is, there is some $R_0$ so that if $R \geq R_0$, then
$$
\int_{\varepsilon/4}^{\pi - \varepsilon/4} e^{-R \sin(t)} \, dt  \leq \frac{\varepsilon}{2}.
$$
For $R \geq R_0$, we have
$$
\int_{0}^{\pi} e^{-R \sin(t)} \, dt = \int_0^{\varepsilon/4} e^{-R \sin(t)} \, dt
+ \int_{\varepsilon/4}^{\pi - \varepsilon/4} e^{-R \sin(t)} \, dt + \int_{\pi -\varepsilon/4}^{\pi} e^{-R \sin(t)} \, dt  \leq \int_0^{\varepsilon/4} 1 \, dt + \frac{\varepsilon}{2} + \int_{\pi -\varepsilon/4}^{\pi} e^{-R \sin(t)} \, dt= \varepsilon.
$$
(Here, we are using $1$ as an upper bound for the integrand on the intervals $[0, \varepsilon/4]$ and  $[\pi - \varepsilon/4, \pi]$.)
Comment: Technically, it's a bit off; the uniform convergence doesn't work if we extend that interval all the way to $\pi$.
Comment: Ah, you're right.  I've edited.
Answer: To find this limit directly, we divide and conquer with a multi-part estimate; we split the interval into a narrow piece where the integral is small because the interval is small, and a wide piece where the integral is small because the function is small.
First off, I'd rather not deal with both endpoints where $\sin$ is zero, so let's fold it over with symmetry:
$$I(R) = \int_0^{\pi} e^{-R\sin t}\,dt = 2\int_0^{\pi/2}e^{-R\sin t}\,dt$$
Now, we'll split that $\int_0^{\pi/2}$ into $\int_0^{\epsilon/4}+\int_{\epsilon/4}^{\pi/2}$:
\begin{align*}I(R) &= 2\int_0^{\epsilon/4}e^{-R\sin t}\,dt+2\int_{\epsilon/4}^{\pi/2}e^{-R\sin t}\,dt\\
I(R) &\le 2\int_0^{\epsilon/4}1\,dt + 2\int_{\epsilon/4}^{\pi/2}\exp\left(-R\sin \frac{\epsilon}{4}\right)\,dt = \frac{\epsilon}{2}+\left(\pi-\frac{\epsilon}{2}\right)\exp\left(-R\sin \frac{\epsilon}{4}\right)\end{align*}
In both cases, we estimated the function by simply saying that it's less than the largest value on that subinterval.
So now, we need to estimate that exponential term. We have $\sin\frac{\epsilon}{4}\approx \frac{\epsilon}{4}$ - but if we turn that into an inequality, it's a $<$, and that points in the wrong direction for what we need. So instead, estimate $\sin$ by the secant line: $\sin x \ge \frac{2}{\pi}x$ for $0\le x\le \frac{\pi}{2}$. This leads to $\exp\left(-R\sin \frac{\epsilon}{4}\right)\le \exp\left(-R\cdot\frac{2}{\pi}\cdot\frac{\epsilon}{4}\right)$. Then of course $\pi-\frac{\epsilon}{2}\le \pi$, and we can make this term less than $\frac{\epsilon}{2}$ simply by choosing $R$ large enough. For $R\ge \frac{2\pi}{\epsilon}\ln(2\pi)$,
$$I(R) \le 2\int_0^{\epsilon/4}1\,dt + 2\int_{\epsilon/4}^{\pi/2}\exp\left(-R\sin \frac{\epsilon}{4}\right)\,dt \le \frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon$$
As $\epsilon>0$ was arbitrary, that's the definition of convergence to zero, and we're done.
The dominated convergence theorem is of course the easy way; we just use the pointwise convergence to $0$ on the interior (and $1$ at the endpoints) and the fact that all of the functions are less than the integrable function $1$. Then again, this style of argument is worth knowing - it's how we prove the dominated convergence theorem, after all. Running through a few examples like this isn't a bad idea.
Why $\frac{\epsilon}{4}$? Well, you'll probably start out by writing $\epsilon$ - and then when you get an estimate of $4\epsilon$ for the whole thing, go back and divide them all by $4$. The final form of the argument doesn't have to match the scratch version.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\lim_{R \to \infty}\int_{0}^{\pi}\expo{-R\sin\pars{t}}\,\dd t & =
\lim_{R \to \infty}\int_{-\pi/2}^{\pi/2}\expo{-R\cos\pars{t}}\,\dd t =
2\lim_{R \to \infty}\int_{0}^{\pi/2}\expo{-R\cos\pars{t}}\,\dd t
\\[5mm] & =
2\lim_{R \to \infty}\int_{0}^{\pi/2}\expo{-R\sin\pars{t}}\,\dd t
\\[5mm] & =
2\lim_{R \to \infty}\int_{0}^{\infty}\expo{-Rt}\,\dd t
\qquad\pars{~Laplace's\ Method~}
\\[5mm] & =
2\lim_{R \to \infty}{1 \over R} = \bbx{0}
\end{align}

Laplace's Method.

Indeed,
$$
\int_{0}^{\pi}\expo{-R\sin\pars{t}}\,\dd t =
{1 \over 2}\,\pi\bracks{\mrm{I}_{0}\pars{R} - \mrm{L}_{0}\pars{R}}
$$

where $\ds{\mrm{I}_{\nu}}$ and $\ds{\mrm{L}_{\nu}}$ are Bessel and Struve Functions, respectively.

Bringing infinite limit inside integral


How do I get a license tag in Nuget gallery?

Question: Looking at e.g. the jQuery Nuget Package there is a "license details" panel at the bottom of the left column, saying that jQuery is licensed under an MIT license.
How do I get such a "license details" for my own project that is licensed under LGPL?
The license link of my nuget package points to the LICENSE file in the GitHub repo of the project. From what I've been able to find out the "license details" is somehow automatically derived from the linked license file, but it doesn't work for me :-(
Comment: I was going to suggest you try linking to the raw license text instead of the github page but the license details works for the older 0.1 version of your NuGet package which has the same link.
Comment: Thanks for noticing, I hadn't seen that the previous version had the correct tag. Might be worth linking to the raw license file though if it makes detection easier. Will try with next version.
Answer: Its bit late for the answer, yet it might help some else.
On nuget site there is guide how to create a nuget package
https://docs.nuget.org/ndocs/create-packages/creating-a-package
This site does have example of .nuspec file, where you can specify link to the license you wish to have your project under.
To choose appropriate license, have a look here:
http://choosealicense.com/


Get the first value of a column for a group, and the last value of a different column using SQL

Question: apt   week     startday       endday
10    1        07.03.2023     07.07.2023
10    2        07.10.2023     07.15.2023
10    3        07.17.2023     07.22.2023
10    4        07.24.2023     07.25.2023
15    3        05.05.2023     05.10.2023
15    4        05.12.2023     05.18.2023
25    1        09.12.2023     09.15.2023
25    2        09.17.2023     09.19.2023

i am trying to accomplish in here same apt first week and last weeks combine start day and endday values in one column. so the result should be like this
   apt       startday      endday
    10       07.03.2023    07.25.2023
    15       05.05.2023    05.18.2023
    25       09.12.2023    09.19.2023

Comment: https://meta.stackoverflow.com/questions/388759/why-should-i-tag-my-rdbms
Answer: It looks to me like you can just use min() and max() functions like this:
select apt
     , min(startday)
     , max(endday)
 group by apt;

But you should specify which RDBMS you're using.


Is there a postcode for deliveries checker module for drupal 7?

Question: I'm thinking about using Drupal for a take away (delivery) ecommerce site and was wondering if there is a module that could calculate the the distance between the postcode added by the user and the shop locations (a few) and if its within a certain radius go ahead and allow the user to place the order. Is there such module available for drupal? if not, is there a similar module(s) that could be adapted to it?
Thanks
Answer: There's no single module for this, but you can use a suite of modules.  For example, you can take addresses stored in the Address Field module and then use Geocoder to geocode them and save the results in a Geofield.  You can then use Rules to check the distance.
That said, there is no simple way to do this.  In fact, there's an entire book about Mapping with Drupal.
Comment: Would you say that'd be reasonable to do with drupal or should I look for a different solution? Would the end result be good (as in robust)? Thanks for your help.
Comment: @WagnerMatosUK That's impossible to say without knowing the details of your situation, but it's certainly not going to be a point and click solution.  It will probably require some custom PHP glue code and you will also probably have a few obscure bugs that you will have to hunt down patches for (just speaking roughly from experience).  That said, it's much easier than writing the whole tool yourself.
Answer: There is a Commerce Postal Code Filter module

Postal code (US ZIP codes, UK postcodes etc) filtering functionality for the Drupal Commerce checkout process. This module provides 2 main modes (whitelisting and blacklisting) which allow shop owners to restrict the areas of a country that they deliver to:


Server is not accepting connection from Client side to read data from a file

Question: I want to read a file on Server from the Client application on Linux. I have mentioned below my Server and Client application.
On Client side I open a file (which is necessary to my requirements).
The Client receive the data which I have written on the file. Now, I want to send the received data from Client to the Server side and get back the echo to the Client.
I am facing trouble with the Server to accept the Client connection. I am glad to have a solution, where I made mistake exactly. I also appreciate If I get the solution for the code. Thanks in advance.
Server.C

#include<stdio.h>

#define BufferLength 100

/* Server port number */
#define SERVPORT 3389

int main(int argc, char *argv[])
{

/* Variable and structure definitions. */
int sd, sd2, rc, length = sizeof(int);
int totalcnt = 0, on = 1;
char temp;
char buffer[BufferLength];
//char data[BufferLength];
struct sockaddr_in serveraddr;
struct sockaddr_in their_addr;

fd_set read_fd;
struct timeval timeout;
timeout.tv_sec = 15;
timeout.tv_usec = 0;

/*To read xillybus*/
//  FILE *fp;
//  fp = fopen("/dev/xillybus_read_8", "r");
//  if(fp==NULL)
//  {
//      printf("Error file open\n");
//      exit(-1);
//  }
//  else{
//      printf("File found %s\n", fp);
//  }

/* Get a socket descriptor */

if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
    perror("Server-socket() error");
    exit (-1);
}
else
{
    printf("Server-socket() is OK\n");
}

/* Allow socket descriptor to be reusable */

if((rc = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) < 0)
{
    perror("Server-setsockopt() error");
    close(sd);
    exit (-1);
}
else
{
    printf("Server-setsockopt() is OK\n");
}

/* bind to an address */
memset(&serveraddr, 0x00, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(SERVPORT);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
printf("Using %s, listening at %d\n", inet_ntoa(serveraddr.sin_addr), SERVPORT);

if((rc = bind(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)
{
    perror("Server-bind() error");
    close(sd);
    exit(-1);
}

else
{
    printf("Server-bind() is OK\n");
}

/* Up to 10 clients can be queued */

if((rc = listen(sd, 10)) < 0)
{
    perror("Server-listen() error");
    close(sd);
    exit (-1);
}
else
{
    printf("Server-Ready for client connection...\n");
}

/* accept() the incoming connection request. */

int sin_size = sizeof(struct sockaddr_in);

if((sd2 = accept(sd, (struct sockaddr *)&their_addr, &sin_size)) < 0)
{

    perror("Server-accept() error");
    close(sd);
    exit (-1);
}
else
{

    printf("Server-accept() is OK\n");
}

/*client IP*/
    printf("Server-new socket, sd2 is OK...\n");
    printf("Got connection from the  client: %s\n", inet_ntoa(their_addr.sin_addr));

/* Wait for up to 15 seconds on */
/* select() for data to be read. */
FD_ZERO(&read_fd);
FD_SET(sd2, &read_fd);
rc = select(sd2+1, &read_fd, NULL, NULL, &timeout);

if((rc == 1) && (FD_ISSET(sd2, &read_fd)))
{
/* Read data from the client. */
totalcnt = 0;

while(totalcnt < BufferLength)
{

/* read() from client */
rc = read(sd2, &buffer[totalcnt], (BufferLength - totalcnt));
if(rc < 0)
{
    perror("Server-read() error");
    close(sd);
    close(sd2);
    exit (-1);
}

else if (rc == 0)
{
    printf("Client program has issued a close()\n");
    close(sd);
    close(sd2);
    exit(-1);
}

else
{
    totalcnt += rc;
    printf("Server-read() is OK\n");
}

}
}
else if (rc < 0)
{
    perror("Server-select() error");
    close(sd);
    close(sd2);
    exit(-1);
}

/* rc == 0 */
else
{
    printf("Server-select() timed out.\n");
    close(sd);
    close(sd2);
    exit(-1);
}

/* Shows the data */
    printf("Received data from the client: %s\n", buffer);
    printf("Server-Echoing back to client...\n");

/*Write function*/
rc = write(sd2, buffer, totalcnt);
if(rc != totalcnt)
{
    perror("Server-write() error");
    rc = getsockopt(sd2, SOL_SOCKET, SO_ERROR, &temp, &length);

if(rc == 0)
{
    /* Print out the asynchronously */
    /* received error. */
    errno = temp;
    perror("SO_ERROR was: ");
}
else
{
    printf("Server-write() is OK\n");
}
close(sd);
close(sd2);
exit(-1);
}

/******************************************/
close(sd2);
close(sd);
exit(0);
return 0;
}

Client.c

#include<stdio.h>

#define BufferLength 100

#define SERVER "00.00.00.00"
/* Server's port number */

#define SERVPORT 3389

/* set the server name in the #define SERVER ... */

int main(int argc, char *argv[])
{
/* Variable and structure definitions. */
int sd, rc, length = sizeof(int);
struct sockaddr_in serveraddr;
char buffer[BufferLength];
char server[255];
char temp;
int totalcnt = 0;
struct hostent *hostp;

//char data[500] = "Hello ravi !!! "; // writes data to the server

/*To open directory and read the xillybus*/

FILE *fp;
char s[100];
fp = fopen("/dev/xillybus_read_8", "r");
if(!fp)
    return 1;
while(fgets(s,100,fp)!=NULL){
    printf("%s ", s);
}
//fclose(fp);

/******************************************/
/* get a socket descriptor */

if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
    perror("Client-socket() error");
    exit(-1);
}
else
{
    printf("Client-socket() OK\n");
}
/*If the server hostname is supplied*/
if(argc > 1)
{
/*Use the supplied argument*/
    strcpy(server, argv[1]);
    printf("Connecting to the server %s, port %d ...\n", server, SERVPORT);
}
else
{
/*Use the default server name or IP*/
strcpy(server, SERVER);
memset(&serveraddr, 0x00, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(SERVPORT);
}

if((serveraddr.sin_addr.s_addr = inet_addr(server)) == (unsigned long)INADDR_NONE)
{

/* get host address */
hostp = gethostbyname(server);
if(hostp == (struct hostent *)NULL)
{
    printf("HOST NOT FOUND --> ");
/* h_errno is usually defined */
/* in netdb.h */
    printf("h_errno = %d\n",h_errno);
    printf("---This is a client program---\n");
    printf("Command usage: %s <server name or IP>\n", argv[0]);
    close(sd);
    exit(-1);
}
memcpy(&serveraddr.sin_addr, hostp->h_addr, sizeof(serveraddr.sin_addr));
}

/* connect() to server. */

if((rc = connect(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)
{
    perror("Client-connect() error");
    close(sd);
    exit(-1);
}
else
{
    printf("Connection established...\n");
    printf("Sending some string to the server %s...\n", server);
}
/* Write() some string to the server. */
//rc = write(sd, data, sizeof(data));

rc = write(sd,fp, sizeof(fp)); // here is my write function

if(rc < 0)
{
    perror("Client-write() error");
    rc = getsockopt(sd, SOL_SOCKET, SO_ERROR, &temp, &length);
if(rc == 0)
{
/* Print out the asynchronously received error. */
    errno = temp;
    perror("SO_ERROR was");
}
close(sd);
exit(-1);
}
else
{
    printf("Client-write() is OK\n");
    printf("String successfully sent \n");
    printf("Waiting the %s to echo back...\n", server);
}
totalcnt = 0;

/* Read data from the server. */
while(totalcnt < BufferLength)
{
rc = read(sd, &buffer[totalcnt], BufferLength-totalcnt); //&buffer[totalcnt],BufferLength-totalcnt
if(rc < 0)
{
    perror("Client-read() error");
    close(sd);
    exit(-1);
}
else if (rc == 0)
{
    printf("Server program has issued a close()\n");
    close(sd);
    exit(-1);
}
else
{
    totalcnt += rc;
}
}
    printf("Client-read() is OK\n");
    printf("Echoed data from the  server: %s\n", buffer); //data ->buffer

/* Close socket descriptor from client side. */
close(sd);
exit(0);
return 0;
}

Comment: I didn't look through your code in detail (bit messy and lengthy), but there are tons of examples of echo servers and clients. I suggest you study those closely... This problem has been solved a million times.
Comment: Thanks for your reply Karel Kubat. My problem is not echo. I am unable to accept and read the client connection. I am newbie in c programming. I can establish the connection between server and client when I am not using the function FILE*fp fp=fopen();... Now I want to read the file using fopen on the server. Please anysuggestion would help me a lot to solve this problem.
Comment: Has this question any relation to the topic of FPGAs? You tagged it with fpga ...
Comment: What happens instead of the server accepting the connection?
Comment: Hello EJP, server is waiting to accept the connection from the client. I have two files read and write on the client side on Linux. I run the write file using cat > /dev/xillybus_write-8,  where I can enter my data. The data should pass through the client on the server and receive the acknowledgement.
Comment: On the client side I can read the data from the write_8 file, but I am unable to establish the connection on the server to read the data and echo back. I am not sure that while loop is causing problem. Any written sample code could help me a lot.
Comment: F the server doesn't accept the connection the client must be getting an error. What is it?
Answer: In you client.c program, you try to send a FILE* to the server. What you are sending is the address of the file descriptor in client program and not the text contained in the file.
You send only 4 or 8 bytes (depending on architecture 32 or 64 bits), while server waits for at least 100 bytes before echoing anything. So both programs do exactly what you programmed - but not what you expected.
To send the content of a file, you read the file in a char array and send the char array. You can iterate over the file reading one buffer at a time and sending the buffer. But there is no magic allowing to send a whole file.
Comment: What exactly is 'dangerous' about looping until you get a complete message?
Comment: Hello Serge Ballesta, thanks for answering for my question. I am presently trying out to find out the solution.
Comment: @EJP : nothing should be dangerous, except that in current case *as peer never sends enough data* and there is no timeout or other error handling it ends in an infinite loop.
Comment: No it doesn't. It result in a blocking read, which is terminated either by arrival of data or the peer closing the connection. Every protocol-based program in the world has to keep reading until it assembles an entire request. Your remark makes no sense.
Comment: @EJP : Ok, I understand your point. The server waits for 100 characters when client only send 4 but it is a problem of bad protocol implementation. My remark was based on the fact that program was only echoing input, and as such could process data as soon as it arrives but I must acknowledge it's not what my remark means. And I can remove it from the post since it's detailed here now. Thanks for your interest.


Is there any hotkey to exit from shadow?

Question: How can I close shadow window without using mouse? Is there any hotkey? My aims is to avoid move user mouse cursor, when I've decided to exit.
In Windows 2008 R2 I was able to use Ctrl + *  or another hotkey which I choiced when entered to shadow.
Comment: Is this about RDP?
Comment: @Jonathan Yes, shadow of an user RDP ssession
Comment: Funny enough, Microsoft states `CTRL+* (numpad)` is still the way to go in Server 2016: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/shadow
Answer: I found this which should help you with your problem:
One Solution is to use the numpad if you have one:
  Ctrl+NP*

The other solution is:
Turn off windows key combination using registry to Disable Windows Key combination for mstsc.exe ( RDP )
Open Registry and go to:
  HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\DefaultUserConfiguration

  Shadow=1

Change Binary Value to:
  Shadow=0

Now windows shortcut keys will work with Winkey like to Open Explorer: "Winkey + E "
So you can now make other key combinations work as they should.
Idea found here: https://www.experts-exchange.com/questions/26622927/Change-finish-hotkey-for-command-line-shadow-of-a-terminal-or-RDP-session.html
Comment: Please expand the answer to include the information in the link. Link-only answers will get down-voted.
Comment: OK, I am new could you explain how I should format this type of information.
Comment: Hi, you can paste the solution, quote it and give the source, its a best way to do it, as link only answer can die in age, and expertexchange sometime block to see the answer when not a members too, thus not a reliable link only answer. To do so you can click edit and modify your answer
Comment: Read it, understand it, and put it in your own words.


Number of bits for a scalar product

Question: let's consider two vectors $v_1[i]$, $v_2[i]$, for $i = 0, 1, ... , N-1$.
Suppose you want to calculate the scalar product between them: it is simply the sum of all $v_1[i] * v_2[i]$ terms $(i=0,...,N-1)$.
Suppose now that each element of $v_1, v_2$ may be written as a $M$ - bits binary number. How many bits are the necessary to express the result?
Answer: For each product, the maximum result is
$$
(2^M - 1)^2 = 2^{2M} - 2^{M+1} + 1
$$
Let $q = log_2N \Leftrightarrow N = 2^q$, then the biggest number you might get from your dot product is
$$
 N(2^{2M} - 2^{M+1} + 1) = 2^{2M+q} - 2^{M+q+1} + 2^q
$$
which means you might need $2M+\mathtt{ceil}(q)$ bits

Number of bits for a scalar product


how to display image from path stored in database? in laravel

Question: am developing a site using laravel and I am trying to retrieve images stored as a path in the database but my code only gets the name of the image and the price in the views. I suspect its how i am calling the images as laravel has stored them in the storage/public folder. Please help.
Here is my code:
@section('content')

    @foreach ($products->chunk(4) as $items)

            @foreach ($items as $products)

                            slug]) }}">path) }}" alt="products" class="img-responsive">

{{ $products->name }}

{{ $products->price }}

                            slug]) }}" class="btn btn-success pull-right" role="button">add to Cart

            @endforeach

    @endforeach

Then in my controller:
if($request->hasFile('file')){
            $uploaded_file = $request->file('file');
        // this get the original extention
        $uploaded_file_ex = $uploaded_file->getClientOriginalExtension();

        // the path to store the file
        // I add the time at the begining to avoid overwritting the file if another file has the same name.
        $filename = time().'.'.$uploaded_file_ex;
        $path = $uploaded_file->storeAs('public', $filename);

Comment: Please show your code
Comment: @Chalo Your images in public folder directly? If your images is not having fix path then you can also send $path in view from controller.
Comment: Yes they are. what do you mean by sending the $path in view
Comment: $path you can use if you are sending dynamic path for every image
Comment: but if you are storing all images in public folder only and have fix path then no need
Comment: But don't give public in asset. Give like {{ asset($products->path) }}
Comment: But make sure $products->path contains the complete path of your image.
Answer: You need to use images or some other folder where you will store your images in place of public directly. Even if you want to store your images in public folder then no need to give public in asset. It will pick from public folder by default and if you are using dynamic path for images then you must send $path from your controller method to view.
Below code will help you if you are directly getting images from public folder.

@foreach ($products->chunk(4) as $items)

        @foreach ($items as $products)

                        slug]) }}">path) }}" alt="products" class="img-
responsive">

{{ $products->name }}

{{ $products->price
}}

                        slug]) }}"
class="btn btn-success pull-right" role="button">add to Cart

        @endforeach

@endforeach

Upload Image Script that you need to add in your controller method where you are receiving your data from form :-
// Upload Image Script
if($request->hasFile('image')){
    if (Input::file('image')->isValid()) {
         $file = Input::file('image');
         $destination = 'img/';
         $extension = Input::file('image')->getClientOriginalExtension();
         $fileName = rand(111,99999).'.'.$extension;
         $file->move($destination, $fileName);
     }
 }

Comment: oh, I get could you please help me with how i send $path from my controller to view am kinda lost there
Comment: First tell me what are you getting in $products->path that you are using in asset to get image?
Comment: the images that i have uploaded, the path is stored in the db but the image is stored in the storage folder,, I am getting the images from public/img folder
Comment: if images are in public/img folder then update like src="{{ asset('img/' . $products->path) }}"
Comment: That is where i am retrieving from then storing them in the storage folder via the path in the database
Comment: I can't able to get your point. Your image is located in storage folder or public folder?
Comment: okay i have images in my public folder then when i insert the image it is stored in the storage folder under the folder i have specified in my code..
Comment: Means you want to store your images at storage folder?
Comment: you know storage path is directly unavailable for public?
Comment: You must use storage folder for images if you want to keep them much secure otherwise no need for normal usage. Because it's bit tricky to get images from storage folder for showing in view.
Comment: oh so how should my insert image look like to store it in the public folder??
Comment: Yes we can add images in public folder. do I attach its code in my answer?
Comment: We simply need to add in some folder like img that you have created in public folder and show it in view very easily.
Comment: Add me at FB https://www.facebook.com/amitg100 I will try my best to sort out your issue.
Comment: I have added upload image script that will work in your Laravel project
Comment: images will get uploaded in img folder that you have to create in public folder.


Expressing variables in terms of each other re: implicit function theorem

Question: The following was given as a question on a practice midterm for my introductory vector analysis class: True or False? If $f: \mathbb{R^3} \rightarrow \mathbb{R}$ is any function that is continuously differentiable and $D_2f(a, b, c) \neq 0$ and $D_3f(a, b, c) \neq 0$, then there is a function $h$ of $(y, z)$ defined near $(b, c)$ such that $f(h(y, z), y, z)) = 0$.
I'm thinking since $D_2f(a, b, c) \neq 0$ and $D_3f(a, b, c) \neq 0$, it is possible to express $a$ in terms of $b$ and $c$ (i.e. the function $h(y, z)$ defined near $(b, c)$ exists), but I don't know how to formalize that, nor do I know how to show that $f(h(y, z), y, z)) = 0$ using the text of the IFT itself.
Answer: Upon review, it turns out that this is in fact false. The function $f(a, b, c) = b + c$ is clearly $C^1$ with $D_2f(a, b, c) = 1 \neq 0$ and $D_3f(a, b, c) = 1 \neq 0$, but $D_1f(a, b, c) = 0$, so the Implicit Function Theorem does not guarantee an implicit function defining $a$ in terms of $b, c$ because $0$ is not invertible. Furthermore, $b + c$ does not vanish identically in any neighborhood of $\vec{0}$, so the implicit function actually does not exist.


componentWillMount is deprecated and will be removed in the next major version 0.54.0 in React Native

Question: I use the react native latest version of 0.54.0 and Whenever run the apps on iOS there is found warning about deprecate the lifecycle methods. and also please update the components.
Warning :
componentWillMount is deprecated and will be removed in the next major version. Use componentDidMount instead. As a temporary workaround, you can rename to UNSAFE_componentWillMount.
Please update the following components: Container, Text, TouchableOpacity, Transitioner, View
I Have also change according to the waring add prefix UNSAFE_ each of the method.
UNSAFE_componentDidMount() {
}
UNSAFE_componentWillMount() {
}
UNSAFE_componentWillUpdate(nextProps, nextState) {
}
UNSAFE_componentWillReceiveProps(nextProps) {
}

Although the warning continue. Please help me.
Currently I have hide the YellowBox waring in my Apps.
import { YellowBox } from 'react-native';

render() {

  YellowBox.ignoreWarnings([
    'Warning: componentWillMount is deprecated',
    'Warning: componentWillReceiveProps is deprecated',
  ]);
}

Comment: I use `componentWillMount` in my SSR web app as well... there seems to be discussions about adding in a `componentWillServerRender` (will prob be named something else)
https://github.com/reactjs/rfcs/pull/8/files/fe1c7bf56d792328a4c554fc51f80bc3503b995b#diff-6aaaf484b3a1d656cf6d95ee5dfbfd97

So one alternative might be to hold off with upgrading until the dust has settled then swapping over to the new hooks? (If they get added... if not. panic again I guess)
Answer: You should move all the code from the componentWillMount to the constructor or componentDidMount.

componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor() instead.
  Avoid introducing any side-effects or subscriptions in this method. For those use cases, use componentDidMount() instead.
  This is the only lifecycle hook called on server rendering.
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
  This method is a good place to set up any subscriptions. If you do that, don't forget to unsubscribe in componentWillUnmount().
  Calling setState() in this method will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won't see the intermediate state. Use this pattern with caution because it often causes performance issues. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.

From the official docs
Comment: `constructor(props) {super(props); this.state = { tabindex:0 }}`
Comment: I don't have any epxlicit place with `componentWillMount`, but I do have in my `app.js` a line of code after the constructor with `state={ tabindex:0 }`  How do I "move" that into the constructor?
Answer: componentDidMount isn't deprecated and is definitely still safe to use, so there's no need to add UNSAFE_ to that method. The componentWillSomething methods are the ones that seem to be on their way out. Instead of componentWillMount, use a constructor for the stuff that doesn't produce side-effects, and use componentDidMount for the stuff that does.
Answer: You should avoid using componentWillSomething in order to use constructor or componentDidMount
However, You have to be very carefully which one you'll use. A typical scenario is when you want to display a loading (using states) immediately after you open a screen
this.setState({ isLoading: true });
...
this.setState({ isLoading: false});

In this kind of case you have to use componentDidMount in order to set states. This is what React said about constructors

Typically, in React constructors are only used for two purposes:

Initializing local state by assigning an object to this.state.

Binding event handler methods to an instance.

You should not call setState() in the constructor(). Instead, if your component needs to use localstate, assign the initial state to this.state directly in the constructor.

Good coding!


Docbook 5 XSLT: Query and return value of "edition" element failing

Question: I'm using docbook5 with oxygen xml editor. I'm going to PDF via XSLTproc and FOP. I am trying to get the value of the"edition" tag to show up in the footer, but this is not working correctly.
Given the docbook 5 source of:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book
<book version="5.0" xmlns="http://docbook.org/ns/docbook"
   xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude"
   xmlns:svg="http://www.w3.org/2000/svg" xmlns:m="http://www.w3.org/1998/Math/MathML"
   xmlns:html="http://www.w3.org/1999/xhtml" xmlns:db="http://docbook.org/ns/docbook">
      <info>
        <title>User Manual</title>
        <edition>Ed. 123456</edition>
      </info>
</book>

And the footer template of:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fo="http://www.w3.org/1999/XSL/Format" version="1.0">

<xsl:template name="footer.content">
  <xsl:param name="pageclass" select="''"/>
  <xsl:param name="sequence" select="''"/>
  <xsl:param name="position" select="''"/>
  <xsl:param name="gentext-key" select="''"/>

  <fo:block>

    <xsl:choose>

      <xsl:when test="$sequence = 'odd' and $position = 'left'">
        <fo:retrieve-marker retrieve-class-name="section.head.marker"
                        retrieve-position="first-including-carryover"
                        retrieve-boundary="page-sequence"/>
      </xsl:when>

      <xsl:when test="$sequence = 'odd' and $position = 'center'">
         <xsl:value-of select="ancestor-or-self::book/info/edition"/>
      </xsl:when>

    </xsl:choose>
  </fo:block>
</xsl:template>
</xsl:stylesheet>

The value returns properly when I query from the oxygenxml xquery section in the toolbar, but not when I process the document to PDF. Any help would be super!
Answer: You have to take the DocBook namespace into account. By convention, the namespace URI is mapped to the d prefix in the stylesheets. Do this in your customization file:

Add
xmlns:d="http://docbook.org/ns/docbook"
exclude-result-prefixes="d"

to the root <xsl:stylesheet> element.
Change
<xsl:value-of select="ancestor-or-self::book/info/edition"/>

to
<xsl:value-of select="ancestor-or-self::d:book/d:info/d:edition"/>


virtual box version 5.0.4 Failed to create the VirtualBoxClient COM object.

Question: i installed genymotion version 2.5.4 package with virtual box version 5.0.4. However the virtual box could not function. It comes out with error.
Failed to create the VirtualBoxClient COM object.
The application will now terminate.
Callee RC: REGDB_E_CLASSNOTREG (0x80040154)
I have tried to reinstall but not luck. Here the log file of virtual box.
<code>VirtualBox COM Server 5.0.4 r102546 win.amd64 (Sep  8 2015 10:46:49) release log
00:00:00.006000 main     Log opened 2015-11-18T13:46:28.173803900Z
00:00:00.006000 main     Build Type: release
00:00:00.006000 main     OS Product: Windows 7
00:00:00.006000 main     OS Release: 6.1.7600
00:00:00.006000 main     OS Service Pack:
00:00:00.037002 main     DMI Product Name: Inspiron N5110
00:00:00.049002 main     DMI Product Version: Not Specified
00:00:00.049002 main     Host RAM: 4003MB total, 1741MB available
00:00:00.049002 main     Executable: C:\Program Files\Oracle\VirtualBox\VBoxSVC.exe
00:00:00.049002 main     Process ID: 6520
00:00:00.049002 main     Package type: WINDOWS_64BITS_GENERIC
00:00:00.052002          Home directory: 'C:\Users\User 20-01-2014/.VirtualBox'
00:00:00.206011          usbLibDevCfgDrGet: DeviceIoControl 1 fail winEr (31)
00:00:00.213012          USB: Unknown USB device detected (idVendor: 0x0000, idProduct: 0x0000). Please, report the idVendor and idProduct to virtualbox.org.
00:00:00.213012          USB: Unknown USB device detected (idVendor: 0x0000, idProduct: 0x0000). Please, report the idVendor and idProduct to virtualbox.org.
00:00:00.253014          Skipped non-Ethernet 'Loopback Pseudo-Interface 1'
00:00:00.253014          Skipped non-Ethernet 'Local Area Connection* 11'
00:00:00.253014          Skipped non-Ethernet 'isatap.{DA53AD29-3A42-4681-8970-EA104A7A59EA}'
00:00:00.253014          Skipped non-Ethernet '6TO4 Adapter'
00:00:00.253014          Skipped non-Ethernet 'isatap.{13F37373-5B94-4591-849E-4C2F0CFEC644}'
00:00:00.253014          Skipped non-Ethernet 'isatap.{A0FA46F7-BBD1-4D4F-A153-582E4A9FF470}'
00:00:00.253014          Skipped non-Ethernet 'isatap.{3B262A5D-979C-43CC-BBE9-85F6D3B5FF05}'
00:00:00.253014          Skipped non-Ethernet 'isatap.{1CD1246A-DE08-41B3-B52E-9EE9EA1F8C27}'
00:00:00.275015          HostDnsMonitor: old information
00:00:00.275015            no server entries
00:00:00.275015            no search string entries
00:00:00.275015            no domain set
00:00:00.275015          HostDnsMonitor: new information
00:00:00.275015            server 1: 192.168.43.1
00:00:00.275015            no search string entries
00:00:00.275015            no domain set
00:00:00.275015          HostDnsMonitorProxy::notify
00:00:00.724041          VD: VDInit finished
00:00:05.768329 Watcher  ERROR [COM]: aRC=E_ACCESSDENIED (0x80070005) aIID={0169423f-46b4-cde9-91af-1e9d5b6cd945} aComponent={VirtualBoxWrap} aText={The object is not ready}, preserve=false aResultDetail=0
</code>
Answer: in VBoxSVC.log you have error like this:
Watcher  ERROR [COM]: aRC=E_ACCESSDENIED (0x80070005) aIID={0169423f-46b4-cde9-91af-1e9d5b6cd945} aComponent={VirtualBoxWrap} aText={The object is not ready}, preserve=false aResultDetail=0
you have a key: {0169423f-46b4-cde9-91af-1e9d5b6cd945} and you dont have a permission to that key
use registry editor and set "Full control" for Administrators to that key and subkeys in it
sorry for my english :) I dont use it to often
sg
Answer:

Open registory editor (open RUN -> type regedit) then find for given key (key - aIID={0169423f-46b4-cde9-91af-1e9d5b6cd945})
  change
  its permission and restart machine.

If above won't work then make sure that you don't have VMWare-horixon-client installed in your system. For my System this
  was
  the problem and after that its working fine.


How to prove that $\phi:G\rightarrow \pi_1(X/G,p(x_0))$ is a homomorphism of groups?

Question: Let $G$ be a discontinuous group (this means that it acts discontinuously with finite stabilizers) of homeomorphisms of a simply connected, locally compact metric space $X$. Let $p:X\rightarrow X/G$ be the orbit map. Choose a base point $x_0\in X$ and let $\pi_1(X/G,p(x_0))$ be the fundamental group of $X/G$.
Define $\phi:G\rightarrow \pi_1(X/G,p(x_0))$ as follows - for any $g\in G$ let $\alpha$ be a path from $x_0$ to $g(x_0)$. Send $g$ to the homotopy class of loops $p\circ\alpha$, that is $\langle p\circ\alpha\rangle$. This map is independent of the choice of path as $X$ is simply connected.

I am having trouble proving that it is a group homomorphism.

If $g_1,g_2\in G$ then let $\gamma_1$ be a path from $x_0$ to $g_1(x_0)$ and $\gamma_2$ be a path from $x_0$ to $g_2(x_0)$ then $\gamma_1*g_1\circ\gamma_2$ is a path from $x_0$ to $g_1\circ g_2(x_0)$. So ,$$\phi(g_1\circ g_2)=\langle p \circ (\gamma_1*g_1\circ\gamma_2)\rangle=\langle (p \circ \gamma_1)*(p\circ g_1\circ\gamma_2)\rangle$$
But I am not sure where to go from here. The next step should be to say this is equal to  $ \langle p\circ\gamma_1\rangle\langle p\circ\gamma_2\rangle$. Now obviously $g_1\circ\gamma_2$ is homotopic to $\gamma_2$ and both project to loops based at $p(x_0)$. I know that these loops are homotopic in $X/G$  however why are they path homotopic?
Thanks!
Answer: They are not only path homotopic, they are the same curve as $p\circ g_1 = p$ by definition of $X/G$. So
$$p\circ g_1\circ\gamma_2 = p\circ\gamma_2 = \phi(g_2).$$


Flink RMQSource

Question: I want to test RMQSource class for receiving data from RabbitMQ, but i don´t know how to config the Rabbit virtual host for my exchange, and i think is the problem i have. My code:
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.streaming.connectors.rabbitmq.RMQSource
import org.apache.flink.streaming.util.serialization.SimpleStringSchema

object rabbitjob {
  val env = StreamExecutionEnvironment.getExecutionEnvironment
  val stream = env.addSource(new RMQSource[String]("192.168.1.11", 5672,"user","pass", "inbound.input.data",false, new SimpleStringSchema())).print

def main (args:Array[String]){
    env.execute("Test Rabbit")
 }
}

Error in IntelliJ IDE:
Error:(10, 29) could not find implicit value for evidence parameter of type org.apache.flink.api.common.typeinfo.TypeInformation[String]
  val stream = env.addSource(new RMQSource[String]("192.168.1.11", 5672,"user","pass", "inbound.input.data",false, new SimpleStringSchema())).print
^
Error:(10, 29) not enough arguments for method addSource: (implicit evidence$7: org.apache.flink.api.common.typeinfo.TypeInformation[String])org.apache.flink.streaming.api.scala.DataStream[String].
Unspecified value parameter evidence$7.
  val stream = env.addSource(new RMQSource[String]("192.168.1.11", 5672,"user","pass", "inbound.input.data",false, new SimpleStringSchema())).print
^
Any idea how to solve it or alternatives??
Thank you in advance.
Comment: Not exactly clear what you are asking. Do you want to create the vhost and exchange? Or do you already have that and want to pass it in the code? Or something third?
Comment: I already have a vhost and exchange, and i want to pass it in my code
Comment: What is the name of the vhost?
Answer: Things changed over time.
Please have a look at RMQConnectionConfig: here you can find the way to specify a virtual host through builder pattern.
Answer: You need to provide the vhost name as well. Take a look at AMQP URI spec.
In your case the whole AMQP URI would look like would be "user:email@example.com:5672/TestVHost".
Comment: This is good if you are using RabbitMQ lib, but with [Flink connector](https://github.com/apache/flink/blob/master/flink-streaming-connectors/flink-connector-rabbitmq/src/main/java/org/apache/flink/streaming/connectors/rabbitmq/RMQSource.java)...
Comment: If that lib doesn't support vhost, you shouldn't use it. No one should.
Comment: So the question is how to use RabbitMQ lib in a Flink context
Comment: Well, change the source. In the link you provided RMQ java client is used, so simply extended Flink with a function that includes vhost parameter. Why don't you use official RMQ java client anyhow? (just curious)
Comment: Could you give me an example please, i´m not a java developer. The reason is because i´m doing a PoC with Flink and i want to test the native method
Comment: It's easier to to PoC with official rabbitmq java client. You already have the examples written. But if you want to.. In the file provided change the constructor, so that it has `String vhost` which you assign to the member attribute with the same name. And change the `initializeConnection` method (which is private, so you cannot extend actually) to call `factory.setVhost(vhost);`, the same way it's done for username etc...
Comment: Thank you, i did it, it was my alternative, but now i want to run it in a Flink stream context....
Comment: You are welcome! And since you are new: according to http://meta.stackexchange.com/questions/79347/reminding-new-users-of-accept-upvote-duty I guess I wouldn't seem to bad if I ask for upvote and accept :)
Answer: The error you're seeing is a Scala compile time error caused by some needed imports not being there.  Whenever you are using the Flink Scala API you should include the following:
import org.apache.flink.api.scala._
This will solve the compile time problem you're having.
Comment: `Connected to the target VM, address: '127.0.0.1:4391', transport: 'socket'`
`Disconnected from the target VM, address: '127.0.0.1:4391', transport: 'socket'`
`java.lang.NoClassDefFoundError: org/apache/flink/streaming/api/datastream/DataStreamSink`
`Caused by: java.lang.ClassNotFoundException: org.apache.flink.streaming.api.datastream.DataStreamSink`
`Error: A JNI error has occurred, please check your installation and try again`
Comment: How are running this?  Can you provide some more details?  Are you running in Intellij, local cluster, remote-cluster, etc..  How are you submitting your job?
Comment: I´m running it in IntelliJ, i want to consume Json from a RabbitMQ exchange queue
Comment: The goal is to compile it, and run it in a Yarn-Flink cluster. Dependencies: `org.apache.flink:flink-scala_2.11:1.0.3, org.apache.flink:flink-streaming-scala_2.11:1.1-SNAPSHOT, org.apache.flink:flink-clients_2.11:1.0.3, org.apache.flink:flink-connector-rabbitmq_2.11:1.1-SNAPSHOT`
MANIFEST.MF: `Class-Path: scala-library.jar rabbitmq-client.jar`
Comment: I noticed from your dependencies list above that you are mixing Flink 1.0.3 dependencies with 1.1-SNAPSHOT dependencies.  This could be the cause of the errors you're now seeing.  I would straighten that out and try again.
Comment: Thank you Jamie, the solution was the import you said, and put the rabbit-connector dependency in the profile for packaging JAR files in pom.xml

Flink RMQSource


how to show ip address on the web?

Question:
Possible Duplicate:
How do I find a user's IP address with PHP?
How can I get the user's IP address in PHP?

I make application web based. I want to show the IP address of the user/visitor who visit my web. I've used the script to find the IP address but it didn't work and no IP show. How to solve it?? do I miss something? This is my php script :
function get_ip()
{
    global $ip;
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$ip = get_ip();

Please, I really need your help ! Thank you ...
Comment: You don't need `global $ip;` btw
Comment: Add $_SERVER["HTTP_X_REAL_IP"]
Comment: Do a print_r( $_SERVER ); to see what you are playing with.
Comment: @Sergey, where I have to add that script??
Answer: Your script does not display the result from the function call, only assigns it to the $ip variable.  You'd want to add the following to display its value:
echo 'IP Address: ' . $ip;

Cheers.
Comment: actually, just do echo get_ip(); at the end of your file.  You can get rid of $ip = get_ip() all together unless you need it somewhere else.  No use declaring a variable unless your going to use it in more than one place!
Comment: @alecwhardy - Good point.  Just thought I would put it this way so they could get some insight on how functions work and how variables and functions can interact.  :)
Comment: @alecwhardy: Another use of a variable is to give a value a name. Works even when used once and can make sense.
Comment: it works inside a function, globally its not a good idea to have any variables if you can keep everything inside a class as a property.

how to show ip address on the web?