text:
Q: Определение пола Хочу как в ВК сделать автоматическое определение пола, но не могу понять как это реализовать. Допустим, если ставить женский пол по окончанию имени(а и я), но есть ведь имена: Любовь и другие + есть и мужские имена: Никита, Илья. Подскажите, пожалуйста, что использовать для реализации идеи?

A: Тривиальными средствами вроде проверки окончаний вы эту задачу вряд ли решите по вполне понятным причинам. Возможно, имеет смысл сделать словарь возможных имен - если речь идет о более-менее традиционных русских именах, то это может помочь - как правило в русском языке мужские и женские имена не пересекаются - возможно, я что-то забыл, но я не помню в русском языке ни одного имени, звучащего одинаково для мужчин и для женщин(за исключением уменьшительных форм типа Саша или Женя).
С другой стороны, это тоже не панацея.
Во-первых, подобный словарь должен быть достаточно большим (причем 95% его содержимого не будет использоваться вообще, либо будет, но редко. Скажем, вряд ли среди ваших пользователей будет много Никандров или Ратиборов)
Во-вторых, если в вашей системе возможны уменьшительные имена, то довольно сложно сказать, является ли условный(ая) Саша мальчиком или девочкой.
В-третьих, с иностранными именами тоже далеко не все гладко - скажем, в английском не редкость, что одно и то же имя может принадлежать мужчине или женщине. А уж если брать восточные имена (китайские например или хотя бы армянские), то там и вовсе черт ногу сломит.
В-четвертых, ничто не мешает пользователю вместо имени ввести вообще что попало, или какой-то ник. Тут в некоторых случаях даже человеческий мозг будет бессилен.
Хотя, с другой стороны, если в вашей системе не предполагается наличие пользователей из Кореи, и в сумеете их убедить писать исключительно имена, а не ники, то с более-менее успешно это может сработать (но все же не стоит забывать что и в этом случае никто ничего не гарантирует)
Можно также попробовать анализировать не тоьлко имя, но и фамилию - женские фамилии часто заканчиваются на "а", но тут никакие словари не помогут - если имена еще как-то можно перечислить, то фамилии могут быть вообще какие угодно. Кроме того, есть куча несклоняемых фамилий типа Дуся Гвоздь или какой-нибудь Петя Иванчук, но все же анализ имени и фамилии одновременно может отсеять некоторые непонятности.
А вот с отчествами все значительно проще - в подавляющем большинстве случаев мужское отчество заканчивается на "вич", а женское на "вна". С другой стороны, отчества может и не быть вовсе, если человек иностранец, либо его не всегда указывают при регистрации.
А мораль этой истории такова: для определения пола используйте галки "М" и "Ж"

A: Проще спросить.
Не зря же все сайты спрашивают пол, вместо определения.
Как ни крути, а универсального алгоритма нет.
Можно, конечно, попробовать словарём, исключениями, анализировать сообщения на предмет определения пола автора (последнее, кстати, точно будет работать, но реализовать сложно), но везде есть вероятность ошибки.
Плюс - некоторые вообще муть пишут типа ♥ ღКсюня♥ ღ ღВивенскаяღ (реальный ник выдрал из ВК), по ней точно ничего  не определишь.

A: Можно сделать несколько критериев, например как вы уже сказали по окончанию (на ь мужских имен мало, но есть  - Олесь), плюс еще добавить словарь исключений (типа Никита, Илья). Можно просто словарь (русских имен не так уж много). Если иностранные имена, то тут все сложнее, так как иногда и человек по имени определить пол не сможет, не говоря уж об алгоритме.


text:
Q: ArgumentError: wrong number of arguments (1 for 2) I'm very new to Rails, MVC, and CRUD, and I'm trying to use the update method to change the amount of votes on a post. I have the following code in my Posts Controller update method:
def update
    @post = Post.find(params[:id])

    if params[:vote] == 'up'
        @post.update_column(:ups => @post[:ups] + 1)
    elsif params[:vote] == 'down'
        @post.update_column(:downs => @post[:downs] + 1)
    end

    flash[:notice] = "Thanks for voting! This helps us determine important issues in our schools."

    redirect_to 'Posts#index'
end

and I have the following code in my routes.rb:
OpenMCJC::Application.routes.draw do
  root :to => 'posts#index'
  resources :posts
  match '/posts/:id/:vote', :to => 'posts#update'
end

After navigating to "/posts/3/up", it throws the following error:
ArgumentError in PostsController#update

wrong number of arguments (1 for 2)

The request parameters according to the page are as such:
{"id"=>"3",
"vote"=>"up"}

Can you help me figure out what went wrong?

A: As Mischa pointed out, update_column takes two arguments. However, I would discourage you from using this method. First, it skips validations which may not be what you want. Second, Rails has built-in methods for incrementing or decrementing values. In your case, you could change your controller method to something like this:
if params[:vote] == 'up'
  @post.increment(:ups)
elsif params[:vote] == 'down'
  @post.increment(:downs)
end

A: update_column takes two arguments. You are only passing one.
Instead of:
@post.update_column(:ups => @post[:ups] + 1)

Try:
@post.update_column(:ups, @post[:ups] + 1)

This may seem like two arguments:
:ups => @post[:ups] + 1

but it's actually one hash.
With the more commonly used update_attributes, you can pass a hash:
@post.update_attributes(:ups => @post[:ups] + 1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why use std::vector instead of realloc? Here, in this question, it's stated that there is no realloc-like operator or function in c++. If you wish to resize an array, just just std::vector instead. I've even seen Stroustrup saying the same thing here.
I believe it's not hard to implement one. There should be a reason for not implementing one. The answers only say to use std::vector but not why it's not implemented.
What is the reason for not implementing realloc-like operator or function and preferring to use std::vector instead?

A:
What is the reason for not implementing realloc-like operator or function and preferring to use std::vector instead?

Save time. Don't chase bugs in your own code for a problem that has long been solved. Idiomatic C++ and readability. Get answers to your questions easily and quickly. Customize the realloc part by an allocator.

I believe it's not hard to implement one

That heavily depends on what you need from the template you intend to write. For a general-purpose std::vector-like one, have a look at the source code (libcxx's 3400 line vector header is here). I bet you will revise you initial assumption on the low complexity of such construct.

A: There's several advantages.

*

*Vector keeps track of its size and capacity, which means you don't have to do this yourself.

*Because the current size is part of the vector object itself, you can pass a vector (by reference or by value) without needing an additional size parameter. This is especially useful when returning a vector as the caller doesn't need to receive the size through some side-channel.

*When reallocating, vector will add more capacity than is needed to add just the element(s) requested to be added.  This sounds wasteful but saves time as fewer reallocations are needed.

*Vector manages its own memory; using vector lets you focus on the more interesting parts of your program instead of the details of managing memory, which are relatively uninteresting and tricky to get exactly right.

*Vector supports many operations that arrays don't natively support, such as removing elements from the middle and making copies of an entire vector.

A: realloc's expectation that there might be sufficient free space after the current allocation just does not fit well with modern allocators and modern programs.
(There's many more allocation going on, many allocation sizes go to a dedicated pool for that size, and the heap is shared between all the threads in a program.)
In most cases, realloc will have to move content to a completely new allocation, just like vector does. But unlike vector<T>, realloc does not know how to move elements of type T, it only knows how to copy plain data.

A: Well, as the other answers have explained nicely about the reason for using vectors, I will simply elaborate on why realloc was not implemented. For this, you need to take a look at what realloc actually does. It increases the size of the memory by intelligently using malloc() and free(). You need to understand, that though it seems to simply increase the size, it does not actually increase the size, but instead allocates another block of memory with the required size (That explains the name realloc).
Take a look at the following lines:
int* iarr = (int*)malloc(sizeof(iarr)*5);
iarr = (int*)realloc(6,sizeof(iarr));  //this is completely discouraged
//what you're supposed to do here is:
int* iarr2 = (int*)realloc(iarr,1 + sizeof(iarr));  //copies the old data to new block implicitly
//this not only saves the previous state, but also allows you to check if realloc succeeded

In C++, this can be (if it is must) achieved, by writing:
int* iarr = new int[5];
int* iarr2 = new int[6];
for(int i = 0; i < 5; i++) {
    iarr2[i] = iarr[i];
}
delete[] iarr;

The only use of realloc was to increase the memory capacity; as C arrays did not do that automatically they had to provide a mechanism to do so; which has been implicitly implemented in most of the containers, making the reason for having a realloc in the first place, moot.


text:
Q: How can I can autocomplete for my custom command, based on the name of files in another directory? This is my requirement. We have a custom Ssh command that uses ssh under the hood, but automatically provides some options based on some conditions.
For example, our developers can write Ssh example.com and it would run ssh -A -C john@example.com or it might run ssh root@example.com based on some environmental conditions.
Now, I want to provide the auto-completion for the domain names.
For example, I want the developer to type Ssh a and hit tab and automatically get api or the suggestion list.
Based on this article I learned that I can use complete.
However, I need to tell the complete to get its completion list from the name of files in a directory.
We do have a directory in which many files exist with the names of our domains:
example.com
admin.example.com
api.admin.example.com
another-domain.tld
learner.another-domain.tld
api.learner.another-domain.tld
accounts.another-domain.tld
third-domain.cctld
api.third-domain.cctld

And the files in this directory are constantly changing and updated automatically for all developers (pulled automatically from our GitHub account).
I searched and saw these questions:
Bash autocomplete: List files and directories from other directory
How to customize bash autocomplete to list the files in another directory
But to be honest, their codes are very complex, especially this answer. I realized that I can use complete -o nospace -F SshCompletionFunction Ssh to specify a function for completion.
But I don't know what to write in that function.
I would really appreciate your help.


text:
Q: Error while creating OS X Mavericks bootable USB I am running on OS X Mavericks GM and now that Mavericks has finally released, I downloaded it from App Store. I wanted to make a bootable USB of it so I followed This Tutorial but when I tried to run the command for copying the files from .app to USB I got the following error
Ankurs-MacBook-Pro:~ Ankur$ sudo /Applications/Install\ OS\ X\ Mavericks.app/Contents/Resources/createinstallmedia
--volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Mavericks.app -nointeraction
Password:
sudo: /Applications/Install OS X Mavericks.app/Contents/Resources/createinstallmedia: command not found
Ankurs-MacBook-Pro:~ Ankur$

What can I do to resolve this issue?
EDIT
Using DiskMaker X I got the same error

A: Solved it
I copied the same Install OS X Mavericks.app in a different Mac that was running on Mountain Lion 10.8.5 and tried DiskMaker X and it worked. I'm not sure but maybe the reason was that OS X Mavericks GM Build doesn't support the command that was used or maybe there's a different way to copy things on OS X Mavericks using terminal.
Update
I tried making another bootable USB using my Mac (OS X 10.8.5) with the same Install OS X Mavericks.app but failed to do so, it seems that you can only make a bootable USB on the same system that you've downloaded Mavericks on.

A: Had the same problem. Thought the file "createinstallmedia" was missing, but that wasn't the case.
Then I realised I simply needed to make it executable with the following command:
sudo chmod +x /Applications/Install\ OS\ X\ Mavericks.app/Contents/Resources/createinstallmedia

This will create the executable that DiskMaker X initially couldn't find.
After running the command above you shouldn't have the error anymore.
Hope that helps :)


text:
Q: Howto get livereload working? I'm using gulp-connect 2.0.6 to try and get livereload working,
WebSocket connection to 'ws://localhost:35729/livereload' failed: Error during WebSocket handshake: Status line contains embedded null

The line that throws that error says,
this.socket = new this.WebSocket(this._uri);

I pasted all the relative files (gulpfile.js, package.json etc.) and console output in this gist.

A: From what I can tell, it seems like you were following along with a screencast that I published on getting a D3 environment up and running with auto reload: https://www.tagtree.tv/d3-episode1-environment
I had a look at the gist. Just to make this post easier to read for everyone, I want to pull in the contents of your gulpfile.js:
Your gulpfile.js
var gulp = require('gulp'),
  connect = require('gulp-connect'),
  traceur = require('gulp-traceur'),
  sass = require('gulp-ruby-sass');

gulp.task('connect', function() {
  connect.server({
    livereload: true,
    port: 8005
  });
});

gulp.task('sass', function(){
  gulp.src('./sass/*.scss')
  .pipe(sass())
  .pipe(gulp.dest('dist/css'));
});

gulp.task('watch', function(){
  gulp.watch(['./sass/*.scss'], ['sass']);
});

gulp.task('default', ['connect', 'watch', 'sass']);

Solution
I don't know if it's strictly necessary, but what I did when I coded up the screencast, is hook up a gulp task from the watch task that calls reload on connect.
Changing the watch task
Firstly, you need to change your watch task to look like this. Note that the path uses the path from the screencast, but use the correct glob to watch files that should trigger a reload.
gulp.task('watch', function(){
    gulp.watch(['./sass/*.scss'], ['sass']);
    gulp.watch(['./dist/**/*.*'], ['reload']);
});

The reload task
The reload task calls reload on the connect module, which publishes a message on the websocket that causes the files to be reloaded, here's what my reload task looks like:
gulp.task('reload', function(){
    gulp.src('./dist/**/*.*')
    .pipe(connect.reload());
});

The final version of the gulpfile.js
For anyone else having problems with the screencast, please have a look at the final version of the gulpfile:
var gulp = require('gulp'),
    connect = require('gulp-connect'),
    traceur = require('gulp-traceur'),
    sass = require('gulp-ruby-sass');

gulp.task('connect', function(){
    connect.server({
        livereload: true,
        port: 8005
    });
});

gulp.task('reload', function(){
    gulp.src('./dist/**/*.*')
    .pipe(connect.reload());
});

gulp.task('sass', function(){
    gulp.src('./sass/*.scss')
    .pipe(sass())
    .pipe(gulp.dest('dist/css'));
});

gulp.task('traceur', function(){
    gulp.src('./scripts/*.js')
    .pipe(traceur())
    .pipe(gulp.dest('dist/scripts'));
});

gulp.task('watch', function(){
    gulp.watch(['./sass/*.scss'], ['sass']);
    gulp.watch(['./scripts/*.js'], ['traceur']);
    gulp.watch(['./dist/**/*.*'], ['reload']);
});

gulp.task('default', ['connect', 'watch', 'sass', 'traceur']);


text:
Q: How do I solve: pandoc: ...:hGetContents: invalid argument (invalid byte sequence) I'm running the following code in terminal on Mac OSX 10.6.8:
find . -name \*.html -type f -exec pandoc -o {}.md {} \;
It parses some documents, but gives me this error on quite a few:
pandoc: ./Teaching/how_16825_make-lesson-book.html: hGetContents: invalid argument (invalid byte sequence)
Any idea how to fix this?

A: Having the same problem I also see this is in the Pandoc README.html file:---

Pandoc uses the UTF-8 character encoding for both input and output. If your local character
encoding is not UTF-8, you should pipe input and output through iconv:
iconv -t utf-8 input.txt | pandoc | iconv -f utf-8

Of course you may need iconv instqalled first (Mac Osx already has it I beleive) ...

http://gnuwin32.sourceforge.net/packages/libiconv.htm Gnu Win32
https://code.google.com/p/win-iconv/  Google Win-Iconv

A: As kadeix said, this is a character encoding issue. Modifying the charset declaration in the html didn't do anything for me.
In vim to solve this issue I used: :w ++enc=utf-8

A: I get this error when i try to parse a file encoded in latin-1.
Try saving the file in utf-8 (and modify the charset declaration in the html code) before using pandoc when you get this error.


text:
Q: Do coarse moduli spaces respect Galois actions? To explain, I will use the following concrete example: Let $\mathcal{M}_g$ be the functor for the moduli problem of classifying genus $g$ smooth projective curves (taking a scheme $S$ to the set of ways that $S$ parametrizes genus $g$ curves). This, as is well known, has a coarse moduli space: $M_g$.
Let $\sigma \in Aut(\mathbb{C})$, and say that we begin with a specific $\mathbb{C}$-curve of genus $g$. This $\sigma$ may act in two ways on this curve (by act I mean turn it into a different curve, not act as meaning an automorphism):
1. By taking a fiber product over the automorphism $Spec(\mathbb{C}) \rightarrow Spec(\mathbb{C})$ (this is the usual action people use, and has nothing to do with the moduli space)
2. By letting $\sigma$ act on $M_g(\mathbb{C})$, the point corresponding to our curve, will be taken to another $\mathbb{C}$-point, which in turn corresponds to another curve.
The question is: do these two actions agree in general? Are there conditions that need to be fulfilled for this to be true?
As an aside, this is true if the moduli space is fine. For example, if the moduli of genus $g$ curves were fine (which it isn't), then the curve corresponding to $Spec(\mathbb{C})\rightarrow M_g$ will be given simply by taking the fiber product with the universal family $E_g\rightarrow M_g$. Since fiber products commute, we get that the two actions above agree. This reasoning breaks down, however, if the moduli space is not fine.

A: There are curves (with automorphisms) for which the field of definition is not the field of moduli. Concretely, there are curves $C$ with corresponding point $P \in M_g$, such that $C$ cannot be defined over $K =\mathbb{Q}(P)$, only over larger fields. That means that there are automorphisms of $\mathbb{C}$ (fixing $K$) whose action don't change $P$ but change $C$.

A: If $X$ is the coarse moduli scheme associated to a functor $F$ on schemes, then in particular, there is a natural transformation $F\to h_X$, where $h_X$ is the functor of points of $X$.
Unless I am missing something, if you apply the naturality of this transformation to the map $\mathrm{Spec}(\mathbb{C}) \to \mathrm{Spec}(\mathbb{C})$ associated to your automorphism $\sigma$, this implies that the two actions coincide in your case, since the associated map $F(\mathrm{Spec}(\mathbb{C})) \to F(\mathrm{Spec}(\mathbb{C}))$ is given by the fiber product of the curve, and the associated map $X(\mathrm{Spec}(\mathbb{C})) \to X(\mathrm{Spec}(\mathbb{C}))$ is just the action on the points.  I wish I could make the obvious 2-by-2 commutative diagram...


text:
Q: Style a embedded video for mobile version I am trying to style a video, because on the mobile version the video does not fit the screen. I have the following HTML code:

        How much is the fish?

So in order to style the video for the mobile version I did the following:
.iframe-container{
  position: relative;
  width: 100%;
  padding-bottom: 56.25%;
  height: 0;
}
.iframe-container iframe{
  position: absolute;
  top:0;
  left: 0;
  width: 100%;
  height: 100%;
}

However when I make these changes in my CSS document, it does not make any chances. I am not too sure what I do wrong here. Is it the fact that I do not select the right element? Also I have a picture of the full code which is to large to post: Full code

A: I left your HTML and CSS as it is but I changed your width in your css

.iframe-container{
  position: relative;
  max-width: 100%;
  padding-bottom: 56.25%;
  max-height: 0;
}
.iframe-container iframe{
  position: absolute;
  top:0;
  left: 0;
    max-width:100%;
  max-height: 100%;
}

        How much is the fish?


text:
Q: Geckoview Doesn't work I am working on a project using geckoview in android studio. The app keeps crashing when I reach the containing activity. using log cat I found out that it gives me the following error
    FATAL EXCEPTION: main

    Process: app, PID: 2815

  java.lang.RuntimeException: Unable to start activity ComponentInfo{project name}: android.view.InflateException: Binary XML file line #27: Binary XML file line #27: Error inflating class org.mozilla.gecko.GeckoView

I dont know how to fix this or what does it mean or what to do...
Here is my code, I hope it helps
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_page);
        Button Nav=(Button) findViewById(R.id.Nav);

        GeckoView geckoView = (GeckoView) findViewById(R.id.geckoview);

        GeckoSession session = new GeckoSession();
        geckoView.setSession(session);

        session.loadUri("http://google.com");

    }

XML
<org.mozilla.gecko.GeckoView
    android:id="@+id/geckoview"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="82dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/guideline2" />

Thank you in advance..

A: Change Geckoview in xml as below
<org.mozilla.geckoview.GeckoView
    android:id="@+id/geckoview"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="82dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/guideline2" />


text:
Q: Android Facebook API - I receive emails only for some fb accounts I have been using the Facebook SDK for Android a bit now. I have been having trouble where one of my testers could not create an account in my app using Facebook. After some debugging I figured out that for some reason when he tries to login / register the JSON object that contains the information does not come with his email. This only happens for HIS account!
Does anyone know why this could happen?
(I have included a simplified version of my login code so you can see if there is anything wrong with it that might cause it)
List<String> permissionNeeds = Arrays.asList("public_profile", "user_friends", "email");
loginButton.setReadPermissions(permissionNeeds);

loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(final LoginResult loginResult) {
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        try {
                            Log.d(TAG, object.toString()); // Has no email sometimes!
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e(TAG, String.format("Error with facebook login: %s", e.getMessage()));
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,picture,email,gender");
        request.setParameters(parameters);
        request.executeAsync();
    }

    @Override
    public void onCancel() {
    }

    @Override
    public void onError(FacebookException error) {
        Log.d(TAG, String.format("Error with facebook login: %s", error.getMessage()));
    }
});

loginButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        LoginManager.getInstance().logInWithReadPermissions(SplashActivity.this,
                Arrays.asList("public_profile", "user_friends", "email"));
    }
});

If any more information is needed, please tell me I'll be happy to add some.
Thanks!

A: So turns out that my tester had an inactive email account.
In general you should never be counting on every Facebook user having an email address.


text:
Q: How to improve the nonlinear fit to a data set Some data to begin with
data = {{0, 0}, {0.05, 0.5786}, {0.5, 0.7202}, {1, 0.7902}, {2, 0.8978},
        {3, 0.9246}, {4, 0.9620}, {5, 0.993}, {6, 1}, {7, 1}, {8, 1},
        {9, 1}, {10, 1}};

I know from theory that the best fist to such data is the formula $0.5(1 + tanh(a + bx))$.
So I use the NonlinearModelFit
fit = NonlinearModelFit[data, 0.5*(1 + Tanh[a*x + b]), {a, b, c}, x]

which gives

where the dots correspond to the data, while the solid line to the fit. As we can see the result is not so good.
So, is there a way to obtain a better fit to my data? When I say better I mean that the solid fit line should pass very close from all given data points.

A: The suggestion give by george2079 works quite well.
workingData = Rest @ data;
fit = NonlinearModelFit[workingData, c (1 + Tanh[a x + b]), {a, b, c}, x]
Plot[fit[x], {x, 0, 10},
  PlotRange -> {0, 1.03},
  Epilog -> {PointSize[Medium], Point[workingData]}]


text:
Q: Postsharp not compiling in release mode I'm using Postsharp express and everything is working properly when I'm using it in debug mode (x86).
When I set it to Release mode the compiler cannot find this attribute SafeForDependencyAnalysis
and I get an error saying:

Error CS0246  The type or namespace name 'PostSharp' could not be found
  (are you missing a using directive or an assembly reference?)

The only thing I changed was switching from Debug to Release mode. How can I fix that?
I'm using the latest version of Postsharp 4.2.22.0
Thanks.


text:
Q: How do I make uwp app size smaller it should be simple I am trying to make a very simple UWP app smaller than default but i can't.
How to do this?
As you can see in the image the windows calculator app and the notepad is smaller in width than my app. I can't make it smaller???
enter image description here
I have looked on google and this site but can't find any answers.
It should be simple???
If this has been answered please guide me to the answer.
Thanks

A: You could use the ApplicationView.PreferredLaunchViewSize Property to set the size of your UWP APP.

*

*Set a minimum value for the size using ApplicationView.SetPreferredMinSize(Size) Method.

*Set a value for the size of the app as you want by setting the ApplicationView.PreferredLaunchViewSize Property

*Apply the size by setting ApplicationView.PreferredLaunchWindowingMode Property.

Please refer to the following code:
        public MainPage()
    {
        this.InitializeComponent();

        //set minimized size
        ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(200, 200));
        // change to smaller size
        ApplicationView.PreferredLaunchViewSize = new Size(400, 400);
        ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
    }


text:
Q: How to run-app in Grails 4.0.3 app ignoring unavailable RabbitMQ Everytime I try to run my grails app and RabbitMQ is unavailable, my application does not go up (start). It shows me the error and I have to fix it before running again.
But RabbitMQ is not essential, I would like it runs even if Rabbit MQ is unavailable.
Does anyone know a way for my application to show me only a WARN informing tha Rabbit is not available and go up regardless?
Thank you
Alfredo
java.net.ConnectException: Conexão recusada (Connection refused)
        at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
        at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
        at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
        at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.base/java.net.Socket.connect(Socket.java:609)
        at com.rabbitmq.client.impl.SocketFrameHandlerFactory.create(SocketFrameHandlerFactory.java:60)
        at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:62)
        at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:156)
        at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1095)
        at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1054)
        at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1012)
        at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1201)
        at com.rabbitmq.client.ConnectionFactory$newConnection$6.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:127)
        at com.budjb.rabbitmq.connection.ConnectionContextImpl.start(ConnectionContextImpl.groovy:132)
        at com.budjb.rabbitmq.RabbitManagedContext$start$0.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:119)
        at com.budjb.rabbitmq.connection.ConnectionManagerImpl.start(ConnectionManagerImpl.groovy:194)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:101)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
        at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:351)
        at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:64)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:156)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:168)
        at com.budjb.rabbitmq.connection.ConnectionManagerImpl$_start_closure4.doCall(ConnectionManagerImpl.groovy:179)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:101)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:323)
        at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:263)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1041)
        at groovy.lang.Closure.call(Closure.java:405)
        at groovy.lang.Closure.call(Closure.java:421)
        at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2296)
        at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2281)
        at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2322)
        at org.codehaus.groovy.runtime.dgm$186.invoke(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:244)
        at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:127)
        at com.budjb.rabbitmq.connection.ConnectionManagerImpl.start(ConnectionManagerImpl.groovy:177)
        at com.budjb.rabbitmq.RabbitManager$start$1.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:119)
        at com.budjb.rabbitmq.RabbitContextImpl.startConnections(RabbitContextImpl.groovy:201)
        at com.budjb.rabbitmq.RabbitContextImpl.start(RabbitContextImpl.groovy:82)
        at com.budjb.rabbitmq.RabbitContext$start$0.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:119)
        at com.budjb.rabbitmq.RabbitContextProxy.start(RabbitContextProxy.groovy:65)
        at com.budjb.rabbitmq.RabbitContext$start$0.call(Unknown Source)

Above, the response of the Grails 4.0.3 application if RabbitMQ is not available.
Below, my application.yml
grails:
    profile: rest-api
    codegen:
        defaultPackage: plataforma.msid.grails4
    gorm:
        autowire: true
        reactor:
            # Whether to translate GORM events into Reactor events
            # Disabled by default for performance reasons!
            events: false
info:
    app:
        name: '@info.app.name@'
        version: '@info.app.version@'
        grailsVersion: '@info.app.grailsVersion@'
spring:
    jmx:
        unique-names: true
    main:
        banner-mode: "off"
    groovy:
        template:
            check-template-location: false
    devtools:
        restart:
            additional-exclude:
                - '*.gsp'
                - '**/*.gsp'
                - '*.gson'
                - '**/*.gson'
                - 'logback.groovy'
                - '*.properties'
management:
    endpoints:
        enabled-by-default: true
    endpoint:
        health:
            show-details : always
---
grails:
    mime:
        disable:
            accept:
                header:
                    userAgents:
                        - Gecko
                        - WebKit
                        - Presto
                        - Trident
        types:
            json:
              - application/json
              - text/json
            hal:
              - application/hal+json
              - application/hal+xml
            xml:
              - text/xml
              - application/xml
            atom: application/atom+xml
            css: text/css
            csv: text/csv
            js: text/javascript
            rss: application/rss+xml
            text: text/plain
            all: '*/*'
    urlmapping:
        cache:
            maxsize: 1000
    controllers:
        defaultScope: singleton
    converters:
        encoding: UTF-8

---
hibernate:
    allow_update_outside_transaction: true
    cache:
        queries: false
        use_second_level_cache: false
        use_query_cache: false
dataSource:
    pooled: true
    jmxExport: true
    driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
    logSql: true

environments:
    development:
        dataSource:
            dbCreate: update
            dialect: org.hibernate.dialect.SQLServer2017Dialect
            url: jdbc:sqlserver://ip:port;databaseName=BD_DOC_DIGITAL_CMB_PLATAFORMA;domain=DMZHLG
            username: usr
            password: 'dddd'
        cmbaut:
            gettingNewTokenUrl: 'https://hml.project/plataforma/cmbaut/api/v1/auth/refresh?grant_type=refresh_token&refresh_token='
            gettingUserId: 'https://hml.project/plataforma/cmbaut/api/v1/parts/$partId/users/$cpf'
        rabbitmq:
            connections:
                - name: main
                  host: 192.168.xxx.xx
                  port: 5672
                  username: cmbid
                  password: xxxxx
                  virtualHost: "/plataforma"
        grails:
            plugin:
                springsecurity:
                    rest:
                        token:
                            storage:
                                jwt:
                                    secret: 'xxxx'

server:
servlet:
contextPath: /cmbid
port: 8081
max-http-header-size: 65536


text:
Q: Aligning modal content box to center of any screen Hi i have created login form and need to display that box to center of any screens.Gap should be equal on all the sides in any of the screens.Tried with postion:absolute display flexbut not working.

            <form action="" role="form">

                        <input type="text" class="form-control" placeholder="User Name" />

                        <input type="password" class="form-control" placeholder="Password" />

                    <button type="submit" class="btn btn-success btn-lg">Login</button>
                    forget Password

            </form>

Style.css
.modal-content{
        background-color: #fff;
    }
    .btn-link{
        color:white;
    }
    .modal-heading h2{
        color:#ffffff;
    }

A: .modal-dialog{
position:absolute;
left:50%;
width:400px;
top:50%;
transform:translate(-50% , -50%)
}

add this and it should work!

A: You can making it with display block, margin auto and text align on modal-dialog

.modal-content{
        background-color: #fff;
    }
    .btn-link{
        color:white;
    }
    .modal-heading h2{
        color:#ffffff;
    }

    .modal-dialog {
      width:400px;
    display: block;
    margin: 0px auto;
    text-align:center;
}

            <form action="" role="form">

                        <input type="text" class="form-control" placeholder="User Name" />

                        <input type="password" class="form-control" placeholder="Password" />

                    <button type="submit" class="btn btn-success btn-lg">Login</button>
                    forget Password

            </form>


text:
Q: Vectors that form basis in $\mathbb{R}^3$ and transition matrix
Consider the following set of vectors in $\mathbb{R}^3:$
$u_0 = (1,2,0),~ u_1 = (1,2,1), ~u_2 = (2,3,0), ~u_3 = (4,6,1)$
Explain why each of the two subsets $B_0 = \left\{u_0, u_2,
 u_3\right\}$ and $B_1 = \left\{u_1, u_2, u_3\right\}$ forms a basis of
   $\mathbb{R}^3$. If we write $[\mathbf{x}]_0$ and $[\mathbf{x}]_1$ for the coordinates of the vector $\mathbf{x}$ in terms of these two basis, find the precise transition matrix which inter-relates these two sets of coordinates. If $\mathbf{x} = 4\mathbf{e}_1+4\mathbf{e}_3$, what are $\mathbf [\mathbf{x}]_0$ and $[\mathbf{x}]_1$?

Writing the vectors of the subset $B_0$ as the columns of a matrix we have:
$\mathbf{A}_0: = \begin{pmatrix}
1&2&4  \\
2&3&6  \\
0&0 &1
\end{pmatrix} \to \begin{pmatrix}
1&2&4  \\
0&-1&-4  \\
0&0 &1
\end{pmatrix} \implies \det(\mathbf{A}_0) =(1)(-1)(1) =  -1 $
As the columns of a $3 \times 3$ matrix whose determinant is non-zero, these vectors form a basis for $\mathbb{R}^3.$
Similarly, writing the vectors of the subset $B_1$ as the columns of a matrix we have:
$\mathbf{A}_1: = \begin{pmatrix}
1&1&2  \\
3&2&6  \\
0&1 &1
\end{pmatrix} \to \begin{pmatrix}
1&1&2  \\
0&-1&0  \\
0&0 &1
\end{pmatrix} \implies \det(\mathbf{A}_1) =(1)(-1)(1) =  -1 $
As the columns of a $3 \times 3$ matrix whose determinant is non-zero, these vectors form a basis for $\mathbb{R}^3.$
I don't know what it wants me to do beyond this point however. Could someone please explain what a transition matrix is?

A: The given vector $x$
$$
x = 4 e_1+ 4 e_3
$$
can be represented according the first or the second basis too.
\begin{align}
x
&= x_1^{(0)} b_1^{(0)} + x_2^{(0)} b_2^{(0)} + x_3^{(0)} b_3^{(0)}
= (x_1^{(0)},x_2^{(0)},x_3^{(0)})^T = [x]_0 \\
&= x_1^{(1)} b_1^{(1)} + x_2^{(1)} b_2^{(1)} + x_3^{(1)} b_3^{(1)}
= (x_1^{(1)},x_2^{(1)},x_3^{(1)})^T = [x]_1
\end{align}
This gives a set $[x]_i$ of coordinates, a coordinate vector, for each basis. You are asked to give the matrix $T$, which would transform the first set into the second set of coordinates.
$$
[x]_1 = T [x]_0
$$
Solution:
From $B_0$ to standard basis $e_i$ we get via the matrix
$$
A_0 =
(u_0, u_2, u_3) =
\begin{pmatrix}
1 & 2 & 4 \\
2 & 3 & 6 \\
0 & 0 & 1
\end{pmatrix}
$$
From $B_1$ to standard basis we get via the matrix
$$
A_1 =
(u_1, u_2, u_3) =
\begin{pmatrix}
1 & 2 & 4 \\
2 & 3 & 6 \\
1 & 0 & 1
\end{pmatrix}
$$
From $B_0$ to $B_1$ we get by going from $B_0$ to standard basis via $A_0$ and from standard basis to $B_1$ via $A_1^{-1}$:
\begin{align}
T &= A_1^{-1} A_0 \\
&=
\begin{pmatrix}
1 & 0 & 0 \\
2 & 1 & 0 \\
-1 & 0 & 1
\end{pmatrix}
\end{align}
We have
\begin{align}
[x]_0 &= A_0^{-1} [x] \\
&=
\left(
\begin{array}{rrr}
-3 & 2 & 0 \\
2 & -1 & -2 \\
0 & 0 & 1
\end{array}
\right)
\begin{pmatrix}
4 \\
0 \\
4
\end{pmatrix} \\
&=
\left(
\begin{array}{rrr}
-12 \\
0 \\
4
\end{array}
\right)
\end{align}
and
\begin{align}
[x]_1 &= A_1^{-1} [x] \\
&=
\left(
\begin{array}{rrr}
-3 &  2 & 0 \\
-4 &  3 & -2 \\
 3 & -2 & 1
\end{array}
\right)
\left(
\begin{array}{rrr}
4 \\
0 \\
4
\end{array}
\right)
\\
&=
\left(
\begin{array}{rrr}
-12 \\
-24 \\
16
\end{array}
\right)
\end{align}


text:
Q: String error in MainActivity in Android studio I am having issues with resolving R in Android studio. Here is a screenshot of my error:

As you can see, the error is with the layout width String in wrap_content.I do not understand why this is an error since xml allows you to assign wrap_content to layout_width
http://217.199.187.200/pentaworld.com/content_main.jpg
http://217.199.187.200/pentaworld.com/content_main_2.jpg


text:
Q: Pass addition information in Connection String I want to pass an additonal string value in connection string so that can see which person was connected.
This connection string is login as sql authentication and log file will show sql user id and computer name but i want to add user name who is connected to my applicaiton.
Is there a way to pass user information who is using that application and add in sql server log file. e.g. message.
string constr = "WorkStation id=computerName;"
                    + "packet size=0000"
                    + ";user id=user001;"
                    + "data source=servername;"
                    + "persist security info=True;"
                    + "initial catalog=database"
                    + ";password=password";

A: A connection string is intended as a single string that is used by all the users. It's also something that usually is shared by multiple users, because a database has a limited amount of open connections possible. If you have a connection open for every user, you're going to run into scaling issues and connection pool overflows.
If you want to know what user issued the command, the best solution is to use a stored procedure that takes the user information as a parameter and logs it through that.
However, passing user info through the logic layer to the data layer is a code smell. If you need to know who did a transaction, it's better that you log this in the application code instead of through the SQL database.

A: There is simply no way of doing that directly in to the SQL Logs.
If you want to log the usage you have 2 good options:
1) Create a different SQL user for each username in your application. This is probably only possible if you have Active Directory integration, otherwise it could be a very tedious proces of adding new SQL users
2) Log your application usage from the application into a seperate SQL table. This is how a lot of applications works, and would be considered best practice in this case.


text:
Q: Cannot access property of req.user without iterating I'm havig trouble understanding how to access the properties of a global variable that is set in the middleware of my application
// app.js
app.use(function (req, res, next) {
  res.locals.user = req.user || null;
  next();
});

I would have thought I could access the req.user.username in my template (using handlebars), but for some reason it is forcing me to iterate over this object.
A consle.log(req.user) shows:
  _id: 5f01f9a861f5b33b42a9e,
  username: 'onetap',
  email: 'test@gmail.com',
  password: '$2b$10$VLBS8ZwPKiaXasdfsiiwfg.wyJ1J5CwTKLjS5zXwAsvukHpNmk0HG2',
  createdAt: 2020-07-05T16:02:48.081Z,
  __v: 0
}

And in my template I have to use an each loop and can't access the properties directly. the req.user is not an array either.
{{user.username}}//undefined

{{#each user}}
{{username}}  //onetap
{{/each}}

passport.js file
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");

// Load User Model
const User = require("../models/User");

module.exports = function (passport) {
  passport.use(
    new LocalStrategy({ username: "username" }, (username, password, done) => {
      //   Match User
      User.findOne({
        username: username,
      }).then((user) => {
        if (!user) {
          return done(null, false, { message: "Invalid Username" });
        }
        console.log("Checking password");
        // Match password
        bcrypt.compare(password, user.password, (err, isMatch) => {
          if (err) throw err;
          if (isMatch) {
            return done(null, user);
          } else {
            return done(null, false, { message: "Password incorrect" });
          }
        });
      });
    })
  );

  passport.serializeUser(function (user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
      done(err, user);
    });
  });
};

I was able to fix this by chaning deserialize to:
  passport.deserializeUser(function (id, done) {
    User.findById(id)
      .lean()
      .exec(function (err, user) {
        done(err, user);
      });
  });


text:
Q: Randomly select a list then an item from said list, then print it but also print the list it is in I know how to randomly select something from a list.
I want to randomly select a list and then randomly select a thing from that list, to print it but I also want to be able to print the list the thing is in.
Say there's this:
a = [a1, a2, a3]
b = [b1, b2, b3]

If it selects b2, I want it to print "b2, b" since b2 is in b. If it selects a1, it should print a.
I'm new to python, so help would be great.
Edit:
import random

lists = ['first', 'second']
first = ['one', 'word']
second = ['two', 'more', 'and']

selected = random.choice(random.choice(lists))

print(selected)

A: import random

possible_lists: [[]] = [
    [1,2], # list a
    [3,4]  # list b
]
selected_list = random.choice(possible_lists)
selected_item = random.choice(selected_list)
print(selected_item, selected_list)

Python 2
import random

possible_lists = [
    [1,2], # list a
    [3,4]  # list b
]
selected_list = random.choice(possible_lists)
selected_item = random.choice(selected_list)
print selected_item, selected_list

A: Define first and second first. Then use those variables in lists, not strings that name the variables.
import random

first = ['one', 'word']
second = ['two', 'more', 'and']

lists = [first, second]

selected_list = random.choice(lists)
selected_string = random.choice(selected_list)

print(selected_list, selected_string)

A: import random

lists = ['first', 'second']
first = ['one', 'word']
second = ['two', 'more', 'and']

listused=random.choice(lists)
if listused=="first":

    selected = random.choice(first)
else:
    selected=random.choice(second)

print selected
print listused

A: You need a list of lists so that you can select from the base list, in which all the lists are, a random list with a random value. You can do, for example, like this:
import random

lst = [['first', 'second'],
['one', 'word'],
['two', 'more', 'and']
]

ran_lst = random.choice(lst)

ran_val = random.choice(ran_lst)

print(ran_lst, ran_val)


text:
Q: Easily editing base class variables from inherited class How does communication between base classes and inherited classes work?
I have a data class in my python code ( storing all important values, duh ), I tried inheriting new subclasses from the data base class, everything worked fine except the fact that the classes were not actually communicating ( when one class variable was changed in a subclass, the class attribute was not changed in the base class nor any other subclasses.
I guess I just failed to understand how inheritance works, my question is: Does inheritance keep any connection to the base classes, or are the values set at the time of inheritance?
If there is any connection, how do you easily manipulate base class variables from a subclass ( I tried it with the cls variable to access base class variables, didn't work out )
Example
class Base:
    x = 'baseclass var' # The value I want to edit

class Subclass(Base):
    @classmethod(cls)
        ???edit_base_x_var_here??? # This is the part I don't know

A: Well, you could do that in this way:
class Base:
    x = 'baseclass var' # The value I want to edit

class Subclass(Base):
    @classmethod
    def change_base_x(cls):
        Base.x = 'nothing'

print Subclass.x
Subclass.change_base_x()
print Subclass.x

furthermore, you don't have to use @classmethod, it could be staticmethod, because you don't need current class object cls:
class Base:
    x = 'baseclass var' # The value I want to edit

class Subclass(Base):
    @staticmethod
    def change_base_x():
        Base.x = 'nothing'

EDITED:
According to your question, about other way. Yes it is, but not so pretty. I would say more. If you want to change variable of base class, then you will do it globally though, so that option with assigning to Base.x is the best way you can achieve that.


text:
Q: How to discover services using Active Directory? I would like to add server discovery to a .Net application.  This is so that I can change the servers available for the client to talk to, without rolling out new versions of the application itself.
I work for a large organisation, and different departments may want to expose their own services.  AD seems ideal for this from an organisational point of view.
Whereabouts in AD should I store this sort of thing?  Is there a standard protocol for doing this?  It's not something I've done before.

A: Usually you would use service connection points for this. Here's a couple links to get you started:

*

*http://technet.microsoft.com/en-us/library/cc961722.aspx

*http://msdn.microsoft.com/en-us/library/ms675764(VS.85).aspx


text:
Q: SlimPHP Application not downloading File I am trying to dowload a file using SlimPHP and it doesn't seem to be working for me.
Here is the route I have made:
    $backendApp->post('/export', function ($request, $response, $args) {
        $emails = $this->orginization->exportEmails();
        $exportFile = $this->file->writeEmailExport($emails, 'AllEmails.csv');

        $fh = fopen($exportFile, "r");
        $stream = new \Slim\Http\Stream($fh);

        $response = $response->withHeader('Content-Type', 'application/octet-stream')
            ->withHeader('Content-Description', 'File Transfer')
            ->withHeader('Content-Disposition', 'attachment; filename="' . basename($exportFile) . '"')
            ->withHeader('Content-Length', filesize($exportFile))
            ->withBody($stream);

        return $response;
    });

I know for a fact that $exportFile is a valid PHP streaming resource as the contents of the file come back in the response, I just need to trigger the browser file download functionality for the user.
These are the headers that are present on the response:
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:close
Content-Description:File Transfer
Content-Disposition:attachment; filename="AllEmails.csv"
Content-Length:267
Content-Type:application/octet-stream
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Host:localhost:8080
Pragma:no-cache
X-Powered-By:PHP/5.6.15

Does anything immediately standout that I am doing wrong here? I can see the contents of the file come back in the response tab so I know that I am getting the contents of the file, I just need the user to be prompted to download said file.

A: It's related to however you are calling this as this code works:
$app = new \Slim\App($config);

$app->get("/", function ($request, $response, $args) {

    $response->write(
        <<<EOT
<form method="POST" action="/export">
<input type="submit" value="Download">
</form>
EOT
    );

    return $response;
});

$app->post('/export', function ($request, $response, $args) {
    $exportFile = __DIR__ . '/../test_file.txt';

    $fh = fopen($exportFile, "r");
    $stream = new \Slim\Http\Stream($fh);

    $response = $response->withHeader('Content-Type', 'application/octet-stream')
        ->withHeader('Content-Description', 'File Transfer')
        ->withHeader('Content-Disposition', 'attachment; filename="' . basename($exportFile) . '"')
        ->withHeader('Content-Length', filesize($exportFile))
        ->withBody($stream);

    return $response;
});

You say that you can see information in the response tab. Does this mean that you're triggering this via JavaScript? If so, then the browser will send the file back to the JS rather than to the user. If you want the file download dialog to appear, then provide a form (as you want a POST) with a button on it for the user to click.


text:
Q: opnet attribute name of opnet model is unrecognized I'm trying to simulate a network with opnet and I'm building all parts of it myself (like processors, nodes, links, ...). In my node models I use point-to-point transmitters and receivers and it all seems to be ok but when I try to run the simulation I get this error:
<<< Recoverable Error >>>
Attribute name (data rate) is unrecognized for object (0).
T (0.0001), EV (14), MOD (top.Office Network.node_1.port_tx0), KP (op_ima_obj_attr_get)

node_1 is a node and port_tx0 is its transmitter. I did not create the transmitter, I just used opnet model for it and as I can see "data rate" IS in its attributes by default and I can't even edit it.
SO why doesn't it recognize its own attribute?

A: In the error message the object id is 0.  In my experience, this is not the correct object id for a transmitter.
To see if I am correct, please replace
op_ima_obj_attr_get(objid, "data rate", &datarate);

with the following:
{
  char hname[128];
  char err_str[128];
  op_ima_obj_hname_get(objid, hname, 128);
  snprintf(err_str, 128, "Who is objid (%d):", objid);
  op_prg_odb_print_major(err_str, hname, OPC_NIL);
}
op_ima_obj_attr_get(objid, "data rate", &datarate);

This should answer the question "why does it not recognize its own attribute?" when run in the OPNET debugger.


text:
Q: Null pointer exception while setting adapter to the recycler view Cannot successfully render the recycler view. Getting the error:

"java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference"

Even though I've set initalized the RecyclerView, set the linear layout and set it the adapter. Can anyone point out the error?
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_food_list);

    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    searchBar = (MaterialSearchBar) findViewById(R.id.searchBar);

    if(getIntent() != null ){
        if(getIntent().getStringExtra("categoryId") != null){
            categoryId = getIntent().getStringExtra("categoryId");
            fetchFoodList(categoryId);
        }
    }
    databaseReference = FirebaseDatabase.getInstance().getReference("foodlist");
    floatingActionButton = findViewById(R.id.food_list_fab);
    recyclerView = findViewById(R.id.food_recycler_view);

    final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

}

private void fetchFoodList(String categoryId) {
    Query query = FirebaseDatabase.getInstance().getReference("foodlist").orderByChild("MenuId").equalTo(categoryId);
    FirebaseRecyclerOptions<FoodModel> options = new FirebaseRecyclerOptions.Builder<FoodModel>().setQuery(query, new SnapshotParser<FoodModel>() {
        @NonNull
        @Override
        public FoodModel parseSnapshot(@NonNull DataSnapshot snapshot) {
            Log.d(TAG, "parseSnapshot: "+snapshot.child("Discount").getValue().toString());

            return new FoodModel(snapshot.child("Description").getValue().toString(), snapshot.child("Discount").getValue().toString(), snapshot.child("Image").getValue().toString(), snapshot.child("MenuId").getValue().toString(), snapshot.child("Name").getValue().toString(), snapshot.child("Price").getValue().toString());
        }
    }).build();

    FirebaseRecyclerAdapter firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<FoodModel, FoodViewHolder>(options) {
        @NonNull
        @Override
        public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
            View v = inflater.inflate(R.layout.food_items, viewGroup, false);
            return new FoodViewHolder(v);
        }

        @Override
        protected void onBindViewHolder(@NonNull FoodViewHolder holder, final int position, @NonNull FoodModel model) {
            holder.setFoodName(model.getName());
            Log.d(TAG, "onBindViewHolder: "+model.getImage());
            holder.setFoodImage(model.getImage());
            holder.setFoodDescription(model.getDescription());
        }
    };

    recyclerView.setAdapter(firebaseRecyclerAdapter);
}

A: To solve this, please move the following line of code:
recyclerView = findViewById(R.id.food_recycler_view);

Right after this line:
searchBar = (MaterialSearchBar) findViewById(R.id.searchBar);.

In this way, the RecyclerView object will be initialized before using it.


text:
Q: Help needed with linear algebra computation I do not see what is happening here.
$$(F^TF + \begin{bmatrix}V_1 & V_2\end{bmatrix}\begin{bmatrix}\gamma &0 \\ 0 & 0\end{bmatrix}\begin{bmatrix}V_1^T \\ V_2^T\end{bmatrix})^{-1}F^Ty = \begin{bmatrix}V_1 & V_2\end{bmatrix}\Bigg(\begin{bmatrix}V_1^T \\ V_2^T\end{bmatrix}F^TF\begin{bmatrix}V_1 & V_2\end{bmatrix} + \begin{bmatrix}\gamma &0 \\ 0 & 0\end{bmatrix}\Bigg)^{-1}\begin{bmatrix}V_1^T \\ V_2^T\end{bmatrix}F^Ty\\$$
Help that could explain this is appreciated :)


text:
Q: postgres use of rank function Am new to Sql queries. I need to build a query which will rank the student based on number of test on which he has got 100% divide by total number of test he has taken and consider only test which are 10 days old. Here is my table structure.
CREATE TABLE student(
id serial NOT NULL,student_email varchar NULL,
student_name varchar NULL,
test_subject varchar NULL,
total_question varchar NULL,
total_passed varchar NULL,
total_failed varchar NULL,
total_skipped varchar NULL,
test_time timestamp NULL,
CONSTRAINT student PRIMARY KEY (id));

if a student has total_failed or total_skipped not 0 then that test is not considered has 100%.
sample data will be like
1   j@b.com john    maths   10  10  0   0   2019-08-20 21:00:00
2   j@b.com john    maths   10  10  0   0   2019-08-19 21:00:00
3   j@b.com john    maths   10  09  1   0   2019-08-18 21:00:00
4   j@b.com john    english 10  10  0   0   2019-08-20 21:00:00
5   j@b.com john    english 10  10  0   0   2019-08-19 21:00:00
6   j@b.com john    english 10  09  0   1   2019-08-20 21:00:00
7   p@b.com paul    maths   10  10  0   0   2019-08-20 21:00:00
8   p@b.com paul    maths   10  10  0   0   2019-08-19 21:00:00
9   p@b.com paul    maths   10  10  0   0   2019-08-18 21:00:00
10  k@b.com koki    maths   10  10  0   0   2019-06-20 21:00:00
11  k@b.com koki    english 10  10  0   0   2019-06-20 21:00:00
12  k@b.com koki    science 10  10  0   0   2019-08-20 21:00:00
13  k@b.com koki    maths   10  08  2   0   2019-08-20 21:00:00
14  k@b.com koki    english 10  10  0   0   2019-08-20 21:00:00

from the above data set i need to consider only those data which are with in 10 days and give the "RANK" based on total number of test with 100% divided by total number of test for every distinct subject_name,student.
output of above dataset will be
koki    science 100%   k@b.com
koki    english 100%   k@b.com
paul    maths   100%   p@b.com
john    maths   66.6%  j@b.com
john    english 66.6%  j@b.com
koki    science 0%     k@b.com

Any help appreciated

A: You can use conditional aggregation.  In this case, avg() should work:
select student_name, test_subject,
       avg( (total_failed + total_skipped = 0)::int ) as ratio_passed
from t
where test_time > now() - interval 10 day
group by student_name, test_subject;

A: When I

*

*translate your definition of rank:

total number of test with 100% divided by total number of test

as
COUNT(*) FILTER (WHERE total_passed = total_question) / COUNT(*)::real

*and apply the filter for the last 10 days:
test_time > CURRENT_DATE - interval '10 days'

I end up with the following query
SELECT
  student_name
, test_subject
, COUNT(*) FILTER (WHERE total_passed = total_question) / COUNT(*)::real student_rank

FROM student
WHERE test_time > CURRENT_DATE - interval '10 days'
GROUP BY 1, 2
ORDER BY 3 desc;

I get the desired output:
 student_name | test_subject |   student_rank
--------------+--------------+-------------------
 paul         | maths        |                 1
 koki         | english      |                 1
 koki         | science      |                 1
 john         | maths        | 0.666666666666667
 john         | english      | 0.666666666666667
 koki         | maths        |                 0
(6 rows)


text:
Q: Not able to refresh parent view on close of child window in MVC 4! I am using IE 8 I have a bytearray, which open in a new browser window. I opened the new window by giving target=_blank in HTML.BeginForm. Now the issue is that I am not able to refresh the parent view on close of child browser.
Razor code to open PDF in new window using HTML.BeginForm on form post:
@using (Html.BeginForm("GeneratePDFs", "Flights", FormMethod.Post, new { target = "_blank" }))

Here is the Javascript code to refresh the parent page:
<script type="text/javascript" language="javascript">
    debugger
    window.opener.location.reload();

    window.onunload = refreshParent;
    function refreshParent() {
        window.opener.location.reload();
    }
</script>

A: Ok firstly, calm down! :p
You just need to add the following script on your child view
<script type="text/javascript">

    $(function() {

        $(window).on("unload", function() {
            window.opener.location.reload(true);
            window.close();
            e.preventDefault();
        });

    });

</script>

Basically it attaches an event to the child window with a callback function. So when the window is closed it refreshes the window that originally opened it!


text:
Q: How to get query transaction id from AWS managed blockchain using chaincode I am not able to get transaction id from AWS managed blockchain using chaincode's stub.getState(key) method. Please suggest..

A: Please try the stub method getTxID() instead.
Or, you can get it from the transaction object at the client layer when submitting the transaction


text:
Q: oracle sql developer query error DB2 SQL Error: SQLCODE=-109, SQLSTATE=42601, SQLERRMC=WITH ISOLATION USE AND KEEP, DRIVER=3.69.56 I am trying to run queries batches in oracle sql developer editor and get the following error message:
DB2 SQL Error: SQLCODE=-109, SQLSTATE=42601, SQLERRMC=WITH ISOLATION USE AND KEEP, DRIVER=3.69.56
it is hosted on windows and the oracle sql developer is version 17
I cannot use with ur as the queries are being run in oracle sql developer.
Please see examples of queries run, any ideas on how to get round the error
SELECT 'test' AS Data_Item, 'RC322' AS Test, 'dc' AS Source_Table, (SELECT COUNT() FROM schema.tableA ) AS VALUE FROM SYSIBM.SYSDUMMY1
union all SELECT 'test' AS Data_Item, 'RC323' AS Test, 'dc' AS Source_Table, (SELECT COUNT() FROM schema.tableB ) AS VALUE FROM SYSIBM.SYSDUMMY1
union all SELECT 'test' AS Data_Item, 'RC324' AS Test, 'dc' AS Source_Table, (SELECT COUNT() FROM schema.tableC ) AS VALUE FROM SYSIBM.SYSDUMMY1
union all SELECT 'test' AS Data_Item, 'RC325' AS Test, 'dc' AS Source_Table, (SELECT COUNT() FROM schema.tableD ) AS VALUE FROM SYSIBM.SYSDUMMY1


text:
Q: Edit an email before sending My application uses following function to send email.
Function SendHTMLEMail (strFrom, strTo, strCC, strSubject, strBodyHTML)
 ' create NewMail object
 Set objNewMail = Server.CreateObject("CDONTS.NewMail")
' set sender and recipients (latter can be ';' separated lists)
 objNewMail.From = strFrom
 objNewMail.To = "abc@xyz.com"
 objNewMail.Cc = "def@stu.com"
' set Email Subject
 objNewMail.Subject = strSubject
' construct and set Email's body
 strHTMLStart = "" & strSubject & ""
 strHTMLEnd = ""
 objNewMail.Body = strHTMLStart & strBodyHTML & "To : " & strTo & "CC :" & strCC & strHTMLEnd
' set parameters to Normal importance MIME-encoded and HTML-formatted Email
 objNewMail.Importance = 1 '9-low, 1-normal, 2-high
 objNewMail.BodyFormat = 0 '0-HTML, 1-Text
 objNewMail.MailFormat = 0 '0-MIME, 1-Text
 ' send Email now
  objNewMail.Send
' release NewMail object
 Set objNewMail = Nothing
End Function
I do not want the email to be sent automatically. It should open in outlook and allow me to edit it.
Can anyone help me with the change I should put here in the code so that the email opens instead of being sent automatically ?
The data is coming from a classic asp page and the above function is in utils.inc

A: You need to understand that you are processing the mail in the server and only sending HTML to the client (the web browser).
There is no possible way to manipulate a program (Outlook) in the client PC from the server, unless you have some piece of software (ActiveX, Add-on, etc.) in the client computer.
That said, you can do this trick
response.redirect("mailto:name@hotmail.com?subject=Hello&body=Place body here")

This will open the mail program configured in the client (it will depend on how the client PC is configured)
Be aware that you are very limited on the length of subject and body.
Tested in Firefox 3.6, Chrome and Internet Explorer 8 (it raises a security warning)


text:
Q: Getting CurrentItem within a nested ItemsControl I have an itemscontrol, with a item template. Inside this item template another itemscontrol exists. The latter ItemsControl has a button in its template, the command bound to this template needs to get the "parent" itemscontrol current item.
The structure looks something like this:
<ItemsControl x:Name="outerItemsControl" ItemsSource={Binding MyCollection}>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource={Binding MySecondCollection}>
                <ItemTemplate>
                    <DataTemplate>
                        <Button Command="{Binding MyFantasticCommand}"
                                CommandParameter="{Binding ????}"/>
                    </DataTemplate>
                </ItemTemplate>
            </ItemsControl>
        </DataTemplate>
    <ItemControl.ItemTemplate>
</ItemsControl>

What should I replace the {Binding ????} with to get hold of the current item in MyCollection?
I've tried with both:
Binding ., ElementName=outerItemsControl

and
Binding Path="." RelativeSource="{RelativeSource AncestorType={x:Type ItemsControl}, AncestorLevel=2}

EDIT
Usually when we need to access the "current item" in an items control we do the following:
<ItemsControl x:Name="outerItemsControl" ItemsSource={Binding MyCollection}>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
               <Button Command="{Binding MyCommand}" CommandParameter="{Binding .}"/>
            </DataTemplate>
        <ItemControl.ItemTemplate>
    </ItemsControl>

I want to do the same as this example, but access the parent's "current" item from the child itemscontrol.

A: It seems you want to access the object with the MySecondCollection property from the inner DataTemplate.
This should work:
CommandParameter="{Binding DataContext,
    RelativeSource={RelativeSource AncestorType=ContentPresenter, AncestorLevel=2}}"


text:
Q: In SQL Server, are subqueries automatically optimized? Please ignore the reasons why I wrote the query this way, that's not the subject of the question, as this is a hypothetical derived from a real world example.
I have a case where I need to retrieve records through pagination: only 9 records every page.
I have a subquery which retrieves all rows from the users table (> 10,000 rows), and in the enveloping query, I apply the pagination, like this:
select *
from
    (select firstname, lastname, age
     from users)  -- returns > 10,000 rows
order by lastname asc
offset 0 rows fetch next 9 rows only

Now, again, please ignore why it's written this way, my question is more about understanding how SQL Server optimizes queries: does SQL Server actually run the subquery, and then return the entire resultset first, then filters it down to the first 9 rows, which of course impacts the performance negatively, OR, does it somehow optimize it so it never has to return the entire resultset, resulting in the same performance if there was no subquery?
I have re-written the query to be more direct, like below:
select firstname, lastname, age
from users
order by lastname asc
offset 0 rows fetch next 9 rows only

yet to my surprise, I didn't notice THAT much of an improvement in performance, which lead me to think maybe SQL Server does it's own optimization behind the scenes?
Does anyone have any clues?

A: SQL is a descriptive language, not a procedural language.  A SQL query describes the results being produced.  It does not specify HOW those results are calculated.
That is the function of the compiler and optimizer.  In fact, the code that is executed looks nothing like the original SQL statement.  Technically, it is called a DAG (directed acyclic graph).  And it uses a bunch of primitive operators that you would not recognize.  It is often difficult to figure out what in the original query matches to a particular operator.
When SQL Server executes a query, the entire query is optimized.  SQL Server has a good optimizer, so it is not fooled by subqueries.  You will probably find that the execution plan for the two queries is exactly the same.
Note that all databases work this way.  However, not all optimizers are equal.  So, if you use subqueries in MySQL (older versions) or MS Access, then you might find a noticeable performance difference.


text:
Q: Firebase Cloud Messaging, in onRefreshToken, I can't access my preferences I'm testing Firebase Cloud Messaging under Android Sudio on Ubuntu after I have deleted my android app that implements it on my target phone.
As explained in the documentation, onRefreshToken is called when I start the app for the first time. I try to send the token to my app server, whose URL is stored in the app's Preferences.
Unfortunately I can't read the preferences until after onCreate runs, which is after the onRefreshToken runs. Thus I can't send the new token automatically to my server.
How can I get round this , preferably by being able to read the preferences in the onRefreshToken callback?

A:
Here it is, this is how you can get the context, it was so straight forward.


text:
Q: Problem to order a bar chart in a decreasing way I have a DataFrame containing data about different projects. I tried to create a bar chart, representing the number of users for each project and this 'filtered' depending if the project has been audited before or after 2014.
My problem is that I would like to have all of the bars ranked from the biggest one to the smallest one, and not one on one side and the other one on the other side. I think it's quite hard to understand but with the following pictures, it will be much clearer.
I tried the following:
applications = applications.sort_values(by='NombreUtilisateur2017', ascending=False)

fig = px.bar(applications, x='AppCode', y='NombreUtilisateur2017', color='test_avant_2014')
fig.show()

Here is my output:
current output
But, I would like my graph to look like this:
expected output


text:
Q: Two-dimensional table with row/column highlighting I need a table with N rows and M columns.
The touch event in the table should cause highlighting of current column and row, and when released triggered an action.
By means of what is possible to write such a table?
I thought of using 2D array of UIView/UIButtons to make the table, and putting invisible UIView over this table to handle touch action.
What do you think? Or is there a better solution?

A: You have several options.
Option 1. Two dimensional array of UIButtons.
- (void)setupButtons
{
    int N = 3;
    int M = 3;
    CGFloat buttonSize = 50.0f;
    CGFloat padding = 5.0f;

    CGPoint startButtonLocation = CGPointMake(40.0f, 40.0f);
    CGPoint buttonLocation;

    for (int n = 0; n < N; n++)
    {
        buttonLocation.x = startButtonLocation.x + n * (buttonSize + padding);

        for (int m = 0; m < M; m++)
        {
            buttonLocation.y = startButtonLocation.y + m * (buttonSize + padding);

            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(buttonLocation.x,
                                                                          buttonLocation.y,
                                                                          buttonSize,
                                                                          buttonSize)];
            button.backgroundColor = [UIColor grayColor];

            [button setTitle:[NSString stringWithFormat:@"%i, %i", n, m]
                    forState:UIControlStateNormal];

            [button addTarget:self
                       action:@selector(buttonTapped:)
             forControlEvents:UIControlEventTouchUpInside];

            [self.view addSubview:button];
        }
    }
}

- (void)buttonTapped:(id)sender
{
    NSLog(@"tapped index: %@", ((UIButton *)sender).titleLabel.text);
}

Output:

Option 2. Implementing UICollectionView.
@interface ViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
{
    UICollectionView *_collectionView;
}

@implementation
- (void)viewDidLoad
{
    [super viewDidLoad];

     UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];

    _collectionView.dataSource = self;
    _collectionView.delegate = self;

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [_collectionView setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:_collectionView];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 15;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor greenColor];

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(50, 50);
}

Output:

When user taps an item, you can handle it in:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // Handling
}

A: You could create a matrix, as you suggest, or an NSMutableArray of NSMutableArrays.
But with the description you give of what you attempt to achieve, it sound very much like something UICollectionView can solve for you. From a coding point it behaves almost like a UITableView,  but allows you to create a grid of cells:
Collection views provide the same general function as table views except that a collection view is able to support more than just single-column layouts. Collection views support customizable layouts that can be used to implement multi-column grids, tiled layouts, circular layouts, and many more.
Take a look at the full documentation.


text:
Q: How build a Spritesheet with pure CSS and JS in React js I have a Spritesheet of a bottle of beer and when Scroll down the bottle turns I use the library react-responsive-spritesheet but
but it looks slow because I have other things that change in the Onscroll method.
I've been thinking about replacing the spritesheet with pure css
something like putting all the images on top of each other and changing the z-index of each of them in such a way that you see a fluid turn.
Somebody now what is the best way for build this animation ?


text:
Q: Python pandas HDFstore append dataframe with missing column Say I already have a hdfstore, having 3 columns [a,b,c] whose dtype are [uint32,int64,datetime64[ns]]
The problem is how to append dataframe with missing column. Say column 'c' is missing, I try to append only [a,b], I cannot do it directly because the dataframe cannot match existing table structure
I try to reindex the dataframe including column 'c', and it still doesn't work, because the new column 'c' is all NaN by default, and its dtype is float64, still doesn't match.
So I try to change its dtype, using .astype(datetime64[ns]) but this method doesn't work on either, the dtype stay unchanged.
Now I am stucked, how can I append this partial column dataframe into HDFstore?


text:
Q: Provide a callback URL in Google Cloud Storage signed URL When uploading to GCS (Google Cloud Storage) using the BlobStore's createUploadURL function, I can provide a callback together with header data that will be POSTed to the callback URL.
There doesn't seem to be a way to do that with GCS's signed URL's
I know there is Object Change Notification but that won't allow the user to provide upload specific information in the header of a POST, the way it is possible with createUploadURL's callback.
My feeling is, if createUploadURL can do it, there must be a way to do it with signed URL's, but I can't find any documentation on it. I was wondering if anyone may know how createUploadURL achieves that callback calling behavior.

PS: I'm trying to move away from createUploadURL because of the __BlobInfo__ entities it creates, which for my specific use case I do not need, and somehow seem to be indelible and are wasting storage space.

Update: It worked! Here is how:
Short Answer: It cannot be done with PUT, but can be done with POST
Long Answer:
If you look at the signed-URL page, in front of HTTP_Verb, under Description, there is a subtle note that this page is only relevant to GET, HEAD, PUT, and DELETE, but POST is a completely different game. I had missed this, but it turned out to be very important.
There is a whole page of HTTP Headers that does not list an important header that can be used with POST; that header is success_action_redirect, as voscausa correctly answered.
In the POST page Google "strongly recommends" using PUT, unless dealing with form data. However, POST has a few nice features that PUT does not have. They may worry that POST gives us too many strings to hang ourselves with.
But I'd say it is totally worth dropping createUploadURL, and writing your own code to redirect to a callback. Here is how:

Code:
If you are working in Python voscausa's code is very helpful.
I'm using apejs to write javascript in a Java app, so my code looks like this:
            var exp = new Date()
            exp.setTime(exp.getTime() + 1000 * 60 * 100); //100 minutes

            json['GoogleAccessId'] = String(appIdentity.getServiceAccountName())
            json['key'] = keyGenerator()
            json['bucket'] = bucket
            json['Expires'] = exp.toISOString();
            json['success_action_redirect'] = "https://" + request.getServerName() + "/test2/";
            json['uri'] = 'https://' + bucket + '.storage.googleapis.com/';

            var policy = {'expiration': json.Expires
                        , 'conditions': [
                             ["starts-with", "$key", json.key],
                             {'Expires': json.Expires},
                             {'bucket': json.bucket},
                             {"success_action_redirect": json.success_action_redirect}
                           ]
                        };

            var plain = StringToBytes(JSON.stringify(policy))
            json['policy'] = String(Base64.encodeBase64String(plain))
            var result = appIdentity.signForApp(Base64.encodeBase64(plain, false));
            json['signature'] = String(Base64.encodeBase64String(result.getSignature()))

The code above first provides the relevant fields.
Then creates a policy object. Then it stringify's the object and converts it into a byte array (you can use .getBytes in Java. I had to write a function for javascript).
A base64 encoded version of this array, populates the policy field.
Then it is signed using the appidentity package. Finally the signature is base64 encoded, and we are done.
On the client side, all members of the json object will be added to the Form, except the uri which is the form's address.
        var formData = new FormData(document.forms.namedItem('upload'));
        var blob = new Blob([thedata], {type: 'application/json'})
        var keys = ['GoogleAccessId', 'key', 'bucket', 'Expires', 'success_action_redirect', 'policy', 'signature']
        for(field in keys)
          formData.append(keys[field], url[keys[field]])
        formData.append('file', blob)
        var rest = new XMLHttpRequest();
        rest.open('POST', url.uri)
        rest.onload = callback_function
        rest.send(formData)

If you do not provide a redirect, the response status will be 204 for success. But if you do redirect, the status will be 200. If you got 403 or 400 something about the signature or policy maybe wrong. Look at the responseText. If is often helpful.

A few things to note:

*

*Both POST and PUT have a signature field, but these mean slightly different things. In case of POST, this is a signature of the policy.

*PUT has a baseurl which contains the key (object name), but the URL used for POST may only include bucket name

*PUT requires expiration as seconds from UNIX epoch, but POST wants it as an ISO string.

*A PUT signature should be URL encoded (Java: by wrapping it with a URLEncoder.encode call). But for POST, Base64 encoding suffices.

*By extension, for POST do Base64.encodeBase64String(result.getSignature()), and do not use the Base64.encodeBase64URLSafeString function

*You cannot pass extra headers with the POST; only those listed in the POST page are allowed.

*If you provide a URL for success_action_redirect, it will receive a GET with the key, bucket and eTag.

*The other benefit of using POST is you can provide size limits. With PUT however, if a file breached your size restriction, you can only delete it after it was fully uploaded, even if it is multiple-tera-bytes.

What is wrong with createUploadURL?
The method above is a manual createUploadURL.
But:

*

*You don't get those __BlobInfo__ objects which create many indexes and are indelible. This irritates me as it wastes a lot of space (which reminds me of a separate issue: issue 4231. Please go give it a star)

*You can provide your own object name, which helps create folders in your bucket.

*You can provide different expiration dates for each link.

For the very very few javascript app-engineers:
function StringToBytes(sz) {
  map = function(x) {return x.charCodeAt(0)}
  return sz.split('').map(map)
}

A: You can include succes_action_redirect in a policy document when you use GCS post object.
Docs here: Docs: https://cloud.google.com/storage/docs/xml-api/post-object
Python example here: https://github.com/voscausa/appengine-gcs-upload
Example callback result:
def ok(self):
    """ GCS upload success callback """

    logging.debug('GCS upload result : %s' % self.request.query_string)
    bucket = self.request.get('bucket', default_value='')
    key = self.request.get('key', default_value='')
    key_parts = key.rsplit('/', 1)
    folder = key_parts[0] if len(key_parts) > 1 else None

A: A solution I am using is to turn on Object Changed Notifications. Any time an object is added, a Post is sent to a URL - in my case - a servlet in my project.
In the doPost() I get all info of objected added to GCS and from there, I can do whatever.
This worked great in my App Engine project.


text:
Q: maintenance job frozen in executing state I have several maintenance job stuck on my sql server , stuck from the 10th of may , what should I do first? I try to stop them from sql agent but nothing happens
I did a check with sp_whoisactive
have this  kind of statments
(327853387ms)PREEMPTIVE_OS_AUTHZINITIALIZECON
update: I restarted the agent but the jobs after a while re appear with the ne execution (they are scheduled jobs)

A: At the end the solution was to restart sql service, the restart of the sql agent was not sufficient


text:
Q: Using redux in my react app is not working I am new to react and trying to use redux in my code.
I have installed redux and react-redux by using below command:
 npm install --save redux react-redux

While importing refrence to redux store  in App.js file:
App.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

import { Provider } from 'react-redux'
import store from './redux/store'

ReactDOM.render(

  <React.StrictMode>

    <App />

  </React.StrictMode>,

  document.getElementById('root')
);

serviceWorker.unregister();

I am getting this error in browser :
Error in browser :
Failed to compile
./src/index.js
Module not found: Can't resolve './redux/store' in 'D:\Acumen\Hermes\src'
This error occurred during the build time and cannot be dismissed
does Any thing else is required?


text:
Q: Ublox NEO-M6 and Raspberry Pi3 I'm working on the project and use neo-6m, raspberry pi 3. I follow these steps but I get an error. Please help me.

Neo 6M VCC -----> Raspberry pi 5v        Neo 6M GND -----> Raspberry pi GND
  Neo 6M  RX -----> Raspberry pi TX (gpio 14)    Neo 6M  TX ----->
  Raspberry pi RX (gpio 15)

sudo nano /boot/config.txt

At the end of the file add the follwing lines:
dtparam=spi=on
dtoverlay=pi3-disable-bt
core_freq=250
enable_uart=1
force_turbo=1

sudo nano /boot/cmdline.txt Replace the content with the follwing line (delete everything in it and write down the following content):
dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait quiet splash plymouth.ignore-serial-consoles
sudo reboot
sudo cat /dev/ttyAMA0

and this error:error


text:
Q: Python creating md5 hashes from a list or text when it's a string in the script it generates it correctly like:
result = hashlib.md5(b"12345")
print(result.hexdigest())

this is: 827ccb0eea8a706c4c34a16891f84e7b as it should be but when it comes to read a word from a list or a text it doesnt give the correct md5 hash. I tried to strip "\n" but it didnt work. What should i do? What would you do if you were to generate md5 hashes from a text?
import hashlib

result = hashlib.md5()

with open("text.txt", mode="r", encoding="utf-8") as f:
    for line in f:
        line.strip("\n")

        result.update(line.encode())
        result_md5 = result.hexdigest()

        print(result.hexdigest())

output is: 4528e6a7bb9341c36c425faf40ef32c3
b6cef2a8d7cd668164035a08af6eab17
f44b0df2bb9752914ceac919ae4ca5e5
text file:
pass
12345
password

expected output is:
1a1dc91c907325c69271ddf0c944bc72
827ccb0eea8a706c4c34a16891f84e7b
5f4dcc3b5aa765d61d8327deb882cf99

A: import hashlib

with open("text.txt", "r") as f:
    temp = f.read().splitlines()
    for each_element in temp:
        result = hashlib.md5(each_element.encode("utf-8"))
        print(result.hexdigest())

Output

1a1dc91c907325c69271ddf0c944bc72
827ccb0eea8a706c4c34a16891f84e7b
5f4dcc3b5aa765d61d8327deb882cf99

A: You have to move this:
result = hashlib.md5()

inside your loop, so it's reinitialized every time for every new line. The final code might look like this:
with open("text.txt") as f:
    for line in f:
        print(hashlib.md5(line.strip().encode()).hexdigest())

A: You want an MD5 hash independently for each line.
import hashlib

with open("text.txt", mode="r", encoding="utf-8") as f:
    for line in f:
        line = line.rstrip("\r\n")
        result = hashlib.md5(line.encode())
        print(result.hexdigest())


text:
Q: What happens when rollback is done with auto commit = false? I'm not sure if I understand the concepts correctly,
If I have:
try{
  conn.setAutoCommit(false);
  Statement st= conn.createStatement();

  // valid statement
  String statement1 = ....;
  st.executeUpdate(statement1)

  // invalid statement that will cause an error
  String statement2 = ....;
  st.executeUpdate(statement2)

}catch(SQLException e){
  // there was an error
  conn.rollback();

Are both statements discarded? or does it only ignore statement2 and statement1 goes through?

A: From the Javadoc for Connection#rollback():

Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object. This method should be used only when auto-commit mode has been disabled.

This means that everything which happened inside your wrapped transaction would be rolled back.  Should the error occur on the second update, implying that the first update succeeded, then perhaps only the first update would need to be reversed.
The transaction you showed us allows your two updates to happen atomically, or at least appear this way, to all threads which might be running in the database.  Part of this requirement is that the entire transaction succeeds or fails.  If the latter case, rollback is what is used in the case of failure to take the database back to the starting point before the transaction was attempted.

A: A working example that you require in the scenario that you mention is available at this place.
Here is the Oracle documentation that talks about this behavior.
Setting the autocommit() to false suggests that you as a programmer wants to take control of committing the transaction, based on the outcome of your DML queries.
To answer your question, in the case that you've mentioned none of the INSERT statements would succeed.
Hope you got the information that you seek!


text:
Q: More vocabulary for periodic elements in monoids Let $M$ be a monoid, and let $x\in M$.  One says that $x$ is periodic if
$$x^{i+j}=x^j$$
for some integers $i\geq 1$ and $j\geq 0$.
An easy division algorithm argument shows that if $m$ is the smallest value of $i$ where this happens (for some $j$), and similarly $n$ is the smallest value of $j$ where this happens (for some $i$), then $x^{m+n}=x^n$.  (So those minimal values work together.)
Moreover, given such an $m$ and $n$, the displayed equality holds if and only if $m|i$ and $n\leq j$.
Question 1: Is there a standard reference for these basic facts in the monoid setting?
Question 2: Is there a standard name for $m$ and $n$?
Question 3: Are there special names for the periodic property when $n=0$ or when $n=1$?  (I've seen them called "torsion units" and "potents" [generalizing "idempotents"] in the ring-theoretic setting.)

A: Question 1: See Clifford and Preston, volume 1.
Question 2: $m$ is the period, $n$ is called the index of the element. See this Wikipedia text.
Question 3: If $n=1$, the element is called a group element of finite order. If $n=0$, it is called a unit of finite order. Or you can just call it an element of index 1 (resp. 0).


text: Q: UITextView fade beginning and end of view I have seen many times that a text view is faded in/out at the beginning/end of the text area. Is this a built in function in iOS or do you make it manually? And how?


text:
Q: Cassandra DELETEs with or without IF EXISTS I have a situation where I do not know if data exists in a set of tables. So, as of now, I am issuing DELETEs on all those tables. So, a single API call is resulting in about 30-50 DELETEs in Cassandra. Recently, it is so happening that most of the DELETEs are being issued on non-existent data. Would Cassandra's performance still be negatively affected because of the millions of DELETEs on data that does not exist? Should I use 'IF EXISTS' while deleting data that I am unsure if it exists or not?

A: It's better to just issue regular delete without the IF EXISTS because in this case the coordinator starts to use serial consistency and paxos protocol which takes longer and makes other nodes run in batches etc. IF NOT EXISTS is a light weight transaction and they should be used with 1% workload, not something you do regularly.
Still you don't want to have a lot of tombstones around (what delete does) so it depends on how you model your data and how you do deletes. I'll be more than happy to provide insight on that if you give some schema, insert and delete statements ;)

A: IF EXISTS will just fail if the row doesn't exists.
Deletes indeed affect performance, but deleting nonexistent row will do nothing (but searching for this row), it will not create tombstones for columns that aren't there.


text:
Q: adding two integers to get a long in JAVA I have cracked my head enough and hence asking here:
This works:
int dummy_1, dummy_2;
long final_dummy;
dummy_1 = 0x12345678;
dummy_2 = 0x78563412;
final_dummy = (long)dummy_1 | (long)dummy_2<<32;
System.out.println(String.format("%08X", final_dummy));

Answer : 7856341212345678
This doesnt work:
int dummy_1, dummy_2;
long final_dummy;
dummy_1 = 0xB6F93000;
dummy_2 = 0xB6F93000;
final_dummy = (long)dummy_1 | (long)dummy_2<<32;
System.out.println(String.format("%08X", final_dummy));

Answer: FFFFFFFFB6F93000
Expected answer :  B6F93000B6F93000

A: 0xB6F93000 is actually the int value -1225183232. When coerced to long, it becomes 0xFFFFFFFFB6F93000L, which is also -1225183232.
When you convert int to long you need to make it an unsigned conversion.
// In Java 8
int dummy_1 = 0xB6F93000;
int dummy_2 = 0xB6F93000;
long final_dummy = Integer.toUnsignedLong(dummy_1) | Integer.toUnsignedLong(dummy_2) << 32;

// In all Java versions
int dummy_1 = 0xB6F93000;
int dummy_2 = 0xB6F93000;
long final_dummy = (dummy_1 & 0xFFFFFFFFL) | (long)dummy_2 << 32;

A: In the code that doesn't work, your initial dummy_1 and dummy_2 values are negative; in Java, all numeric types are signed.  The highest bit is set, which is seen because the first hex digit is greater than or equal to 8.
Because these values are negative, when casted to a long, sign extension occurs.
0xB6F93000 => 0xFFFFFFFFB6F9000L

When logically ORed, those F digits remain, explaining why the most significant 8 hex digits (4 bytes) are Fs instead of your value.
Use a mask to clear those sign-extended bits prior to ORing them.
final_dummy = (((long) dummy_1) & 0xFFFFFFFFL) | (((long)dummy_2) & 0xFFFFFFFFL) << 32;

This will clear the most significant 8 hex digits, as if sign extension did not take place.  With this change, I get:
B6F93000B6F93000

Bit-anding on dummy_2 is not necessary, because the shift eliminates those 32 bits anyway.
final_dummy = (((long) dummy_1) & 0xFFFFFFFFL) | (long) dummy_2 << 32;

As an aside, normal Java naming conventions dictate that the variables names should be dummy1, dummy2, and finalDummy.


text:
Q: UIImageView is not retaining it's center while rotation animation is happening I have a UIImageView which I load from nib with autolayout constraints.I am trying to rotate it by 180 deg but when it's rotating it is not holding the center position of its own thus making a weird rotation path.
I am rotating the image by this code
//let center = self.viewAnimate.center
UIView.animate(withDuration: 1.3, delay: 0.0, options: [.repeat,.curveEaseInOut], animations: {
                    //self.viewAnimate.center = center
                    self.viewAnimate.transform = self.viewAnimate.transform.rotated(by: CGFloat(Double.pi))
}, completion: nil)

the commented part is done when I thought may be I can force it to holder the center position it had before animation started. How can I solve this issue?


text:
Q: Jenkins hack to use svn export instead of svn checkout? Has anyone hacked, er, improved Jenkins to allow use of svn export instead of svn checkout?  The time savings is substantial (1 minute versus 12 minutes) on my repo.
There's an issue in the Jenkins queue to provide this feature, but it has been languishing there since 2008.  https://issues.jenkins-ci.org/browse/JENKINS-1304

A: You can open an Execute Shell or Execute Windows Batch Command build steps, and just type svn co as you please