text:
Q: model.fit vs model.predict - differences & usage in sklearn I am new to ML with Python and was trying my first attempt via a tutorial. In that tutorial, there are some lines of code that I am having difficulties understanding how they interact with each other.
First code is the splitting of the data occurred as the following:
train_x, val_x, train_y, val_y = train_test_split(X, y,test_size=0.3)

My first question: Why do we use validation data over test data? Why not all, train, val, and test? What is the use case for which combination to use?
The next section speficies the ML model and preditcs.
model = DecisionTreeRegressor()
model.fit(train_x, train_y)
val_predictions = model.predict(val_x)

My second question: For the model.predict() statement, why do we put val_x in there? Don't we want to predict val_y?
Bonus Question: Also, in many tutorials I saw how StandardScalers are applied. However, in this tutorial it doesnt appear as such or did some other function already scale it without having to explicitly state it? Please help.

A: Q 1.1 : Why do we use validation data over test data? (in above scenario)
train_x, val_x, train_y, val_y = train_test_split(X, y,test_size=0.3)

First of all, the terms validation set and test set are very loosely
  used in many tutorials and sometimes interchangeably. It is quite
  possible to call the above val_x, val_y as test_x, test_y

Q 1.2 :Why not all, train, val, and test? (why the split?)
All our machine learning algorithms are going to be used on some real-world data (refer actual test data). However after devising an algorithm we want to "test" how well it performs, what is its accuracy, etc.

Actually we currently don't have the real world data! Right?

But what do we have? The train data! so we cleverly put aside a portion of it (splitting) for later testing the algorithm. The test data is used to evaluate the perform once the model is ready.
model = DecisionTreeRegressor()
model.fit(train_x, train_y)
val_predictions = model.predict(val_x) # contains y values predicted by the model
score = model.score(val_x, val_y) # evaluates predicted y against actual y of test data
print(score)

Q 2. : For the model.predict() statement, why do we put val_x in there? Don't we want to predict val_y?
Absolutely right we want to predict val_y, but the model needs val_x to predict y. That's exactly what we are passing as argument to the predict function.

I understand it might be confusing to read model predict val_x.
So the better way is to interpret it, as model could you u please predict
  from val_x, and return predicted_y.

I say predicted_yand not val_y because, both won't be exactly similar. How much they differ? That is what  given by score.
Some Terminologies

*

*Data Set :  Data in hand. It is this data that gets divided later

*Train Set :  It is part of Data Set from which our model learns. Usually large, about 70-80%. Commmonly denoted by train_x and train_y.

*Test Set : Part of Data Set that we set aside to evaluate the performance of model. This "tests" the model hence the name. Denoted by test_x and test_y.

*Validation Set : If we want unbiased estimates of accuracy during the learning process, we use another split of Data Set. Usually to find hyperparamters etc. Typically to

*

*Pick best-performing algorithm (NB vs DT vs..)

*Fine-tune parameters (Tree depth, k in kNN, c in SVM)

Q 1.3 : What is the use case for which combination to use?

You will always have train & test, or all three. However in your case
  the test is just named as val.

BONUS Question : In many tutorials I saw how StandardScalers are applied. However, in this tutorial it doesnt appear as such or did some other function already scale it without having to explicitly state it?

It all depends on your data. If the data is pre-processed and all scaled properly then StandardScalers need not be applied. This particular tutorial just implies that data is already normalised accordingly.

A: 1) Validation sets are often used to help you tune hyper-parameters accordingly. Because you may fine tune the model according to its performance on the validation set, the model may become slightly biased to the validation data, even though it isn't directly trained on that data, which is why we keep this separate from the test set. Once you tune the model to your liking based on the validation set, you can evaluate it on your test set to see how well it generalizes.
2) Calling model.predict(val_x) will return the predicted y values based on the given x values. You can then use some loss function to compare those predicted values with val_y to evaluate the model's performance on your validation set.


text:
Q: Changing azure web application logo shown in office 365 I'm currently trying to host a web application through azure and making it available to users in office 365 via 'My Apps'.
The user connect to the app site, allows the app to gather data from azure AD, and through the magic of interconnectivity, the app then shows in 'My Apps'.
The problem I'm having is that I need to change the logo/image/tile of the app from the generic 'custom application' one, but I'm having trouble finding any sources telling me how to do this.
The application is built as an ASP.NET Web Application (MVC).
TL;DR: How do i change the tile/icon of a web application hosted in azure, shown in office 365
This image shows the app i need to change

A: You need to go to your application's page in the Azure Management Portal, then go to the Configure tab. On the action bar at the bottom of the screen, there is an option to Upload Logo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Permutating Result Set of My Query, Something is wrong I have 4 tables:

*

*Persons

*Jobs

*Titles

*Departments

Persons Table
id | title_id | person | phone | email | dept_id | job_id
---+----------+--------+-------+-------+---------+-------
1  |        1 | some1  | 12345 | s@a.c |       2 |      3
...

Other tables' structures are same as the following
id | ********
---+---------

Assume that there are 5 records in table titles, 5 records in table departments and 5 job records in table jobs.
And let's say suitable records defined by $search string = 6 in table persons;
When I execute the query below, the result set has  5 x 5 x 5 x 6 = 750 records and most of them are repetitive. The results look like doing permutation.
$query = sprintf(
                  "SELECT *
                   FROM
                         persons p, titles t, departments d, jobs j
                   WHERE
                         p.person LIKE %s OR
                         p.phone LIKE %s OR
                         p.email LIKE %s AND
                         p.id=t.id AND
                         p.id=j.id AND
                         p.id=d.id",
                   $search, $search, $search
                  );

Then I have tried to changed the conditions as the following:
$query = sprintf(
                  "SELECT *
                   FROM
                         persons p, titles t, departments d, jobs j
                   WHERE
                         p.person LIKE %s OR
                         p.phone LIKE %s OR
                         p.email LIKE %s AND
                         p.title_id=t.id AND
                         p.job_id=j.id AND
                         p.dept_id=d.id",
                   $search, $search, $search
                  );

This returns the same result.
I just want to get title's itself instead of title_id, job's itself instead of job_id and department's name instead of dept_id in the result set, at once.
What am I doing wrong?

A: Try using join:
$query = sprintf(
                  "SELECT *
                   FROM
                         persons p join titles t on p.title_id=t.id join departments d on  p.dept_id=d.id join jobs j on p.job_id=j.id
                   WHERE
                         p.person LIKE %s OR
                         p.phone LIKE %s OR
                         p.email LIKE %s
                   ",
                   $search, $search, $search
                  );

DEMO

A: Replace SELECT *
                   FROM  to SELECT distinct *
                   FROM


text:
Q: FMDB queueing - how does is this pattern correctly implemented? I have some code using the FMDB sqllite wrapper (https://github.com/ccgus/fmdb) and I'm expecting this code to be executed from multiple threads. As such, I'm using the FMDatabaseQueue class to execute all DB work.
I'm a little bit confused by the pattern, e.g.
FMDatabaseQueue *q = [FMDatabaseQueue databaseQueueWithPath:@""];
[q inDatabase:^(FMDatabase *db) {
    NSLog(@"1");
    BOOL yn = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS Foo (Bar TEXT)"];
    NSLog(@"2%@", yn ? @"YES" : @"NO");
}];
NSLog(@"3");

If you look at the code above.. is it guaranteed that 3 will always be logged after 2 and 1? Such that the executing thread is blocked until the block provided to the queue actually gets to execute?
If so, should I remove any non-database work outside and after the block so that any other threads using the queue are not blocked by work that doesn't need to be synchronized across threads?
Also, do I need to call [db open] when using FMDatabaseQueue?

A: Yes, it's guaranteed that 3 will be logged after 1 and 2.
That's because FMDatabaseQueue -inDatabase: uses a dispatch_sync call internally to do the database operations (as you can see in the source code).
So, the recommendation would be do the less work possible inside the block, and do all the other work on your own queue.
Also, [db open] is not needed, because FMDatabaseQueue -initWithPath: (called by FMDatabaseQueue +databaseQueueWithPath:) already does that (as again, you can see in the source code).


text:
Q: ReplaySubject take is not a function I am trying to replicate angular-realworld-example-app, but I am caught with an error I do not understand. (I am using RxJS 5.4.0 and Angular 4.2.5).
My route "login" has a guard "No Auth Guard" to check if the user is already logged in. Only "non-logged-in" users can "login." The guard checks if the user is logged in, and negates the answer (bool => !bool) to determine whether the user can pass.
User.service.ts:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { ApiService } from './api.service';
import { JwtService } from './jwt.service';
import { User } from '../models/user.model';

@Injectable()
export class UserService {
    private currentUserSubject = new BehaviorSubject<User>(new User());
    public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged();

    private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
    public isAuthenticated = this.isAuthenticatedSubject.asObservable();

    constructor (
        private apiService: ApiService,
        private http: Http,
        private jwtService: JwtService
    ) {}

    // Verify JWT in localstorage with server & load user's info.
    // This runs once on application startup.
    populate() { // THIS IS CALLED IN APP.COMPONENT
        // If JWT detected, attempt to get & store user's info
        if (this.jwtService.getToken()) {
            this.apiService.get('/user')
                .subscribe(
                    data => this.setAuth(data.user),
                    err => this.purgeAuth()
                );
        } else {
            // Remove any potential remnants of previous auth states
            this.purgeAuth();
        }
    }

    setAuth(user: User) {
        // Save JWT sent from server in localstorage
        this.jwtService.saveToken(user.token);
        // Set current user data into observable
        this.currentUserSubject.next(user);
        // Set isAuthenticated to true
        this.isAuthenticatedSubject.next(true);
    }

    purgeAuth() {
        // Remove JWT from localstorage
        this.jwtService.destroyToken();
        // Set current user to an empty object
        this.currentUserSubject.next(new User());
        // Set auth status to false
        this.isAuthenticatedSubject.next(false);
    }

    attemptAuth(type, credentials): Observable<User> {
        const route = (type === 'login') ? '/login' : '';
        return this.apiService.post('/user' + route, {user: credentials})
            .map(
                data => {
                    this.setAuth(data.user);
                    return data;
                }
            );
    }

    getCurrentUser(): User {
        return this.currentUserSubject.value;
    }
}

No-auth-guard.service.ts:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';

import { UserService } from '../services/user.service';

@Injectable()
export class NoAuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private userService: UserService
    ) {}

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): Observable<boolean> {

        return this.userService.isAuthenticated.take(1).map(bool => !bool);
    }
}

Despite updating my imports, I still receive an error that take is not a function
Error: Uncaught (in promise): TypeError: this.userService.isAuthenticated.take is not a function
TypeError: this.userService.isAuthenticated.take is not a function

Similar, but not a duplicate of: Getting boolean value from ReplaySubject<boolean> asObservable

A: We can resolve it in two ways.
import 'rxjs/add/operator/take';

this is more likely importing a specific operator to your service.
import { Observable } from 'rxjs';

i prefer the above statement because it provides all the operators that you need over an Observable rather than a separate import statement for the operator.


text:
Q: Add keyboard-event to Openlayers map I'm unable to add a custom keyboard-event to Openlayers, and can't figure out why. Might it be a bug in relation to the already existing keyboard-events included in Openlayers?
I've tried the following with no result:
this.map.getViewport().addEventListener('keydown', (e) => {
  console.log(e);
}, true)

document.getElementById('map').addEventListener('keydown', (e) => {
  console.log(e);
})

Listening to clicks on the same elements work fine:
this.map.getViewport().addEventListener('click', (e) => {
  console.log(e);
}, true)

document.getElementById('map').addEventListener('click', (e) => {
  console.log(e);
})

Any solutions to this?

A: This problem as Mike mentioned is occurring because of focus issues.
I faced this problem a few months ago, so I searched my old projects and find this:

After assigning a tab index to an element you can use javascript focus().
in order to use it (after assigning tab index) use this:
document.getElementById('map').focus();

I think this could help.
Also, there is an answer I found months ago is here. You can find more info about focusing.

A: As mentioned map needs focus. You can use the FocusMap interaction of ol-ext to focus on the map when ckick on it.
See https://github.com/Viglino/ol-ext/blob/master/src/interaction/FocusMap.js
This example use it to handle ctrl+c/ctrl+v on a map.
https://viglino.github.io/ol-ext/examples/interaction/map.interaction.copypaste.html

A: The most reliable solution in our angular application was to add a custom Interaction, but you still need to set tabindex="0" on your map ;)

Here is an example:
import { Interaction } from "ol/interaction";
import { MapBrowserEvent } from "ol";

class KeyboardEventInteraction extends Interaction {
  constructor() {
    super();
  }
  handleEvent(mapBrowserEvent: MapBrowserEvent<KeyboardEvent>) {
    let stopEvent = false;
    if (mapBrowserEvent.type === "keydown") {
      const keyEvent = mapBrowserEvent.originalEvent;
      if (keyEvent.code?.toLowerCase() === "escape") {
        // do whatever you want with your escape key
        stopEvent = true;
      }
      // add other keys
      if (stopEvent) {
        keyEvent.preventDefault();
      }
    }
    return !stopEvent;
  }
}

You need to add this handler to your map:
new Map({
  //... your map settings
  interactions: [
    //... your interactions
    new KeyboardEventInteraction(),
  ],
});


text:
Q: Can I "optimize" a query involving a text column? If I have this 400M rows table:
create table my_table
( id int,
  filled tinyint,
  content text not null
) engine=myisam

can I prevent the extra access of content (due to column type text) with:
select id,if(filled,content,'') from my_table

(filled is 0 or 1)?
Or if content can be null, would
select id,ifnull(content,'') from my_table

be better (still in term of performance since the null overhead would then occur)?

A: Your question is imprecise.  Might a row have filled = 1 and content = 'some text'?
If yes, then the IF(filled, content, '') makes sense.
If no, then get rid of filled and simply set content to ''.  The cost of accessing an empty string for content is tiny.
How big is content typically?  If is usually only hundreds of characters, the performance difference is small.
Don't use MyISAM, switch to InnoDB.
Do you have a lot of DELETEs or UPDATEs?  If so, the .MYD file of MyISAM may be fragmented.  This implies that content may be scattered around the disk.  If you have no updates or deletes, then content is "right there", hence virtually free to access.
In contrast, InnoDB sometimes puts TEXT and BLOB "off-record".
But, which is better or worse?  The off-record (in some situations) versus the fragmentation (in some situations).
Are you fetching just one row?  Or lots of such rows?  This is another area where MyISAM and InnoDB are implemented quite differently.  MyISAM needs to step over content to get to the "next" row.  (I won't go into a lengthy discussion of where the "next" row is likely to be.)
Bottom line:  Don't worry about optimizing, but do change to InnoDB (for a lot of reasons).
Where is the "next" row likely to be?
MyISAM...  Rows are added to the .MYD in the order of inserts.  But, after updates or deletes, new/changed rows tend to fill in the gaps first, leaving appending to the file as a last resort.
InnoDB...  Rows are in a B+Tree ordered by the PRIMARY KEY.  The BTree is blocked with 16KB blocks.  You have a TEXT column, so it gets more complex...
For "small" TEXT columns, several rows will fit into 16KB.  If, say, content is 1KB strings, up to about 15 rows will be put in a block.  If they are much bigger, then content will be stored "off-record".
The rows in a block are essentially all equidistant from each other.  (The big effort is loading the block into cache and locating the block.)
The "next" (or "previous") block is just a disk access away -- see the "+" in "B+Tree".
When a block overflows, it is "split" into two blocks, some rows go into each.  The new block is allocated somewhere, rarely adjacent.
With SSDs, all blocks are "equidistant" from each other.  With HDD, rotational delays and arm motion complicate the timing of which block might be "closer" than some other block.


text:
Q: Changing input background color depending on the input in PHP I am having trouble with the changing background color of input fields. If it is empty or already in use or the some another rule that I defined, the background color should change. Juts I need an example on simple form like:
<form name="login" action="" method="post">
Username: <input type="text" name="username">

<input type="submit" name="submit" value="Submit">
</form>

I want to use PHP and CSS codes for to do that. Feel free to use div classes and other stuff.
Thanks

A: You can do this with CSS3 attribute selectors. For example, if you wanted the background to be red if the input is empty or green otherwise.
input { background: green; }
input[value=""] { background: red; }

Note that CSS3 attribute selectors are not fully compatible with IE8 and lower. All other modern browsers will support them.
Also if you want it to update dynamically (ie. change from red to green when the user enters something into the input box) you would have to use Javascript.

A: i wrote you a litte example
css
.placeholder {color:#aaa;}
input[type=text],
input[type=password] {
    background:#eee;
}
input[type=text]:focus,
input[type=password]:focus {
    background:#fff;
}

js
$("#username").focus(function(){
    if($(this).val() == "Benutzername")
    {
        $(this).val("");
        $(this).removeClass('placeholder');
    }
});
$("#username").blur(function(){
    if($(this).val() == "")
    {
        $(this).val("Benutzername");
        $(this).addClass('placeholder');
    }
});

$("#password").focus(function(){
    if($(this).val() == "Passwort")
    {
        $(this).val("");
        $(this).prop("type", "password");
        $(this).removeClass('placeholder');
    }
});
$("#password").blur(function(){
    if($(this).val() == "")
    {
        $(this).val("Passwort");
        $(this).prop("type", "text");
        $(this).addClass('placeholder');
    }
});

html
<input id="username" type="text" class="placeholder" value="Benutzername" />

<input id="password" type="text" class="placeholder" value="Passwort" />

Check it out in JSFiddle
http://jsfiddle.net/hk8k4vew/


text:
Q: Bypass login page in keycloak using access token We have a requirement, where we need to bypass the login page and directly provide access to the user based on a token that has the email of the user.
We are using the email of the user and generating an access token for the user using admin credentials in Keycloak.
Even after getting an access token, we are not understanding how to start a session in Keycloak using the access token or refresh token or id token that we get.
We generated the access token with the help of steps provided in the below link:
Keycloak: Generate access token for a user with keycloak-admin
Can anyone suggest how to proceed further on how to initiate a keycloak session

A: I would suggest using the action token spi. You can see an example in the quickstarts: action-token: Using Action Token to Incorporate External App Call into Authentication Flow.
The way you could use this feature:

*

*Create a REST endpoint for generating a link that contains the one time use action token

*Create an handler for the action token that sets a auth session note and redirects the user to the browser flow

*Create an alternative authenticator that check for the auth session note set by the token handler

The action token should be one time use.
The user would be given the link generated by the REST endpoint from 1. and it should be able to login without any password.
In my opinion, this is way more secure than passing access tokens to the user.


text:
Q: Django says that model has no ForeignKey to another model but it really does Will you help me to figure out why Django raises this error?

SolutionsForLanguagesApp.LanguageLevel: (fields.E336) The model is
  used as an in termediate model by
  'SolutionsForLanguagesApp.UserProfile.languages', but it does not
  have a foreign key to 'UserProfile' or 'Language'.

I'm confused because, as you can see, there is a foreign key to Language in LanguageLevel already:
class LanguageLevel(models.Model):
    language = models.ForeignKey(Language)
    level = models.ForeignKey(Level)

    class Meta:
        unique_together = (('level', 'language'),)

Do you know what to do?
EDIT - Added UserProfile:
class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')
    date_of_birth = models.DateField(null=True, blank=True)
    telephone = models.CharField(max_length=40, null=True, blank=True)
    IBAN = models.CharField(max_length=40, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    MARITAL_STATUS_CHOICES = (
        ('single', 'Single'),
        ('married', 'Married'),
        ('separated', 'Separated'),
        ('divorced', 'Divorced'),
        ('widowed', 'Widowed'),
    )
    marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True, blank=True)

    HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
        ('coincidence', u'It was coincidence'),
        ('relative_or_friends', 'From my relatives or friends'),
    )
    how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True,
                                                blank=True)

    # TRANSLATOR ATTRIBUTES

    is_translator = models.BooleanField(default=False)

    # language_tuples = models.ManyToManyField(LanguageTuple,blank=True)
    languages = models.ManyToManyField(Language, through='LanguageLevel')

    rating = models.IntegerField(default=0)

    number_of_ratings = models.BigIntegerField(default=0)

    def __unicode__(self):
        return '{} {}'.format(self.user.first_name, self.user.last_name)

    def __str__(self):
        return '{} {}'.format(self.user.first_name, self.user.last_name)

A: Your LanguageLevel model is missing a ForeignKey to the UserProfile:
class LanguageLevel(models.Model):
    language = models.ForeignKey(Language)
    level = models.ForeignKey(Level)
    # Add Foreign Key to UserProfile
    userprofile = models.ForeignKey(UserProfile)

    class Meta:
        unique_together = (('level', 'language'),)

Also I'm not sure that the unique_together constraint is what you want - it will mean that only one user can have any one combination of language/level. A more likely constraint would be ('userprofile', 'language') so that a language can only be mapped to a user once.


text:
Q: Trying to test a function that has a partial function that is wrapped with a Try and Either I have a function that's signature looks like:
def processUsers(user: User): PartialFunction[Try[Either[Boolean, User]], Int] = {
  case Success(s) =>
  case Failure(f) =>

}

Now in my scala test I have this so far:
whenReady(userService.processUsers(testUser)) {

}

I'm not sure how to pass in a partial function that I can simulate both the sucess and failure paths.

A: There's a lot going on here.  The semantics of the method are a little confusing, it's called processUsers (plural) but takes a single user object.  Also, the method returns a partial function, but the implementation looks like it's operating on the return value, e.g. there's nothing to match Success or Failure against in the method body.
Maybe, you want your processUsers function to have a multi-parameter list that accepts a function parameter?
Something like
def processUsers(user: User)(op: user => Either[Boolean, User]): Try[Either[Boolean, User]]] = {
  Try {
    // pre-processing that may cause an exception
    op(user)
  }
}

Then you could write a test case like so
  processUsers(user) { user => /* do stuff */ } match {
    case Success(Left(false)) => ???
    case Success(Left(true)) => ???
    ...
  }

I'm not sure if this is what you are going for. I wouldn't advocate this approach but maybe it answers your question.


text:
Q: Using Python to separate Excel file into multiple files and multiple sheets within each file I have a large file that I need to have separate files determined by a DEPTNAME column. After separating out by DEPTNAME, I need to then create different sheets inside each file based on a STRM column. I can currently separate it out by either STRM or DEPTNAME but cannot get it to create additional sheets for the 2nd loop on STRM.
uni_val1 = mart['DEPTNAME'].unique()
uni_val2 = mart['STRM'].unique()

for items in uni_val1:
    df = mart[mart['DEPTNAME']==items]
    for items2 in uni_val2:
            df2 = df[df['STRM']==items2]
            path = os.path.join(out_loc,str(items)+".xlsx")
            df2.to_excel(path,sheet_name =str(items2)+' All Courses', index=True)

is what I have so far but I am stuck on how to proceed.
My output should be multiple files based on DEPTNAME. Within each file, it would then be filtered/new sheets for each value in STRM.


text:
Q: Python, Kafka and Docker - KafkaConsumer keeps hanging I have the following docker-compose file:
  version: '3.1'

  services:
    postgres_db:
      image: postgres
      restart: always
      environment:
        POSTGRES_USER: admin
        POSTGRES_PASSWORD: admin
        POSTGRES_DB: default_db
      ports:
        - 54320:5432
    zookeeper:
      image: wurstmeister/zookeeper
      ports:
        - "2181:2181"
    kafka:
      image: wurstmeister/kafka
      ports:
        - "9092:9092"
      environment:
        KAFKA_ADVERTISED_HOST_NAME: kafka
        KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
        KAFKA_CREATE_TOPICS: "test:1:1"
      volumes:
        - /var/run/docker.sock:/var/run/docker.sock

After running it using docker-compose up - everything looks fine from the terminal output.
I start a python console and run the following lines:
kp = KafkaProducer(bootstrap_servers=['localhost:9092'],api_version=(0,10),
                         value_serializer=lambda x:
                         dumps(x).encode('utf-8'))
kc = KafkaConsumer('test', bootstrap_servers=['localhost:9092'],api_version=(0,10),group_id=None,auto_offset_reset='earliest',
                   value_deserializer=lambda json_data: json.loads(json_data.decode('utf-8')))
data = {"test":"test"}
kp.send(topic="test",value=data)
for message in kc:
    print(message.value)

However after running this, the console simply hangs and it dosent look like the message was consumed/produced. Any ideas what went wrong here? Thanks!

A: Either you need to run your Python code in a container and set
bootstrap_servers=['kafka:9092']

Or you need to advertise Kafka back to the clients on your host machine
KAFKA_ADVERTISED_HOST_NAME: localhost

You can read the wurstmeister README on the usage of HOSTNAME_COMMAND as well
I'd also recommend running the producer and consumer separately as you test them


text:
Q: React Admin: ReferenceArrayField is not passing data to child I am trying to display a datagrid of media of a product from a list of media ids. Using ReferenceArrayField component, the getMany() function of the media data provider is called. The fetching is working fine.
However, the data fetched is not passed by the ReferenceArrayField component to its child DataGrid.
I really don't get what is happening here, might be a bug.
<ReferenceArrayField label="Médias" reference="mediaResource" source="mediasIds">
            <DataGrid>
                <UrlField source="finalUrl" label="Miniature" target="_blank" />
                <TextField source="type" />
            </DataGrid>
</ReferenceArrayField>


text:
Q: How to protect \input shell command args with backslashes I want to \input"|..." to invoke a shell command and consume its output as LaTeX code.
In particular, I want to write something like:
\expandableShellCmdProtectCmdArgsWithBackslashes{echo}{2(3)}
and have it call the shell with:
echo \2\(\3\)
escaping all the "arg" characters with backslashes.
The reason is to escape shell-special characters like (.
The desired result is that echo prints 2(3) and that is consumed as LaTeX input.
The attempt below via \str_map_inline:nn + \c_backslash_str fails, producing strange slanted double-quote symbols in place of all of the locations where I'd expect backslashes before invoking the shell, and the actual shell command executed doesn't include most of the desired input.
How can I prepend a backslash before each character of an \input command?
\documentclass[11pt]{article}

\begin{document}

\makeatletter
\newcommand{\expandableShellCmd}[1]{ \@@input"|#1"} % \input is not expandable
\makeatother

\ExplSyntaxOn
\NewDocumentCommand{\protectWithBackslashes}{m} { % prepends every character of the input with a backslash
  \str_map_inline:nn{#1}{\c_backslash_str##1}
}
\NewDocumentCommand{\expandableShellCmdProtectCmdArgsWithBackslashes}{mm} {% shell command, args
  % Pass the input string as a cmd to the shell, but prepend each char in the args with a backslash
  \exp_args:Ne\expandableShellCmd{#1~\protectWithBackslashes{#2}} % Fully expand the argument before invoking the shell
}
\ExplSyntaxOff

\expandableShellCmdProtectCmdArgsWithBackslashes{echo}{2(3)} % want to run in shell "echo \2\(\3\)" which produces output "2(3)"
% However, this produces PDF output:
% "2"("3")"
% and the console output shows that the shell command executed was (without quotes) "|echo "

\end{document}

A: Commands defined with \NewDocumentCommand are not touched by e-expansion; also \str_map_inline:nn has the same feature, so calling \exp_args:Ne does nothing at all.
And I don't think you need to worry about expandability.
\documentclass{article}

\ExplSyntaxOn

\tl_new:N \l_fink_shell_output_tl

\NewDocumentCommand{\DoShellCommand}{O{}m}
 {
  \fink_shell_do:nn { #1 } { #2 }
 }

\NewExpandableDocumentCommand{\protectWithBackslashes}{m}
 { % prepends every character of the input with a backslash
  \fink_shell_addbackslash:n { #1 }
 }

\cs_new_protected:Nn \fink_shell_do:nn
 {
  \sys_get_shell:nnN { #2 } { #1 } \l_fink_shell_output_tl
  \tl_use:N \l_fink_shell_output_tl
 }
\cs_generate_variant:Nn \fink_shell_do:nn { ne }

\cs_new:Nn  \fink_shell_addbackslash:n
 {
  \str_map_function:nN { #1 } \__fink_shell_addbackslash:n
 }
\cs_new:Nn \__fink_shell_addbackslash:n
 {
  \c_backslash_str #1
 }

\NewDocumentCommand{\DoShellCmdProtectCmdArgsWithBackslashes}{mm}
 {% shell command, args
  % Pass the input string as a cmd to the shell, but prepend each char in the args with a backslash
  \fink_shell_do:ne {} {#1~\fink_shell_addbackslash:n {#2}}
  % Fully expand the argument before invoking the shell
}
\ExplSyntaxOff

\begin{document}

\DoShellCmdProtectCmdArgsWithBackslashes{echo}{2(3)}

\end{document}

The log file has
(|echo \2\(\3\))


text:
Q: Android: print data on barcode scanner builder window Ok, so i need to display some of my product's database data on the scanner builder window(as shown in the image) when this product gets scanned. Scanner window results
As you can see in the image, the barcode scanner is displayed, my question is: is it possible to print in this windows some other data except from the product's barcode? if yes how should i move?
this is my windows builder code
public void handleResult(Result result) {
         //myResult= barcode text
         myResult = result.getText();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Scan Result");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                scannerView.resumeCameraPreview(addquantityactivity.this);
                updateData();
            }
        });
        builder.setNeutralButton("Visit(if url)", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
                startActivity(browserIntent);
            }
        });
        builder.setMessage(result.getText());
        AlertDialog alert1 = builder.create();
        alert1.show();

    }

A: Do you see where it says builder.setMessage(result.getText()); <--?
This is where you'd set the result. At the moment you're just putting in the result text which is the number. If you want something more, there is where you would put it.
EDIT:
I'm terrible at writing answers. The method you are using is defined here. It takes in a Character Sequence and will display it. Or it can take in an Int and show that.
EDIT2:
As an example of concatenating the barcode with some other information I would do this:
String myMessage = result.getText() + " and some other amazing information about this barcode";

builder.setMessage(myMessage);


text:
Q: Create a legend based on numeric array in matlab There is an array filled with numbers from 1 to 5. Each number denotes a particular class.
What would be the best way to populate another array that converts this to a string array representing classes.
For example:
Numbers=[1; 2; 3; 3; 2; 1]

Answer should be:
Strings=['Apple'; 'Orange'; 'Banana', 'Banana', 'Orange'; 'Apple']

I understand doing this with a loop is a trivial thing. But does there exist a more elegant solution which does not use a loop in matlab?

A: You only have to index your cell array of labels with your numbers:
Numbers = [1; 2; 3; 3; 2; 1]
Labels = {'Apple';'Orange';'Banana'};

Strings = Labels(Numbers);

Note that the result needs to be a cell array (not a matrix), because the strings have different lengths.
In your example, this gives:
>> Strings

Strings =

    'Apple'
    'Orange'
    'Banana'
    'Banana'
    'Orange'
    'Apple'


text:
Q: Map of Number Theory I've attempted going past basic number theory several times, and always got lost in its vastness. Do any of you, perhaps, know a good review that pieces together the many concepts involved (Hecke algebras, SL2(ℤ), Fuchsian groups, L-functions, Tate's thesis, Ray class groups, Langlands program, Fourier analysis on number fields, cohomological versions of CFT, Iwasawa theory, modular forms, ...)?
Thanks.

A: I don't know of any document that gives an accessible overview of all of the topics that you list. Number theory as a whole may be too big for such a thing to be possible. The number of people who have both deep knowledge of all listed topics and the expository skills to make them accessible may be very small.
However, I have seen some good sources for small clusters of the topics that you list. One book that I would recommend is Anthony Knapp's Elliptic Curves book which, despite its title also covers the basics of the theory of modular forms (Fuchsian groups too) and explains how to deduce that a Hecke newform of weight 2 with integral coefficients corresponds to an elliptic curve (the "easy" converse of the modularity theorem). When I read it, a number of things made sense that hadn't previously. But the said book is kind of long, at 450 pages so it doesn't qualify as a review - I just mention it as a relatively accessible and interesting place to get started.
As I've mentioned elsewhere on this site, I like Andre Weil's "Two lectures on number theory. past and present." L'Enseignement Mathematique. Revue Internationale. fie Serie. 20: 87-110. 1974
available here. It focuses on the early history of number theory and touches on little of what you say but may be useful to you in placing modern developments in context.
You might also get something out of browsing Henri Darmon's "Rational Points on Modular Elliptic Curves" which is at a more advanced level than Knapp's book. My experience is that it goes too fast for a beginner to understand in detail, but it gives some idea of different topics in (the more structural parts of) number theory interact with one another.
I look forward to other responses to this question.

A: The book you are looking for exists!! And indeed it contains ALL the buzzwords in your question!
It is Manin/Panchishkin's "Introduction to Modern Number Theory". This is a survey book that starts with no prerequisites, contains very few proofs, but nicely explains the statements of central theorems and the notions occurring therein and gives motivations for the questions that are being pursued. You should take a look, at least it can help you decide what you want to study in more detail.

A: Your question about one book for number theory is like a non-mathematician asking about one book for all mathematics. It is simply not possible. It is a growing subject in various directions. The best I can attempt is to give a book each for each direction, approximating your question. It is impossible to give anything better than this.
For Analytic Number Theory, what you ask can be achieved by:
Iwaniec And Kowalski, Analytic Number Theory.
This is THE book. It is quite comprehensive. Includes L-functions, modular forms, random matrices, whatever.
For algebraic number theory, the book:
Cassels and Frohlich, Algebraic Number Theory
would tell you all about developments upto Classfield Theory and Tate's thesis. Includes the cohomological version. This is a MUST for algebraic number theorists.
For Langlands' program, use the reference that Pete gives.
For Iwasawa theory, there are two books by Coates and Sujatha.
You might want to know a bit more about the applications of algebraic geometry into number theory. The way to go is through Silverman on elliptic curves, Q. Liu's book, Serre's books, etc..
A historic overview up to the time of Legendre can be found in Weil's book, "Number theory through history: From Hammurapi to Legendre".

A: This is a comment to Anweshi. I posted it as an answer because of its length.
@Anweshi - There's a funny story about Weil's Basic Number Theory which Shimura describes on page 139 of his autobiography My Life. Apparently, when the book came out, another member of the IAS protested vehemently about the title; class field theory should not be called basic he reasoned (the member took offense to the title, thinking that Weil had implied he did not possess even a basic knowledge of number theory). The reason that Weil titled the book as he did, was of course because the book did not contain any new results - only results that were by that time well known. Although I look at the book occasionally, my personal feeling is that any book that brings up the Haar measure on a locally compact group before the end of page 3 is perhaps not basic enough.

A: There are quite a few good books on class field theory. I think that Janusz' book Algebraic Number Fields stands out among them as one of the friendliest (Milne's notes are also quite good). As far as local class field theory is concerned, I think that one would be hard pressed to find a better resource than Serre's book Local Fields. Finally, Artin and Tate's book Class Field Theory was recently reprinted by the AMS. It is a fantastic book, but definitely falls under the 'you should only attempt to read this book after already having gained an understanding of the field' heading.

A: Ramakrishnan and Valenza, "Fourier analysis in number fields" is quite nice. Serre's "Cours d'arithmétique" is pretty good too -- and starts basic ("basic" as in "simple" not in "base" -- it has nothing to do with Weil's joking title).


text:
Q: Spring Cloud Zuul: RedirectView redirecting to service and not gateway I'm a bit new to microservices and Spring. I have Spring Cloud microservices (ports: 8xxx-8xxx) with a Zuul gateway running on port 9000. There's a method inside a controller on a UI service which should do a login and then return to a index.html page:
@RequestMapping(value="/do-login", method = RequestMethod.POST)
    public RedirectView doLogin (@ModelAttribute("authEntity") final AuthEntity authEntity, final Model model) {
        model.addAttribute(VERSION, applicationVersion);
        model.addAttribute("authEntity", new AuthEntity());
        authenticatedStatus = true;
        model.addAttribute(AUTHENTICATED, authenticatedStatus);

        return new RedirectView("index");
    }

The problem is that when above method completes it returns an url of the microservice itself localhost:8888/index but not localhost:9000/services/ui/.
If I use a simpler method:
@RequestMapping(value="/do-login", method = RequestMethod.POST)
public String doLogin (@ModelAttribute("authEntity") final AuthEntity authEntity, final Model model) {
    model.addAttribute(VERSION, applicationVersion);
    model.addAttribute("authEntity", new AuthEntity());
    authenticatedStatus = true;
    model.addAttribute(AUTHENTICATED, authenticatedStatus);

    return "index";
}

This returns correctly an url of gateway localhost:9000/services/ui/do-login but with a /do-login which I do not need.
Maybe I can get rid of /do-login/ part of url? Or maybe there is a solution for the incorrect redirect?
Thanks in advance!

A: If you use relative path like in return "index"; the result of the POST request sent to http://localhost:9000/services/ui/do-login will include URLs to http://localhost:9000/... unless coded otherwise in the jsp / freemarker / thymeleaf file.
If you want to get rid of the do-login, you would need to implement what's called a Redirect After Post (or redirect after form submit) approach so that a page refresh doesn't resubmit the form. If you take this approach, which seem what you were doing when using: return new RedirectView("index");, I can think of a couple ways of fixing the URL and set it to the proxy host.
1) http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/view/RedirectView.html, there are a couple of constructors that takes a host parameter, you would need to inject the proxy host in the controller class and most-likely in every controller class that implements Redirect After Post.
2) http://tuckey.org/urlrewrite/, include UrlRewriteFilter and configure rules to rewrite from webapp host to proxy host when webapp http status code response is 302. With this approach it would only be once rule and no need to inject proxy host to controller classes or change the return new RedirectView("index");`
3) Maybe this rewriting is implemented in Zuul and you don't need include and configure UrlRewriteFilter as suggested in 2).
As a side note, I have configured Nginx's proxy_pass to a Java webapps (where I implemented Redirect After Post) in the past and I don't recall having this issue. Will have to take a look at both UrlRewriteFilter and Nginx config files to expand on this.

A: I found that this (thanks to answer in here: Spring redirect url issue when behind Zuul proxy) seems to work as required (but is considered a 'workaround'):
@RequestMapping(value="/do-login", method = RequestMethod.POST)
    public void doLogin (@ModelAttribute("authEntity") final AuthEntity authEntity,
                         final Model model,
                         HttpServletResponse servletResponse) throws IOException {
        ...

        String rUrl = ServletUriComponentsBuilder.fromCurrentContextPath().path("/").build().toUriString();
        servletResponse.sendRedirect(rUrl);
    }


text:
Q: How to add a suffix onto column names based on existing column name? At the moment, the code below is not very reproducible as I am adding the suffix based on column numbers. How would I modify this code to add the suffix to all columns beginning with "rs" instead of using column numbers?
# make data

df <- data.frame(y1 = rbinom(100, 1, 0.5), y2 = rbinom(100, 1, 0.3), y3 = rbinom(100, 1, 0.2), y4 = rbinom(100, 1, 0.22),
                       rs1 = rnorm(100), rs2 = rnorm(100), rs3 = rnorm(100),
                       rs4 = rnorm(100), rs5 = rnorm(100), rs6 = rnorm(100))

# add suffix to column names beginning with rs
colnames(df)[5:10] <- paste(colnames(df)[5:10], "C", sep = "_")

A: Using basic R code:
start_with_rs<-substr(colnames(df),1,2)=="rs" #Boolean vector with T/F based on starting "rs"

#Rename
colnames(df)[start_with_rs]<- paste(colnames(df)[start_with_rs], "C", sep = "_")
        colnames(df)
         [1] "y1"    "y2"    "y3"    "y4"    "rs1_C" "rs2_C" "rs3_C" "rs4_C" "rs5_C" "rs6_C"

A: Use grep or startsWith from base R
nm1 <- startsWith(names(df), "rs")
# // or with grep
nm1 <- grep("^rs", names(df))
names(df)[nm1] <- paste0(names(df)[nm1], "_C")

Or using rename_at from dplyr
library(dplyr)
library(stringr)
df <- df %>%
  rename_at(vars(starts_with('rs')), ~ str_c(., '_C'))


text:
Q: Pass argument to PyRun_File(***) I am writing some code in C and in Python.
I have a python file called sample.py which accepts two string parameters.
My C program calls the python function using the PyRun_SimpleString(). In this way I am not able to pass any parameters.
By PyRun_SimpleString():
int main(int argc,char *argv[])
{
 ......
PyRun_SimpleString("import sample\nsample.mainfunc("argv[1]",'Isolated_domU_t')\n");
.....
}

How can I pass parameters argv[1] by using PyRun_SimpleString(*)?

A: To set arguments do like the following code:
wchar_t** wargv = new wchar_t*[argc];
for(int i = 0; i < argc; i++)
{
    wargv[i] = Py_DecodeLocale(argv[i], nullptr);
    if(wargv[i] == nullptr)
    {
        return EXIT_FAILURE;
    }
}

Py_Initialize();

// char* py=...
PySys_SetArgv(argc, wargv);
PyRun_SimpleString(py);

Py_Finalize();

for(int i = 0; i < argc; i++)
{
    PyMem_RawFree(wargv[i]);
    wargv[i] = nullptr;
}

delete[] wargv;
wargv = nullptr;

A: Use PyRun_String. It has a signature similar to PyRun_File:
PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)

Update:
In your case, it whould be simple enough to just copy the command line arguments into the string you want to execute, just like you tried in your question. Your code won't work though, because that's not how you concatenate strings in C. Try this instead:
#include <Python.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
    char py[1000]; /* that should be big enough */
    strcpy(py, "import sample\nsample.mainfunc(");
    strcat(py, argv[1]);
    strcat(py, ",'Isolated_domU_t')\n");

    Py_Initialize();
    PyRun_SimpleString(py);
    Py_Finalize();
}

This is, of course, only the quick&dirty version without checking if there even is an argument passed to the program, or checking for its length.

A: can use the snprintf or like his function
and  type this
char haies1[2048];
snprintf(haies1, sizeof(haies1),"import sample\n"
                "sample.mainfunc("%s",'Isolated_domU_t')\n",argv[1])

then can use the PyRun_SimpleString function like this
Py_Initialize();
PyRun_SimpleString(haies1);
Py_Finalize();


text:
Q: Vector Field analog of Functions Bear in mind that I don't have a formal education in mathematics. If functions form an abstract vector space then a single function can be considered as a member of a vector space. Then how can we obtain a vector field with functions, i.e., an object that attaches a unique function at each point on a given space?. I am not even sure whether I say make sense or whether my logic is correct.
Essentially what I wonder is that whether one can form an object that would attach a function to a point in space uniquely, as in one function for each point like vector fields attaching vectors to each point in space.

A: A "vector field of functions", an object which attaches a unique function to every point in, say $\mathbb{R}^n$, would basically be another function $g : \mathbb{R}^n \to C(X,Y)$, where $C(X,Y)$ denotes the functions from some set $X$ to another set $Y$. That would be the most basic way to define such an object. To my knowledge, one of the most common ways a structure like this shows up in mathematics is in forms of sections of fibre bundles, specifically differential forms as sections of the cotangent bundle of a manifold. Might be kind of scary concepts if you've not had a formal education in mathematics, but I will try to give a few short explanations for why one wants to study these generalizations:
If the space to which you want to attach functions is not $\mathbb{R}^n$, but maybe a circle, a sphere, a torus, a Klein bottle, of course you will simply need to replace every instance of $\mathbb{R}^n$ with your space in question. However, these spaces are a little bit more difficult to handle compared to $\mathbb{R}^n$ in a few ways: A sphere (which we will denote by $S^n$ from now on) is not a vector space, so adding points on a sphere makes no sense, and as such, it will be difficult to define what it means for a function on a sphere to be differentiable. Why is this important to your question?: Most likely, you want the values of your vector field of functions $g : S^n \to C(X,Y)$ not to be completely arbitrary, but maybe to be related in some smooth manner. When the space in question is "not too bad", like the above mentioned examples, they're manifolds, and a notion of differentiability can be established.
Furthermore: Perhaps you don't want to attach the same kind of function to every point. Like, at point $x_1$ you only allow functions from the space $C_1$, but at point $x_2$ you only allow functions from the space $C_2$. Then you will have to modify your vector field to read $g : S^n \to \bigcup_i C_i$, where the union goes over all different function spaces. That is basically what sections of a fibre bundle are. A fibre bundle is a space, the base space (like our $S^n$) which has another space, the fibre, attached to every point of it (like our $C_i$), and a section of this bundle is a map which chooses an element of the attached space for every point on the base space.
I think the first nontrivial example of such a situation that most mathematicians first come across is differential forms: Those are functions which attach to every point $x$ on a manifold a function $\omega_x$, and this function takes tangent vectors $X_1,\dots,X_n$ on the manifold at that point and assigns a real number to them in a multilinear way. Note that one requires that the function $\omega_x$ only takes tangent vectors attached to the manifold at the point $x$, so here we really have a different function space at every point, because it takes different tangent vectors at every point.
Maybe that gives you some ideas on how your concept is being studied!


text:
Q: How do I fix this issue? (kivy python, kivy 2.0.0) I keep running in into this issue, can you guys help please

A:     #Try this one .
    Python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew;

    python -m pip install kivy.deps.gstreamer

#Or You can also use this one solution.
pip uninstall kivy
pip install kivy
pip install docutils pygments pypiwin32 kivy.deps.sdl2
pip install kivy.deps.glew


text:
Q: Error in model.frame.default(formula = mpg01 ~ ., data = list(cylinders = c(8, : variable lengths differ (found for 'cylinders') I am not sure how to fix the length error in my code. Everything runs smoothly until I run svm.tune. Please advise!
library(ISLR)
attach(Auto)
n <- nrow(Auto)
mpg01 <- rep(0, length(mpg))
mpg01[mpg > median(mpg)] <- 1
mpg01 <- as.factor(mpg01)
Auto <- data.frame(Auto, mpg01)
Auto$mpg = NULL

set.seed(1)
train <- sample(1:n, 0.8*n)
x.train <- Auto[train,-9]
x.test <- Auto[-train,-9]
y.train <- Auto$mpg01[train]
y.test <- Auto$mpg01[-train]

library(e1071)
RNGkind(sample.kind = "Rounding")
set.seed(1)
svm.tune <- tune(method=svm,
                 mpg01~., data = x.train,
                 kernel = "linear",
                 ranges = list(cost = c(0.01,0.1,1,5,10)))

A: It is customary for the data to contain the response variable as well, so instead of splitting the train and test into x and y, you keep the train all in one data frame and the test in one data frame.
xy.train <- Auto[train,]
xy.test <- Auto[-train,]

library(e1071)
#RNGkind(sample.kind = "Rounding")
set.seed(1)
svm.tune <- tune(method=svm,
                 mpg01~., data = xy.train,
                 kernel = "linear",
                 ranges = list(cost = c(0.01,0.1,1,5,10)))


text:
Q: conversion from float to int (weird behavior) I have this shader to implement character animation
uniform mat4 u_mVxP;
uniform mat4 u_mBlendMatrices[54];
uniform vec4 u_vDLDiffuseColor;
uniform vec4 u_vDLAmbientColor;
uniform vec3 u_vLightDir;
attribute vec4 a_Position;
attribute vec3 a_BWeights;
attribute vec3 a_BIndices;
attribute vec3 a_Normal;
attribute vec2 a_TextureCoordinates;
varying vec2 v_TextureCoordinates;
varying vec4 v_Color;
void main()
{
    vec4 vPos;
    vec3 vNormal;
    int i=int(a_BIndices.x);
    int j=int(a_BIndices.y);
    int k=int(a_BIndices.z);
    vPos=a_BWeights.x * a_Position * u_mBlendMatrices[i];
    vPos+=a_BWeights.y * a_Position * u_mBlendMatrices[j];
    vPos+=a_BWeights.z * a_Position * u_mBlendMatrices[k];
    vNormal=a_BWeights.x * vec3(vec4(a_Normal,0.0) * u_mBlendMatrices[i]);
    vNormal+=a_BWeights.y * vec3(vec4(a_Normal,0.0) * u_mBlendMatrices[j]);
    vNormal+=a_BWeights.z * vec3(vec4(a_Normal,0.0) * u_mBlendMatrices[k]);
    vNormal = normalize(vNormal);
    v_Color = u_vDLDiffuseColor * max(dot(-u_vLightDir,vNormal),0.0) + u_vDLAmbientColor;
    gl_Position = vPos * u_mVxP;
    v_TextureCoordinates = a_TextureCoordinates;
}

code runs perfect on galaxy s3 and s4 and my characters have thier animation correctly.
but in sony xperia Z and galaxy note3 they are rendered only in bind pos with no animation!
after a lot of test i found out that when float converts to int in xperia z and galaxy note3 it only return 0
int i=int(a_BIndices.x); // i is always 0
int j=int(a_BIndices.y); // j is always 0
int k=int(a_BIndices.z); // k is always 0

i even used this code
int i=1;

but i is still 0. could anyone help me what is going on

A: I finally found out that i should use vec4 array instead of matrix array!
its weird but solved my case


text:
Q: hash functions family generator in python I am looking for a hash functions family generator that could generate a family of hash functions given a set of parameters. I haven't found any such generator so far.
Is there a way to do that with the hashlib package ?
For example I'd like to do something like :
h1 = hash_function(1)
h2 = hash_function(2)
...

and h1 and h2 would be different hash functions.
For those of you who might know about it, I am trying to implement a min-hashing algorithm on a very large dataset.
Basically, I have a very large set of features (100 millions to 1 billion) for a given document, and I need to create 1000 to 10000 different random permutations for this set of features.
I do NOT want to build the random permutations explicitly so the technique I would like to use in the following :

*

*generate a hash function h and consider that for two indices r and s

*r appears before s in the permutation if h(r) < h(s) and do that for 100 to 1000 different hash functions.

Are there any known libraries that I might have missed ? Or any standard way of generating families of hash functions with python that you might be aware of ?

A: As mentioned above, you can use universal hashing for minhash.
For example:
import random

def minhash():
    d1 = set(random.randint(0, 2000) for _ in range(1000))
    d2 = set(random.randint(0, 2000) for _ in range(1000))
    jacc_sim = len(d1.intersection(d2)) / len(d1.union(d2))
    print("jaccard similarity: {}".format(jacc_sim))

    N_HASHES = 200
    hash_funcs = []
    for i in range(N_HASHES):
        hash_funcs.append(universal_hashing())

    m1 = [min([h(e) for e in d1]) for h in hash_funcs]
    m2 = [min([h(e) for e in d2]) for h in hash_funcs]
    minhash_sim = sum(int(m1[i] == m2[i]) for i in range(N_HASHES)) / N_HASHES
    print("min-hash similarity: {}".format(minhash_sim))

def universal_hashing():
    def rand_prime():
        while True:
            p = random.randrange(2 ** 32, 2 ** 34, 2)
            if all(p % n != 0 for n in range(3, int((p ** 0.5) + 1), 2)):
                return p
    m = 2 ** 32 - 1
    p = rand_prime()
    a = random.randint(0, p)
    if a % 2 == 0:
        a += 1
    b = random.randint(0, p)
    def h(x):
        return ((a * x + b) % p) % m
    return h

Reference

A: I'd just do something like (if you don't need thread-safety -- not hard to alter if you DO need thread safety -- and assuming a 32-bit Python version):
import random

_memomask = {}

def hash_function(n):
  mask = _memomask.get(n)
  if mask is None:
    random.seed(n)
    mask = _memomask[n] = random.getrandbits(32)
  def myhash(x):
    return hash(x) ^ mask
  return myhash

A: @alex's answer is great and concise, but the hash functions it generates are not "very different from each other".
Let's look at the Pearson correlation between 10000 samples of 10000 hashes that put the results in 100 bins
%%time # 1min 14s
n=10000
hashes = [hash_function(i) for i in range(n)]
median_pvalue(hashes, n=n)
# 1.1614081043690444e-06

I.e. the median p_value is 1e-06 which is far from random. Here's an example if it were truly random :
%%time # 4min 15s
hashes = [lambda _ : random.randint(0,100) for _ in range(n)]
median_pvalue(hashes, n=n)
# 0.4979718236429698

Using Carter and Wegman method you could get:
%%time # 1min 43s
hashes = HashFamily(100).draw_hashes(n)
median_pvalue(hashes, n=n)
# 0.841929288037321

Code to reproduce :

from scipy.stats.stats import pearsonr
import numpy as np
import random

_memomask = {}

def hash_function(n):
    mask = _memomask.get(n)
    if mask is None:
        random.seed(n)
        mask = _memomask[n] = random.getrandbits(32)
    def myhash(x):
        return hash(x) ^ mask
    return myhash

class HashFamily():
    r"""Universal hash family as proposed by Carter and Wegman.
    .. math::
            \begin{array}{ll}
            h_{{a,b}}(x)=((ax+b)~{\bmod  ~}p)~{\bmod  ~}m \ \mid p > m\\
            \end{array}
    Args:
        bins (int): Number of bins to hash to. Better if a prime number.
        moduler (int,optional): Temporary hashing. Has to be a prime number.
    """
    def __init__(self, bins, moduler=None):
        if moduler and moduler <= bins:
            raise ValueError("p (moduler) should be >> m (buckets)")

        self.bins = bins
        self.moduler = moduler if moduler else self._next_prime(np.random.randint(self.bins + 1, 2**32))

        # do not allow same a and b, as it could mean shifted hashes
        self.sampled_a = set()
        self.sampled_b = set()

    def _is_prime(self, x):
        """Naive is prime test."""
        for i in range(2, int(np.sqrt(x))):
            if x % i == 0:
                return False
        return True

    def _next_prime(self, n):
        """Naively gets the next prime larger than n."""
        while not self._is_prime(n):
            n += 1

        return n

    def draw_hash(self, a=None, b=None):
        """Draws a single hash function from the family."""
        if a is None:
            while a is None or a in self.sampled_a:
                a = np.random.randint(1, self.moduler - 1)
                assert len(self.sampled_a) < self.moduler - 2, "please give a bigger moduler"

            self.sampled_a.add(a)
        if b is None:
            while b is None or b in self.sampled_b:
                b = np.random.randint(0, self.moduler - 1)
                assert len(self.sampled_b) < self.moduler - 1, "please give a bigger moduler"

            self.sampled_b.add(b)

        return lambda x: ((a * x + b) % self.moduler) % self.bins

    def draw_hashes(self, n, **kwargs):
        """Draws n hash function from the family."""
        return [self.draw_hash() for i in range(n)]

def median_pvalue(hashes, buckets=100, n=1000):
    p_values = []
    for j in range(n-1):
        a = [hashes[j](i) % buckets for i in range(n)]
        b = [hashes[j+1](i) % buckets for i in range(n)]
        p_values.append(pearsonr(a,b)[1])
    return np.median(p_values)

Note that my implementation is of  Carter and Wegman is very naive (e.g. generation of prime numbers). It could be made shorter and quicker.

A: You should consider using universal hashing. My answer and code can be found here: https://stackoverflow.com/a/25104050/207661

A: The universal hash family is a set of hash functions H of size m, such that any two (district) inputs collide with probability at most 1/m when the hash function h is drawn randomly from set H.

Based on the formulation in Wikipedia, use can use the following code:
import random

def is_prime(n):
    if n==2 or n==3: return True
    if n%2==0 or n<2: return False
    for i in range(3, int(n**0.5)+1, 2):
        if n%i==0:
            return False
    return True

# universal hash functions
class UniversalHashFamily:
    def __init__(self, number_of_hash_functions, number_of_buckets, min_value_for_prime_number=2, bucket_value_offset=0):
        self.number_of_buckets = number_of_buckets
        self.bucket_value_offset = bucket_value_offset

        primes = []
        number_to_check = min_value_for_prime_number
        while len(primes) < number_of_hash_functions:
            if is_prime(number_to_check):
                primes.append(number_to_check)
            number_to_check += random.randint(1, 1000)

        self.hash_function_attrs = []
        for i in range(number_of_hash_functions):
            p = primes[i]
            a = random.randint(1, p)
            b = random.randint(0, p)
            self.hash_function_attrs.append((a, b, p))

    def __call__(self, function_index, input_integer):
        a, b, p = self.hash_function_attrs[function_index]
        return (((a*input_integer + b)%p)%self.number_of_buckets) + self.bucket_value_offset

Example usage:
We can create a hash family consists of 20 hash functions, each one map the input to 100 buckets.
hash_family = UniversalHashFamily(20, 100)

And get the hashed values like:
input_integer = 1234567890 # sample input

hash_family(0, input_integer) # the output of the first hash function, i.e. h0(input_integer)
hash_family(1, input_integer) # the output of the second hash function, i.e. h1(input_integer)
# ...
hash_family(19, input_integer) # the output of the last hash function, i.e. h19(input_integer)

If you are interested in the universal hash family for string inputs, you can use the following code. But please note that this code may not be the optimized solution for string hashing.
class UniversalStringHashFamily:
    def __init__(self, number_of_hash_functions, number_of_buckets, min_value_for_prime_number=2, bucket_value_offset=0):
        self.number_of_buckets = number_of_buckets
        self.bucket_value_offset = bucket_value_offset

        primes = []
        number_to_check = max(min_value_for_prime_number, number_of_buckets)
        while len(primes) < number_of_hash_functions:
            if is_prime(number_to_check):
                primes.append(number_to_check)
            number_to_check += random.randint(1, 1000)

        self.hash_function_attrs = []
        for i in range(number_of_hash_functions):
            p = primes[i]
            a = random.randint(1, p)
            a2 = random.randint(1, p)
            b = random.randint(0, p)
            self.hash_function_attrs.append((a, b, p, a2))

    def hash_int(self, int_to_hash, a, b, p):
        return (((a*int_to_hash + b)%p)%self.number_of_buckets) + self.bucket_value_offset

    def hash_str(self, str_to_hash, a, b, p, a2):
        str_to_hash = "1" + str_to_hash # this will ensure that universality is not affected, see wikipedia for more detail
        l = len(str_to_hash)-1

        int_to_hash = 0
        for i in range(l+1):
            int_to_hash += ord(str_to_hash[i]) * (a2 ** (l-i))
        int_to_hash = int_to_hash % p
        return self.hash_int(int_to_hash, a, b, p)

    def __call__(self, function_index, str_to_hash):
        a, b, p, a2 = self.hash_function_attrs[function_index]
        return self.hash_str(str_to_hash, a, b, p, a2)


text:
Q: Flash Player hijacked by Mac .app publish I published my Flash AS3 game as a Mac app and now any swf opened runs my game concurrently behind the intended swf!
Any idea what happened, or how to fix?
I have been selling these games, but haven't had any support issues relating to this, so I think it's a local problem...?

A: Check your mime setting for .SWF files.  Select a .swf file in your finder and press command+i, or go to the file menu and choose "Get info"
Under the part that says "Open With" I think you will find it is using your published game to open the swf.  If this is the case you can change this back to Flash Player and "Change All".
Otherwise, ooooo nice bug ^_^


text:
Q: Hamburger icon not opening navigation drawer When i open my app and click on the hamburger icon, it is does not open the navigation drawer. But when i swipe from the edges it is opening. Also the drawer responds to hamburger icon click events after the swipe action.
I tried every solution on stackoverflow but couldn't resolve the issue. Please someone help. Thanks in advance.
XML Code:
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="start"
tools:context=".MainActivity">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/activity_main">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:title="Nexzen"
                app:titleTextColor="@color/white"
                android:background="@color/dark_green"/>

    </com.google.android.material.appbar.AppBarLayout>

    <com.google.android.material.tabs.TabLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tabLayout"
        android:background="@color/dark_green"
        app:tabTextColor="@color/white"
        app:tabIndicator="@color/receive_message"
        app:tabSelectedTextColor="@color/receive_message"
        android:layout_below="@id/appBarLayout"/>

    <androidx.viewpager2.widget.ViewPager2
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewPager"
        android:layout_below="@id/tabLayout"/>

</RelativeLayout>

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:id="@+id/navmenu"
    android:visibility="gone"
    app:menu="@menu/drawer_menu"
    app:itemTextColor="@color/text_color"
    app:itemIconTint="@color/text_color"
    app:headerLayout="@layout/nav_header"
    android:layout_gravity = "start" />

</androidx.drawerlayout.widget.DrawerLayout>

Activity code :
@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            binding = ActivityMainBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());

            setSupportActionBar(binding.toolbar);

            toggle = new ActionBarDrawerToggle(this, binding.drawer, binding.toolbar, R.string.open, R.string.close);
            toggle.getDrawerArrowDrawable().setColor(getColor(R.color.white));
            toggle.setDrawerIndicatorEnabled(true);
            toggle.setDrawerSlideAnimationEnabled(true);
            binding.drawer.addDrawerListener(toggle);
            toggle.syncState();

        }

    @Override
        protected void onStart() {
            super.onStart();
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            return super.onCreateOptionsMenu(menu);
        }

        @Override
        public boolean onOptionsItemSelected(@NonNull MenuItem item) {
            if (toggle.onOptionsItemSelected(item)) {
                binding.drawer.openDrawer(GravityCompat.START);
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        protected void onPostCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            toggle.syncState();
        }

        @Override
        public void onBackPressed() {
            super.onBackPressed();
            finish();
        }

A: Ensure you haven't set the visibility of the NavigationView in the fragment to invisible or gone. This was the cause for me.
Swiping must make the navigation drawer visible. Clicking the hamburger button does not.


text:
Q: What url to post django-registration form to? I am trying to set up the most trivial example using django-registration. I am using the one-step work flow.
I have a very basic view for registration when I go to /account/register. If I fill username and password fields, and submit the registration form then I end up back on the same registration page! No errors are flagged (but I can make them flag so they seem to be working).
I can see using the admin tools that no user has been registered. I suspect I am posting the form to the wrong url. Here is what I think is the relevant code. Please help!
Textbook url mappings:
urlpatterns = [
    url(r'^register/$',
        views.RegistrationView.as_view(),
        name='registration_register'),
    url(r'^register/closed/$',
        TemplateView.as_view(
            template_name='registration/registration_closed.html'
        ),
        name='registration_disallowed'),
    url(r'', include('registration.auth_urls')),
]

My template:
{% block body_block %}

Register Here

        <form method="post" action=".">
                {% csrf_token %}
                {{ form.as_p }}

                <input type="submit" value="Submit" />
        </form>
{% endblock %}

A: It turns out everything was ok. I was entering a password judged to be too weak. The error was flagged differently to invalid email address or invalid username and appeared as an extra bullet point on the password requirements (there were four already!) so I didn't spot it.


text:
Q: vue.js real time form not working with dynamic rows Hi there fellow stackers, I recently came upon a problem that is quite literally halting my progress on the entire project.
Let's get to it; What needs to be done?
Basically, I have a dynamic form saying Label and Internal Name. I have the section ready where you can click the add button to add a new label and internal name input in the table, however, that was just part 1.
Part 2 is that the internal name input is not filled independantly; it is a realtime form which is supposed to take the input placed in label. So if I type "Hello world" in label, there should automatically also be a "hello world" in the internal name input box without me having typed there at all.
As soon as I started combining two vue.js fiddles, things started to go wrong. These fiddles are:
Dynamic form: https://jsfiddle.net/7nxhygLp/
Realtime form: https://jsfiddle.net/gtmmeak9/118/
Here is the HTML code for my page where it is displayed (includes the vue.js)
=========================================================

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>M06 Property-create</title>

{!! Form::open(array('route' => 'property.store')) !!}

@include('properties.form')

{!! Form::close() !!}

Return

==========================================================
And here is the included form that at this moment is broken
==========================================================
{!! Form::label('field_type_id', Lang::get('misc.fieldtype_name')) !!}
{!! Form::select('field_type_id', $fieldTypes) !!}

                    <button type="button" class="button btn-primary" @click="addRow">Add label</button>

                    Label
                    Internal Name

                            <input name="label" id="label" type="text" v-model="row.label">
                            <input name="internal_name" id="internal_name" type="text" v-model="row.internal_name">
                            <button type="button" class="button btn-primary" @click="removeRow(index)">Remove</button>
                            <comp1: prop.sync="input"></comp1>
                            <comp2: prop.sync="input"></comp2>

{!! Form::label('property_group_id', Lang::get('misc.group_name')) !!}
{!! Form::select('property_group_id', $groups) !!}

{!! Form::label('description', Lang::get('misc.description')) !!}
{!! Form::textarea('description', null, ['class' => 'form-control', 'required']) !!}

{!! Form::submit(Lang::get('misc.save'), ['class' => 'btn btn-success', 'id' => 'btn-save']) !!}

A: Okay I wish to provide an update on the situation; I worked a bit in JSFiddle and this is the outcome:
Now on JSFiddle it works fine; in my browser I get Vue.js warnings whenever I hit a key on my keyboard whilst entering in Label. That looks like: http://prntscr.com/cwp56f .
JSFiddle with these code snippets: https://jsfiddle.net/epdo2prz/
VIEW

  Label
  Internal Name

  <comp1 :prop.sync="input"></comp1>
  <comp2 :prop.sync="input"></comp2>
  Remove

<button class="button btn-primary" @click="addRow">Add row</button>

MODEL
var Component1 = Vue.extend({
template: '<input type="text" v-model="prop"/>',
props: ['prop']
})

var Component2 = Vue.extend({
template: '<input type="text" v-model="prop"/>',
props: ['prop']
})

var app  = new Vue({
el: "#app",
data: {
rows: [
  {label: "",internal_name: ""}
]
},
methods:{
addRow: function(){
  this.rows.push({label:"",internal_name:""});
},
removeRow: function(row){
  //console.log(row);
  this.rows.$remove(row);
}
},
components: {
    'comp1': Component1,
  'comp2': Component2
}
});


text:
Q: difference between two registry locations for HKLM\SOFTWARE\Microsoft\Windows\ and HKLM\SOFTWARE\Microsoft\Windows NT\ What is the difference between the two registry locations
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon:LegalNoticeText
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System:LegalNoticeText

While my question is asking about the LegalNoticeText i am more interested in the difference between the HKLM\SOFTWARE\Microsoft\Windows NT\ and HKLM\SOFTWARE\Microsoft\Windows\. I have searched online and can't find any solid information to explain why I have duplicate keys in two places and why CIS benchmarks suggest only the HKLM\SOFTWARE\Microsoft\Windows\ over the other one.

A: I don't have hard evidence or sources for this, but just my personal experience.
These are not duplicate keys. Yes, they exists in two places, but have different purposes and are both valid and one shouldn't be preferred over the over.
From my experience the Windows NT key was more used in the old days when the OS was actually called Windows NT, so 1993 to 1999, most core OS settings from the time can be found there and never changed after the renaming to Windows 2000. But newer settings were mostly added under the Windows Key, but if a sub-key already existed under Windows NT new values where added here too.
Just think of it as a historical fact, there are two locations for Windows OS settings.
In you specific case I think the LegalNoticeText under Windows NT is the system default, the one under Policies is used for Group Policies to overwrite that default.


text:
Q: Is a force acting on a freely falling body? Albert Einstein in his equivalence principle stated that a freely falling body does not experience force, but if I let a ball free fall its velocity increases periodically (it accelerates). How is this possible without a force being involved?

A: The reason the object appears to fall is from curved space time.  It's not that the object is accelerating towards the Earth but instead space time it self curves towards the Earth.  This means that strait lines through space time look curved from the reference frame of objects in micro gravity.  The ground actually accelerates up at $9.81\ \mathrm{m/s^2}$ through space time but the Earth does not expand because space time curves in such a way that it cancels out the effect of the acceleration of the ground on the size of the Earth.


text:
Q: Running a command as the first command in subprocess I have a function that will open a terminal:
def open_next_terminal():
    import subprocess

    def rand(path="/tmp"):
        acc = string.ascii_letters
        retval = []
        for _ in range(7):
            retval.append(random.choice(acc))
        return "{}/{}.sh".format(path, ''.join(retval))

    file_path = rand()
    with open(file_path, "a+") as data:
        data.write(
'''
#!/bin/bash
"$@"
exec $SHELL
'''
        )
    subprocess.call(["sudo", "bash", "{}".format(file_path)])
    return file_path

I want to run a command in this newly opened terminal before anything is done in it. For example:
subprocess.call(["sudo", "bash", "{}".format(file_path)]) #<= is called
ls #<= is run
 #<= some output of files and folders
root@host:~#  #<= the shell is now available

Does subprocess allow a way for me to run a "first command" during the initialization of the shell?

A: Simply pass the shell=True parameter to subprocess.call, and you can run multiple commands (delimited by semicolons or newlines) as a single string.
subprocess.call('your_first_command.sh; your_real_work.sh', shell=True)


text:
Q: DirectShow DMO Color Converter I am having an issue with connecting the Color Converter DMO object in graphedit (graphstudio, and in code). It works on one machine and turns green in graphedit, however on the machine I have to demo the program on it will not connect! I've looked at sdks, installs, and the machine should mimic my machine.
I also noticed that I can reregister the filter on my machine with regsvr however it fails on the other machine.
Any ideas as to what the culprit could be?

A: *

*Why would you want to re-register it, it is either a core OS component, or not available at all

*It is not a filter, it is dual interface DMO/DSP and while it is available within DirectShow through DMO Wrapper Filter, this use scenario is not guaranteed to work out smoothly and you possibly have to workaround issues.

Having wrapped it through DirectShow.NET library, the number of issues might increase, so you have to gather and provide more details about the errors on the way (HRESULTs etc).


text:
Q: Why doesn't this concat work? maybe I am misunderstanding concat?
why doesn't this code output also "B"
I just get an output "A"
Shouldn't concat work like this:
RACSignal *signal = [RACSignal createSignal:^ RACDisposable * (id<RACSubscriber>  subscriber) {
    [subscriber sendNext:@"A"];
    return nil;
}];

signal = [signal concat:[RACSignal createSignal:^ RACDisposable * (id<RACSubscriber> subscriber) {
    [subscriber sendNext:@"B"];
    return nil;
}] ];

signal= [signal doNext:^(id x){
    NSLog(@"doNext  %@",x);
}];

signal= [signal flattenMap:^RACStream *(id value) {
    NSLog(@"flattenMap %@", value);
   return [RACSignal return:value];
}];

signal=[signal doNext:^(id x){
    NSLog(@"doNext after flattenMap %@",x);
}];

[signal subscribeNext:^(id x) {
    NSLog(@"subscribeNext  %@", x);
}];

A: Your first signal never completes. If you call [subscriber sendCompleted] after calling [subscriber sendNext:@"A"], then you'll find -concat: does what you expect.


text:
Q: Getting undefined method `name' for "actionmailer":String when installing Webistrano When I try and run a RAKE on Webistrano I get the following error:
undefined method `name' for "actionmailer":String`

I am a not proficient in Ruby and RoR but I have installed and played about with plenty of applications before and I can't find what the issue is.
The command I am running is:
RAILS_ENV=production rake db:migrate --trace

Which produces the below:
I would really like to know the best way to diagnose and fix this issue and issues like it in the future.
(in /srv/www/webistrano)
WARNING: 'require 'rake/rdoctask'' is deprecated.  Please use 'require 'rdoc/task' (in RDoc 2.4.2+)' instead.
at /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/rdoctask.rb
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
undefined method `name' for "actionmailer":String
/srv/www/webistrano/vendor/rails/railties/lib/rails/gem_dependency.rb:268:in `=='
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:217:in `==='
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:217:in `block in matching_specs'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:411:in `block in each'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:410:in `each'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:410:in `each'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:216:in `find_all'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:216:in `matching_specs'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:238:in `to_specs'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:256:in `to_spec'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems.rb:1231:in `gem'
/srv/www/webistrano/vendor/rails/railties/lib/rails/gem_dependency.rb:73:in `add_load_paths'
/srv/www/webistrano/vendor/rails/railties/lib/initializer.rb:301:in `block in add_gem_load_paths'
/srv/www/webistrano/vendor/rails/railties/lib/initializer.rb:301:in `each'
/srv/www/webistrano/vendor/rails/railties/lib/initializer.rb:301:in `add_gem_load_paths'
/srv/www/webistrano/vendor/rails/railties/lib/initializer.rb:132:in `process'
/srv/www/webistrano/vendor/rails/railties/lib/initializer.rb:113:in `run'
/srv/www/webistrano/config/environment.rb:16:in `<top (required)>'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
/srv/www/webistrano/vendor/rails/activesupport/lib/active_support/dependencies.rb:156:in `block in require'
/srv/www/webistrano/vendor/rails/activesupport/lib/active_support/dependencies.rb:521:in `new_constants_in'
/srv/www/webistrano/vendor/rails/activesupport/lib/active_support/dependencies.rb:156:in `require'
/srv/www/webistrano/vendor/rails/railties/lib/tasks/misc.rake:4:in `block in <top (required)>'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `block in execute'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `each'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `execute'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/usr/local/lib/ruby/1.9.1/monitor.rb:190:in `mon_synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:176:in `block in invoke_prerequisites'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:174:in `each'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:174:in `invoke_prerequisites'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:157:in `block in invoke_with_call_chain'
/usr/local/lib/ruby/1.9.1/monitor.rb:190:in `mon_synchronize'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:144:in `invoke'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:116:in `invoke_task'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block (2 levels) in top_level'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `each'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block in top_level'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `top_level'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `block in run'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:133:in     `standard_exception_handling'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/bin/rake:33:in `<top (required)>'
/usr/local/bin/rake:23:in `load'
/usr/local/bin/rake:23:in `<main>'
Tasks: TOP => db:migrate => environment

When I run ruby -v I get the following:
ruby 1.9.1p376 (2009-12-07 revision 26041) [i686-linux]

A: I had this problem.
The solution is to downgrade rubygems to a version you support.
I needed version 1.3.5 (for rails 2.3.5)
So you need to do:

gem install rubygems-update -v 1.3.5
update_rubygems --version=1.3.5

And now rake should work.

A: This worked for me.
rvm rubygems 1.6.2


text:
Q: SQL initcap on text[] I am trying to uppercase all the words in an array of text in my table:
update locations
set aka  = initcap(aka)

But initcap() doesn't support text arrays. How can I achieve the same effect?

A: Cast to text and back:
UPDATE locations
SET    aka = initcap(aka::text)::text[]
WHERE  aka IS DISTINCT FROM initcap(aka::text)::text[];

But don't touch rows that wouldn't change, to make it cheaper. See:

*

*How do I (or can I) SELECT DISTINCT on multiple columns?
I assume you are aware the initcap() does not exactly "uppercase" strings. It ...

Converts the first letter of each word to upper case and the rest to lower case.


text:
Q: How to merge elements in a matrix x = [1 2 3 4 5
     1 2 3 0 0];

I want to get off all zeros and merge the two rows
newx = x(:,1) + x(:,2)(nonzeros)
     = [1 2 3 4 5 1 2 3];

A: nonzeros will give you nonzeros in a column vector, you just have to orient the original matrix properly and transpose into a row vector (if that's what you want):
>> newx = nonzeros(x.').'
newx =

   1   2   3   4   5   1   2   3

A: newx=x.';        %Taking Transpose
% Converting the given matrix into a column vector and then taking transpose again
% (since you require answer as a row vector)
newx=newx(:).' ;
newx(newx==0)=[]  %Removing zeros

or  using reshape:
newx = reshape(x.',1,[])
newx(newx==0)=[]  %Removing zeros

Result:
newx =

     1     2     3     4     5     1     2     3


text:
Q: Cannot install npm package in a mounted directory My idea is to use docker container for building js and css assets separately from an app. I have code at the host machine and I'm trying to mount the directory with my code as volume to docker container. But in the Dockerfile when I do RUN npm install sematic-ui --save it doesn't change anything in the directory I'm trying to mount.
Is the mounted volume available at all at the building process or should I install npm packages only when I run image?
Also what is the best practice in my case?
EDIT:
I simplified the case to show an example. Here are my files.
docker-compose.yml
version: '3'
services:
 web:
  build: .
  volumes:
    - ./vol:/root/test

Dockerfile
FROM debian:9
WORKDIR /root/test
RUN touch index.html
CMD /bin/sh

Then I do docker-compose build.
I expect to see the index.html in the vol directory on the host. Why this doesn't happen? As I noticed some docker images could change the host's filesystem during build. But I couldn't.

A: When you mount a volume, it replaces everything in the directory to which you are mounting it in the container. Whatever you have in /root/test will be replaced with your host ./vol directory.

Also I'm not sure this would work anyway because when these lines happen:
WORKDIR /root/test
RUN touch index.html

the /root/test directory doesn't exist. I'm not sure where Docker is putting the index.html. Typically I will RUN mkdir -p /root/test to ensure the container path is explicitly created.


text:
Q: How do I align the text inside list elements when styling with TailwindCSS Typography? I'm re-styling my personal blog using TailwindCSS Typography plugin. The index page lists all the posts I've written in the format yyyy-mm-dd - title. My problem is that - title is not aligned in the same column and moves left or right depending on the date.
Here is a minimal HTML example to reproduce the problem:

    <title>Testing Tailwind CSS text alignment</title>

Programming

2020-08-22 - Blog Post Title 1

2018-12-15 - Blog Post Title 2

2012-02-23 - Blog Post Title 3

2011-08-07 - Blog Post Title 4

Here, you will see that the - in the second item (date: 2018-12-15) is misaligned. How does one fix this? I've tried a bunch of different techniques which all failed, so I'm asking here in the hopes someone can help.

A: This has not much to do with tailwind or the plugin. It is caused by the fact that most used fonts are proportional. So the 'i' takes less space than the 'w'. There are several options to align the text.
You could use an monospaced font (like in the code block), but usually these not quite nice. To show this, I have used the pre tag in the code snippet, in tailwind you can use the class font-mono.
A better solution is to use a table, so you will have real aligned columns. So that even when the number of characters is different, the text is still aligned. Be aware that the tailwind typography will also style the table, which usually is a good thing, but maybe not in this situation.

    <title>Testing Tailwind CSS text alignment</title>

Table

2011-01-11	 - 	Blog Post Title 1

20-8-12	 - 	Blog Post Title 2

2014-3-18	 - 	Blog Post Title 3

2020-08-22	 - 	Blog Post Title 4

Monospaced

2011-01-07 - Blog Post Title 4

2018-08-07 - Blog Post Title 4

2013-04-07 - Blog Post Title 4

2022-06-07 - Blog Post Title 4

Hope this helps.


text:
Q: Need help getting output from Telnet to array in Perl First I want to apologize for such a silly question but I'm quite new to scripting.
What I'm attempting to do:
At my office, I'm attempting to automate the ability to factory reset switches. Its testing equipment for developers not production equipment fyi. I'm trying to dump a list of files from the telnet prompt of the switch into an array and then filter through them to keep our images and delete the rest.
The constants and variables of the switch: the switch prompt for this section is =>, the files both do and don't have extensions, folders are outputted as foo\
My question: The sub isn't properly issuing the rm command, it works in a test (printing the value) but not in the actual deletion script.
New Update:
I know it looks like I abandoned this question, but I didn't! I've been monkeying around with this problem for the last month and I've achieved a major bit of success. I've been able to get my data into my initial array (yes I have 2, more on that in a bit). It will process the array and delete the contents except those I want to keep.
#!/usr/bin/perl

$| = 1;

use Net::Telnet;
use strict;
use CGI;
use warnings;

my $junk;
my $telnet;
my @array;

#establish connection
$telnet = new Net::Telnet (Timeout=> 10,
                           Errmode=> 'return',
                           Port   => '2037');

$telnet->open('trn-13-mrv-con-07');
$telnet->put(chr(13));

#clear out buffered output for array to grab
$junk = $telnet->cmd(string => 'ls', prompt => '/=>/');
#array grabbing
@array = $telnet->cmd(string => 'ls', prompt => '/=>/');

#determining what the values are of the array
foreach my $item (@array) {
   #removing the carriage return
   chomp ($item);
   #if it's a folder, this will shunt the to the sub
   if ($item=~ /\//) {
       subfolders ($item);
       $telnet -> print("rm $item");
   }
   #checks to see if the file is the firmware for the switch
   elsif ($item =~ /btm.swi|secondary.swi/) {
   }
   #deletes the rest
   else {
    $telnet -> print ("rm $item");
    $telnet->put(chr(13));
   }
}

sub subfolders {
 my @subfolder_contents;
 my $subfolder = $_[0];
 my ($file, $sub_junk);

 #attempting to clear out the array
 undef @subfolder_contents;
 #again grabing any cached output so array can do it's work
 $sub_junk = $telnet ->cmd(string => "ls $subfolder", prompt => '/=>/');
 #grabbing files from the folder
 @subfolder_contents = $telnet ->cmd(string => "ls $subfolder", prompt => '/=>/');

 #deleting all files in the subfolder
 foreach $file (@subfolder_contents){
  chomp ($file);
    $telnet-> print ("rm $subfolder$file");
    $telnet->put(chr(13));

 }
};

exit;

That all works wonderfully, AND this will work for the folders as well, mostly... It works on the folders if the folder is empty or has just one item in it. When it has 2 or more items in the folder it doesn't issue the command to delete the files in that folder correctly.
Any thoughts would be appreciated. thanks!
Thanks!

A: Answer edited due to discussion below
The problem is indeed the $t->put(chr(13));  Sending a \r causes the switch to respond with another => prompt which is now in the output. When you issue cmd, the prompt causes that first line of output to stop the reading.
empty_buffer won't work because there's nothing in the input buffer until you call cmd(); it isn't a multithreaded application. cmd() is doing a write, then reading. That's the first read from the socket that is performed. If you were using getline instead at that point you'd have the first line, and the input buffer would contain the rest (or at least most of it depending on how the socket read is done in the library)
If instead of using cmd you wrote the command manually using print or put, then used a loop and getline(), you could ignore the first => if you absolutely can't eliminate sending that \r

A: You likely want to stop capturing the echoed input. Look at cmd_remove_mode in the Net::Telnet docs.


text:
Q: Building Flex Builder projects from commandline I have several Flex Builder projects which depend on each other (both libraries and "applications", i.e. projects which generate an SWF), and want to compile them from commandline. I know there is the fb.exportReleaseBuild ant-Task, but unfortunately it doesn't work on Linux and only comes with Flex Builder.
Is there any other way to build those projects, including their dependencies, from commandline?

A: One nifty toolset is Antenae which has templates for handling nested project with various library dependencies. It's basically bunch of Ant scripts that provide quite a high level of abstraction to the whole build process.

A: Yes, use the command line compiler in the Flex SDK.  More info

A: You can use command line to compile flex projects. But you will have to enter the commands manually. Alternatively you can use ant build. Ant is available for GNU/Linux as well. Or which ever build you are comfortable with.