text:
Q: Blazor service injection not working properly I have this code in Blazor 3.0.0-preview4-19216-03 targeting a client app:
namespace BlazorShared.Services
{
    public interface ILogin
    {
        Task<string> Login();
    }

    public class LoginService : ILogin
    {
        private HttpClient _client;

        public LoginService(HttpClient client)
        {
            _client = client;
        }

        public async Task<string> Login()
        {
            var myclient = new HttpClient();

            var responseMessage = await myclient.GetAsync("http://www.google.es");
            var content = await responseMessage.Content.ReadAsStringAsync();

            Debug.WriteLine(content);

            return content;
        }
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ILogin, LoginService>();
    }

    public void Configure(IComponentsApplicationBuilder app)
    {
        app.AddComponent<App>("app");
    }
}

and this HTML
@functions {
    public async Task Submit()
    {
        var str = await LoginService.Login(null, null, null);
        Console.WriteLine(str);
    }
}

Full Razor file: https://pastebin.com/3LbQQvk0
I have tested it and the web request never gets done and I'm  not able to show the service response in the client. I have tried debugging in chrome following the instructions  And I see the service method is being called but the constructor of the service is not, and as I understood Blazor should inject the HttpClient. Any ideas what can be happening?  Thanks.

A: The following is wrong even if it is not the culprit...
In the LoginService you define an HttpClient variable into which you assign an instance of HttpClient provided by DI. On the other hand, you define a new HttpClient object named myclient and use it in the Login method.
You should use the object provided by DI. You shouldn't yourself define HttpClient objects. Why ? Because Blazor configure for you the HttpClient it creates. For instance, setting the Document base URI, which enable your web app to be navigated as an SPA app.
Hope this helps...


text:
Q: Primeng dropdown in form Hey guys i am using primeng 9 dropdown and i am trying to get the value of the dropdown in form. this is the code <form #f="ngForm"> <div class="p-col-8"> <p-dropdown  id="group" [options]='groupList'  optionLabel="name" formControlName="group" ngModel></p-dropdown> </div> </form> <button  (click)="addPhoneNo(f)" label="Save"></button>. The addPhoneNo(data)
function prints the value of the form by this code console.log(data.value) but the problem is there is no value nor even the control (the dropdown) is not there. pls help

A: There must be issue with your input to the drop down, which is [options]='groupList',
I would suggest that you check what values are being passed on to the variable grouplist and then accordingly take actions.
If you refer this URL it might help you. Look out for the Getting Started Section
https://www.primefaces.org/primeng/showcase/#/dropdown

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dedup.sys 0x7E after inplace upgrade Server 2016 => 19 I've recently performed an in-place upgrade from Server 2016 => 2019 (non-domain).
2 of the drives connected has been configured with data deduplication (mostly VHDs for Hyper-V). Ever since the upgrade, attempting to access, reverse dedupe (start-dedupejob -type unoptimize) the system will crash with 0x07E dedup.sys
(0x0000007E (0xFFFFFFFFC0000094, 0xFFFFF80BE9E82F29, 0xFFFFA00F5D4BA3E8, 0xFFFFA00F5D4B9C30)))
Attempting to copy the data off the drive results in the same error. I have spun up a 2016 VM in an attempt to copy/reverse dedupe and it fails stating revision is unknown. Spun up a fresh 2019 to do the same and receive the same bugcheck as the upgraded system.
Hindsight being 20/20 I should've checked these things before the upgrade but now I'm in this situation, are there any suggestions? I've tried googling for the past several hours and have only come across one report of the same, with no solutions provided.
Any help would be greatly appreciated! Thanks in advance.

A: In MS Q&A Website there is a notice that this is a know bug and will be fixed in this month's Preview Update (Jul 13) When published it will be under KB5004244 for Server 2019. ref
I hope the reference is not fake as it seems there are a lot of people with the same issue.


text:
Q: Shared resource in functional programming Context
I am writing an app using Clojure and following the functional programming paradigm. In this app I have two HTTP endpoints: /rank and /invite. In /rank the app ranks a list of costumers based on their scores. In /invite the app receives an invite from one costumer to another and this should yield changes on the scores of some costumers.
Problem
Data from costumers are kept in a single vector of maps called record.
Putting aside referential transparency for a moment, record should be a shared resource between the endpoints, one reads it and uses it in a ranking function to respond an HTTP request and the other reads it and updates scores in it.
Now, with functional programming in mind, record cannot be updated, so the /invite endpoint should read it and return a new record', problem is, /rank endpoint is setup to use record, but when a new record' is generated it should use it instead of the original one.
My ideas for solving this
I understand that in this context the whole app cannot be fully, functionally speaking, pure. It reads initial input from file and receive requests from the external environment, all of which renders functions that deal with these parts not referentially transparent. And almost every program will have these small portions of non-functional code, but in an attempt of trying not to add more of these non-functional functions to the app and this app being just to exercise some functional programming, I am not persisting record to a database or something, because if this were the case, problem would be solved as I could just call a function to update record on the database.
My best idea so far is: The endpoints are created with a routes function from Compojure, so in the /invite endpoint I should process the new record' vector, and recreate the /rank endpoint supplying it with record'. This part of recreating /rank is what I am struggling at, I am trying to call routes again and define again all the endpoints in the hope that it will override the original call of routes, but as expected, as I believe Compojure follows functional programming, once created, the routes are immutable and a new call of routes won't override anything, it will just create new routes that will be left in the void, not attached to the HTTP requests.
So, is it possible to do what I want with pure functional code? Or it is unavoidable to break referential transparency and I should persist record to a file or database to update it?
PS.: I don't know if this is relevant, but I am new to Clojure and to any sort of web interaction.

A: Clojure (in contrast to Haskell) is not pure and has its own constructs to manage changes to shared state. It doesn't isolate impureness using a type system (like IO monad in Haskell) but promotes using pure functions and managing the state with different types of references (atom, agent, ref) defining a clear semantics how and when the state is changed.
For your scenario Clojure's atom would be the simplest solution. It provides a clear contract on how its state is managed.
I would create a var holding your record within an atom:
(def record (atom [])) ;; initial record is empty

Then in your rank endpoint you could use its value using deref or with @ as a syntactic sugar:
(GET "/rank" []
  (calculate-rank @record))

Whereas your invite endpoint could update your record value atomically using swap!:
(POST "/invite/:id" [id]
  (invite id)
  (swap! record calculate-new-rank id)
  (create-response))

Your calculate-new-rank function would look like that:
(defn calculate-new-rank [current-record id]
  ;; do some calculations
  ;; create a new record value and return it
  (let [new-record ...]
    new-record))

Your function will be called with the current version of the data stored in the atom and other optional parameters and the result of your function will be installed as the new value of your atom.


text:
Q: Are there standard techniques for batching timestamped messages from multiple ordered streams? Let's say that you have N streams, each of which contains messages ordered by a timestamp on the message. The messages in each stream arrive with a rough cadence, but network unreliability means that the interval between messages isn't constant. We are guaranteed that messages aren't duplicated. Furthermore, the streams aren't synchronized with one another. This is a visualization of 3 such streams:
    ───────────────────────────────────────────
1   x    x    x      x   x         x
    ───────────────────────────────────────────
2    x     x   x   x       x    x      x
    ───────────────────────────────────────────
3   x     x   x     x      x    x         x
    ───────────────────────────────────────────

               Time ──────────────────►

Some implications:

*

*We may need to wait for a stream to produce its next available message in order to have a message from each stream.

*We may want a timeout so that we don't wait on a stream forever.

*If we already have a message from a stream, could we get a better "batch" by waiting for its next message?

The goal is produce a "batch" of messages that occur "at the same time." Let's assume we have some metric for determining "at the same time" e.g. minimum variance in timestamps, etc.
My current best guess:

*

*Peek the latest message from each stream.

*If we don't have a message from each stream, try waiting until we get a message from each stream.

*If we haven't reached the timeout, peek the next message from each stream to see if it improves the batch.

*Once we reach the timeout or know that the next message from each stream would make a worse batch, we call it a day and send the batch along.


text:
Q: (PHP) MySQL creates two rows instead of one in Chrome I've already looked through other questions but couldn't find an answer to this specific problem since it seems its all about the Chrome browser.
I stripped down my code to debug this problem and the only thing I'm executing now is loading my database and doing an INSERT.
However it always inserts two rows instead of one row.
Then I tested this with Firefox and there are no problems. I also disabled all my Chrome Extensions and it's still unchanged. I can't figure out what else might be causing this. Like I said, it works in other browsers.

A: there is some discussion about chrome making multiple requests here
the gist seems to be that there are some things that could cause chrome to make an additional request, including (but not limited to):

*

*link tags with an empty href property <link rel="shortcut" href="">

*image, iframe, or scripts tags with an empty or '#' src property <img src="#">

*chrome fetching the favicon

do any of those apply?
regardless of what is causing the double GET, a good solution would be to be to follow standard web development best practices: don't change application state as a result of a GET call.  Require a POST.

A: Server side code (e.g. PHP script) does not depend of your browser. So it couldn't behave differently in different browsers.
But yes, in some cases you may have your code executed two times for single page hit.
Lets assume you have a code that inserts new row every time your page has been visited (for example: old-school visits counter). When using Google Chrome you may be surprised, cause you'll get two inserted rows per single page hit. That happens because Google Chrome makes second request to page just for getting favicon.
Other possibility is an weird  condition in your code. Eg. if it is chrome, do something else/more


text:
Q: SQL combine two rows with common batch number into one line I have an Oracle SQL (select *) query that spools batch transactional information, the result of which outputs the main sender and receivers to different lines for the same transaction like below:
BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME RECEIVER_ACCT_NO    RECEIVER NAME
12345678    15-May-20   103.55  400001000        ENDCORP         (null)
12345678    15-May-20   34.55   400001000        (null)          78909909         JOHN SMITH
12345678    15-May-20   44.00   400001000        (null)          78853229         HENRY FAGIL
12345678    15-May-20   4.00    400001000        (null)          76849852        BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        (null)          72555099          FELIX MAGS
12222222    16-May-20   1902.00 400000105       ZENDCORP          (null)
12222222    17-May-20   1899.00 400000105        (null)          90333300          KEN GOTL
12222222    18-May-20   3.00    400000105        (null)          90127765         JONES MAST

In this case, ENDCORP and ZENDCORP sent out batch payments of a total of 103.55 and 1902.00 to 4 and 2 clients respectively.
However, I would prefer my results to be in the form below:
BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME    RECEIVER_ACCT_NO        RECEIVER NAME
12345678    15-May-20   34.55   400001000        ENDCORP        78909909                JOHN SMITH
12345678    15-May-20   44.00   400001000        ENDCORP        78853229                HENRY FAGIL
12345678    15-May-20   4.00    400001000        ENDCORP        76849852                BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        ENDCORP        72555099                 FELIX MAGS
12222222    17-May-20  1899.00  400000105       ZENDCORP        90333300                  KEN GOTL
12222222    18-May-20   3.00    400000105       ZENDCORP        90127765                 JONES MAST

I would appreciate guidance on how to formulate my query for this result

A: I'm assuming when you say the query is select * that you are showing us the table structure. Otherwise we'd need more detail of the tables and your query.
If it's one table,  you just need to select where sender name is null and join to the same table on sender acct no and sender name is not null, selecting appropriate columns from each relation.

A: I think you can use window functions to impute the name and then filter:
select . . .   -- columns you want
from (select t.*,
             max(sender_name) over (partition by batch_no) as imputed_sender_name
      from t
     ) t
where RECEIVER_ACCT_NO is not null;


text:
Q: Cannot establish connection with socket.io (xhr poll error) in FireFox I am using socket.io 1.4.8 and firefox 48. I have a sample code that works fine in chrome:
// Server
var express = require('express');
var app = express(); var fs = require('fs');
var option = {
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem')
};
var https = require('https').createServer(options, app).listen(process.env.PORT || 3000);
var io = require('socket.io')(https);

io.on('connection', function(socket) {
    socket.on('login', function(username) {
        console.log('[login]', username);
    };
}

// Client
var socket = io('https://127.0.0.1:3000');
var username = 'test';
socket.emit('login', username);

But when i run in firefox, i got an Error: xhr poll error. Here is the log from client:
socket.io-client:url "parse https://127.0.0.1:3000" +0ms
socket.io-client "new io instance for https://127.0.0.1:3000" +3ms
socket.io-client:manager readyState closed +3ms
socket.io-client:manager "opening https://127.0.0.1:3000" +1ms
engine.io-client:socket creating transport "polling" +1ms
engine.io-client:polling polling +1ms
engine.io-client:polling-xhr xhr poll +2ms
engine.io-client:polling-xhr "xhr open GET: https://127.0.0.1:3000/socket.io/?EIO=3&transport=polling&t=LTvQYL3" +1ms
engine.io-client:polling-xhr xhr data null +1ms
engine.io-client:socket setting transport polling +2ms
socket.io-client:manager connect attempt will timeout after 8000 +1ms
socket.io-client:manager readyState opening +3ms
engine.io-client:socket socket error {"type":"TransportError","description":0} +74ms
socket.io-client:manager connect_error +1ms
socket.io-client:manager cleanup +0ms

How can i fix this error? Thanks.

A: For me the reason was site's self-signed certificate not being trusted by Firefox. Go to socket url and you should be shown a dialog to add the untrusted site to exceptions.


text:
Q: Showing triangle inequality for a norm I want to determine whether the following is a norm or not:
\begin{equation}
\max\{|x_1-x_2|, |x_1+x_2|, |x_3|, |x_4|, \ldots,|x_n|\}
\end{equation}
Specifically, I want to know whether the triangle inequality holds:
\begin{equation}
||x+y|| \leq ||x||+||y||
\end{equation} I also noted that this is very similar to the $L-\infty$ norm:
\begin{equation}
||x||_\infty = \max_{1\leq i\leq n}|x_i|
\end{equation}
Since this norm is identical to the $L-\infty$ norm except for the first two elements, it suffices to consider the cases when $|x_1+x_2|$ and $|x_1-x_2|$ are the maximum
elements.
I am stuck on this thought, not being able to cover all the cases. (I have been thinking what if $x_1$ and $x_2$ are large but $y_1$ and $y_2$ are small. Anyway, this
leads me to believe that there is a simpler way.

*

*How do I determine whether the triangle inequality holds?

*What is a good strategy in general when dealing with maxima?

A: Consider the map $f:(x_1,x_2,x_3,\ldots,x_n)\mapsto(x_1-x_2,x_1+x_2,x_3,\ldots,x_n)$. It is easy to show that this is linear and invertible. So, you have got a linear bijection on your hands, and your candidate norm is $|x| = |f(x)|_\infty$.
Then the problem reduces to "given a linear bijection $f:\mathbb{R}^n\to\mathbb{R}^n$ and a known norm $|\cdot|$, show that $|f(\cdot)|$ is also a norm" which (I think) is true and much easier to tackle.


text:
Q: C++ send data to Webserver Currenlty i am trying to send data to a webserver using c++
Right now im using libcurl, but i am facing problem with it, as its slow.
I am kinda new with c++, so I was wondering what other alternatives are available to send data to a webpage, which in turn stores them to database.
I have something likes this now
sprintf(data, "&val1=&val2=&val3=&val4.....",val1, val2, val3, val4....);
then send this data using curl post

the problem is that, the val1,val2,val3,val4 is actually being grabbed from a program, which actually generates 2 sample values per second, hence the curl function becomes slow.
So can someone please help me with any better alternatives?

A: If you must for the sake of speed, you can always try to open a socket with the webserver and directly transmit a self-generated POST message over TCP/IP.  That being said, you'll still have to wait for the proper hand-shake as well as a response from the server in the TCP/IP transmission state, thus the perceived "slowness" of the connection may not be something under your control.
For speed, generally UDP is preferred over TCP/IP due it's lack of checking for a response and other packet-transmission guarantees. In this case though, you may have to buffer the values coming in from your source before you attempt to send them to the webserver, with the hopes that you won't eventually run out of buffer space.

A: It's not curl that becomes slow, it's the fact that you're inducing a very slow process too frequently.
Buffer more of your data before sending it. Send it in larger chunks. Look into a technique called double-buffering so you don't miss any updates.
http://en.wikipedia.org/wiki/Multiple_buffering


text:
Q: '-' not working while using Regular Expressions to match special characters, c# Pattern is
Regex splRegExp = new System.Text.RegularExpressions.Regex(@"[\,@,+,\,?,\d,%,.,?,*,&,^,$,(,!,),#,-,_]");

All characters work except '-'. Please advise.

A: Use
@"[,@+\\?\d%.*&^$(!)#_-]"

No need for all those commas.
If you place a - inside a character class, it means a literal dash only if it's at the start or end of the class. Otherwise it denotes a range like A-Z. As Damien put it, the range ,-, is indeed rather small (and doesn't contain the -, of course).

A: '-' has to be the first charater in your regex.
Regex splRegExp = new System.Text.RegularExpressions.Regex(@"[-,\,@,+,\,?,\d,%,.,?,*,&,^,$,(,!,),#,_]");

A: You need to escape the -character for it to work (it's a regular expression syntax)
Try this:
"[\,@,+,\,?,\d,%,.,?,*,&,^,$,(,!,),#,\-,_]"


text:
Q: Android - SharedPreferences ListPreference - PreferenceFragment onCreate not called Ok, I know there have been a lot of questions about SharedPreferences in Android asked before, and I did manage to get quite far, but since I'm kinda new to SharedPreferences I don't know the last few steps to get it to work.
In my MainActivity I have the following:
public class MainActivity extends ActionBarActivity
{
    ...

    // Public static MainActivity so we can use findViewById from MyPrefsActivity
    public static MainActivity mActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

        mActivity = this;
    }

    ...

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch(id){
            case R.id.action_settings:
                startActivity(new Intent(this, MyPrefsActivity.class));
                return true;
        }
        return false;
    }
}

And this is MyPrefsActivity.java:
package com.example.checkboxoptionsv2;

import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ImageButton;

public class MyPrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
    private static int prefs = R.xml.settings;
    private ImageButton cbButton, spinnerButton, popupButton;
    private final String LIST_PREFERENCE = "prefCheckboxOption";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            getClass().getMethod("getFragmentManager");
            AddResourceApi11AndGreater();
        }
        catch(NoSuchMethodException e){ // Android API < 11
            AddResourceApiLessThan11();
        }

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        preferences.registerOnSharedPreferenceChangeListener(this);
*       ListPreference listPreference = (ListPreference) findPreference(LIST_PREFERENCE);
        if(listPreference.getValue() == null)
            listPreference.setValue("0");

        cbButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnCheckbox);
        spinnerButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnSpinner);
        popupButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnPopup);

        setChosenPreference(0);
    }

    private void setChosenPreference(int chosen_value){
        // First put all Visibilities on GONE
        cbButton.setVisibility(View.GONE);
        spinnerButton.setVisibility(View.GONE);
        popupButton.setVisibility(View.GONE);

        // Then turn the chosen on VISIBLE again
        switch(chosen_value){
            case 0: // Multi-Click CheckBox
            default:
                cbButton.setVisibility(View.VISIBLE);
                break;
            case 1: // Dropdown CheckBox
                spinnerButton.setVisibility(View.VISIBLE);
                break;
            case 2: // Pop-up CheckBox
                popupButton.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if(key.equals(LIST_PREFERENCE)){
            ListPreference listPreference = (ListPreference) findPreference(key); // LIST_PREFERENCE
            listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    int chosen_option = Integer.valueOf((String) newValue);
                    setChosenPreference(chosen_option);
                    return false;
                }
            });
        }
        else{
            // Other settings
        }
    }

    @SuppressWarnings("deprecation")
    protected void AddResourceApiLessThan11(){
        addPreferencesFromResource(prefs);
    }

    @TargetApi(11)
    protected void AddResourceApi11AndGreater(){
*       MyPreferenceFragment pf = new MyPreferenceFragment();
        getFragmentManager().beginTransaction().replace(android.R.id.content, pf).commit();
    }

    @TargetApi(11)
    public static class MyPreferenceFragment extends PreferenceFragment{
        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
*           addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
            // private members seem to be visible for inner class, and
            // making it static made things so much easier
        }
    }
}

And the settings.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="@string/checkbox_options_title" >
        <ListPreference
                android:key="prefCheckboxOption"
                android:title="@string/pref_checkbox_option"
                android:summary="@string/checkbox_options_summary"
                android:entries="@array/checkbox_options"
                android:entryValues="@array/checkbox_option_values" />

    </PreferenceCategory>

</PreferenceScreen>

and arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="checkbox_options">
        <item>CheckBox as Multi-Click</item>
        <item>CheckBox as Dropdown</item>
        <item>CheckBox as Pop-up</item>
    </string-array>
    <string-array name="checkbox_option_values">
        <item>0</item>
        <item>1</item>
        <item>2</item>
    </string-array>
</resources>

(Of course I've also included the MyPrefsActivity in the AndroidManifest.xml)

My goal is to make one of the three checkbox-option (found in the setChosenPreference method) VISIBLE, and the other two GONE, based on the preference selected in the ListPreference.
Right now the Listpreference in both the onCreate() method and onSharedPreferenceChanged() is null and giving a NullPointerException. So I set some breakpoints (see the three " * ") and the reason they are null is because the third " * " (in the static class PF) isn't called.
The addPreferencesFromResources should be called before using findPreference, otherwise it will return null. Does anyone know why during debugging I do get to the second " * " in the AddResourceApi11AndGreater() method, but I'm not getting to the third one in the MyPreferenceFragment-class onCreate method() ?.. the onCreate isn't called at all..
Also, does the rest of my code seems ok(-ish) or should I change something in order to make it work as I intended?
Thanks in advance for the responses.
TL;DR: MyPreferenceFragment instantion is created successfully, but it's @Override onCreate method is never called.

EDIT 1: Ok, I did found the problem: When I added addPreferencesFromResource(prefs) in the activity's onCreate method as a debug-test, I found out that the MyPreferenceFragment-class is indeed being initialized, then it finishes the activity's onCreate method (which would have failed at findPreference() if I didn't added the addPreferencesFromResource(prefs) test-line), and only after the activity's onCreate method is completely finished, it goes to the MyPreferenceFragment's onCreate method.
Is there a way to let the PreferenceFrament's onCreate method go first, while in the middle of the activity's onCreate method, so after AddResourceApi11AndGreater() but before findPreference(LIST_PREFERENCE)?

A: Move your logic to PF, don't do things in PreferenceActivity.
There are also changes in the way of listening to the preferences changes. Check the code.
public class MyPrefsActivity extends PreferenceActivity {
    private static int prefs = R.xml.settings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            getClass().getMethod("getFragmentManager");
            AddResourceApi11AndGreater();
        }
        catch(NoSuchMethodException e){ // Android API < 11
            AddResourceApiLessThan11();
        }
    }

    @SuppressWarnings("deprecation")
    protected void AddResourceApiLessThan11(){
        addPreferencesFromResource(prefs);
    }

    @TargetApi(11)
    protected void AddResourceApi11AndGreater(){
        getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PF()).commit();
    }

    @TargetApi(11)
    public static class PF extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
        private ImageButton cbButton, spinnerButton, popupButton;
        private final String LIST_PREFERENCE = "prefCheckboxOption";

        @Override
        public void onCreate(final Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
            // private members seem to be visible for inner class, and
            // making it static made things so much easier

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            preferences.registerOnSharedPreferenceChangeListener(this);
            ListPreference listPreference = (ListPreference) findPreference(LIST_PREFERENCE);
            if(listPreference.getValue() == null)
                listPreference.setValue("0");

            cbButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnCheckbox);
            spinnerButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnSpinner);
            popupButton = (ImageButton) MainActivity.mActivity.findViewById(R.id.ibtnPopup);

            setChosenPreference(Integer.valueOf(preferences.getString(LIST_PREFERENCE, "0")));
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            int chosen_option = Integer.valueOf(sharedPreferences.getString(key, "0"));
            setChosenPreference(chosen_option);
        }

        private void setChosenPreference(int chosen_value){
            // First put all Visibilities on GONE
            cbButton.setVisibility(View.GONE);
            spinnerButton.setVisibility(View.GONE);
            popupButton.setVisibility(View.GONE);

            // Then turn the chosen on VISIBLE again
            switch(chosen_value){
                case 0: // Multi-Click CheckBox
                default:
                    cbButton.setVisibility(View.VISIBLE);
                    break;
                case 1: // Dropdown CheckBox
                    spinnerButton.setVisibility(View.VISIBLE);
                    break;
                case 2: // Pop-up CheckBox
                    popupButton.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }
}


text:
Q: Unity 3D | Is there any option to import a 3D model and use it in a existing player object? is there any option to import a 3D model and use it in a existing player object?
I have already got a player object and I want to use my 3D object as the model of it.
Can I do this, or must I move all the things to the new object?
(Sorry for the not perfect english)

A: You can just drag your 3D model in to the scene and make it child of the player object. You can do that simply by dragging the model object on top of the player object in Hierarchy. If you already have a model for player object (e.g. default cube model) than you can delete the Mesh Renderer from Inspector.


text:
Q: limit the number of points in svg path I'm developed the below graph using SVG. I added the point to the end of the path using stroke-dasharray, but there are multiple points been added. How to add one point end of the purple path? Is it possible to do that using stroke-dasharray?
https://i.stack.imgur.com/fXFrO.png
This is my HTML so far:
<svg style="fill:none; stroke:#81125A" width="300px" height="200px">
    <linearGradient id="gradient" x1="0" y1="0" x2="0" y2="100%">
      <stop offset="0%" stop-color="#81125A" />
      <stop offset="100%" stop-color="#81125A" />
    </linearGradient>

    <path d=" M  130.45001850481378   166  A  78 78 107 0 1 126.20062143070965 96.52297197783665" stroke="#e7e7e8"></path>

    <path d=" M  131.14095054523523   86.82703015701578  A  78 78 107 0 1 189.84677986512304 49.427292161274664" stroke="#e7e7e8"></path>

    <path d=" M  200.72216074279504   49.04751549251053  A  78 78 107 0 1 261.8938594545413 82.26103796461837" stroke="#e7e7e8"></path>

    <path d=" M  267.49850888669266   91.58874102031533  A  78 78 107 0 1 266.2203371568729 164.81515037921423" stroke="#e7e7e8"></path>

    <path d=" M  130.45001850481378   166  A  78 78 107 1 1 265.5499814951862 166" id="purple" fill='none' class="purple"></path>

    <path d=" M  130.45001850481378   166  A  78 78 107 1 1 265.5499814951862 166" id="white" fill='none' class="border"></path>

    <path d=" M  130.45001850481378   166  A  78 78 107 1 1 265.5499814951862 166" id="back" fill='none' class="fill"></path>

 </svg>

And this my CSS:
path {
    stroke-linecap: round;
    stroke-width: 8;
  }

path.grey {
  stroke: #e7e7e8;
}

path.purple {
  stroke: url(#gradient);
  stroke-dasharray: 100,326;
  stroke-dashoffset: 100;
  stroke-width: 8;
  animation: dash 2.6s ease-out forwards;
}

path.border {
  stroke: #81125A;
  stroke-dasharray: 0px,100px;
  stroke-dashoffset: 100px;
  stroke-width: 19.5px;
  animation: dash 2.6s ease-out forwards;
  fill-rule: evenodd;

}

path.fill {
  stroke: #FFFFFF;
  stroke-dasharray: 0px, 100px;
  stroke-dashoffset: 100;
  stroke-width:9.5px;
  animation: dash 2.6s ease-out forwards;

}

.circle{
  height:15px;
  width:15px;
  background-color:purple;
}

@keyframes dash {
  to {
    stroke-dashoffset: 1;
  }
}

A: I'm not sure that stroke-dasharray is the right tool here.
Here you are probably looking for stroke-dashoffset, it will help you have some progress all along the path of the SVG. You can get the length of it w/ some JS: path.getTotalLength() and decide on how long you want it to progress, with a percentage or alike.
This article may help you understand a bit better how this works.
https://css-tricks.com/svg-line-animation-works/
Great news is that you can animate this ! Just beware because there are some sneaky behavior w/ Firefox when your progress is at 0, it may go backwards at initial load (if I remember correctly).


text:
Q: How to insert div underneath list of floating divs Say you have 5-20 inner boxes inside an outer box, which has a width of 300-500 pixels.
<outer>
<inner>Number 1</inner>
<inner>Number 2</inner>
<inner>Number 3</inner>
<inner>Number 4</inner>
<inner>Number 5</inner>
<inner>Number 6</inner>
...
</outer>

Depending on the outer width, they could end up being displayed like this:
Number 1  Number 2
Number 3  Number 4
Number 5  Number 6

Or this:
Number 1  Number 2  Number 3
Number 4  Number 5  Number 6

Now, when you tap an inner box (eg. #2), you want to reveal a new box underneath the tapped box:
Number 1  Number 2
+----------------+
|                |
| Hello Number 2 |
|                |
+----------------+
Number 3  Number 4
Number 5  Number 6

Or if the width is larger, it would look like this:
Number 1  Number 2  Number 3
+--------------------------+
|                          |
|      Hello Number 2      |
|                          |
+--------------------------+
Number 4  Number 5  Number 6

My question is, in order to be able to easily insert the new box in the correct place in markup, what is the best way to lay out the inner boxes?
a) Simply float the inner boxes. Good: Browser handles positioning. Bad: How do you determine where to insert the new box when your code doesn't know the positions of the inner boxes?
b) Have your code position the boxes in columns and rows according to the available width. Good: Easy to insert the new box the right place. Problem: Creates challenges with responsiveness.
Example: See how album details are revealed in iTunes when clicking an album thumbnail

A: I hope i got your question right, you need to change the css when needed , for example add a class that has float:none and clear:both when a condition (like click occurs.
I did an example on fiddle:https://jsfiddle.net/ejeqs8m7/2/
Just click on any of the divs.
It toggles a class .clicked that looks like this:
.clicked {
  float:none;
  clear:both;
  width:auto;
}

A: You can check whether the elements are in same horizontal line or not and add the viewer element dynamically using JavaScript.

var idles = document.querySelectorAll('.idle');
Array.prototype.forEach.call(idles, function(idle) {
  idle.addEventListener('click', showInfo);
});

function showInfo(e) {
  var selectedTabClass = 'active';
  var viewerClass = 'viewer';
  if (showInfo.prevClickElement && showInfo.prevClickElement !== this) {
    showInfo.prevClickElement.classList.remove(selectedTabClass);
  }
  if (this.classList.contains(selectedTabClass)) {
    // remove viewer element
    showInfo.viewer.parentElement.removeChild(showInfo.viewer);
    this.classList.remove(selectedTabClass);
    return;
  }
  if (!showInfo.viewer) {
    // Create a viewer element only if it wasn't created before
    showInfo.viewer = document.createElement('div');
    showInfo.viewer.classList.add(viewerClass);
  }

  if (!showInfo.section) {
    // Get the parent container
    showInfo.section = document.querySelector('section');
  }
  var after = this;
  // Getting the next element which isn't in the exact horizontal line with the clicked element
  while (after && after.offsetTop === this.offsetTop) {
    after = after.nextElementSibling;
  }

  // Add the content through the below line
  showInfo.viewer.innerHTML = this.innerHTML + " Viewer";
  if (after) {
    showInfo.section.insertBefore(showInfo.viewer, after);
  } else {
    // if after element isn't present then safely assuming that the clicked element was in the last horizontal line and appending the viewer element
    showInfo.section.appendChild(showInfo.viewer);
  }
  this.classList.add(selectedTabClass);
  showInfo.prevClickElement = this;
}
section {
  width: 200px;
}
.idle {
  background-color: green;
  float: left;
  width: 100px;
}
.clicked {
  background-color: yellow;
  float: none;
  clear: both;
  width: auto;
}
.viewer {
  clear: both;
}

Div #1

Div #2

Div #3

Div #4

Div #5

Div #6

Div #7

Div #8


text:
Q: How to get TreeView-like file drop-down list I am trying to code a file drop-down list like the one in the windows file explorer but with a checkbox like shown in the picture.
I have tried using a TreeView but I couldn't find a way to get it looking right. Is there an easy way to do this or do I just have to build it from scratch with an empty canvas?


text:
Q: SIGABRT When using AVFoundation I took this code from an app we made and which is already in store (and still running without issues).
But when I try to run it in a new app, I get a SIGABRT.
Here´s a sample class which I used to reproduced the crash in Xamarin.Forms via DependencyService. The error property remains null after creating the recorder.
public class RedordDependencies : IRecordDependencies
{
    NSObject[] values = new NSObject[] {
        NSNumber.FromFloat (44100.0f), //Sample Rate
        NSNumber.FromInt32 ((int)AudioToolbox.AudioFormatType.LinearPCM), //AVFormat
        NSNumber.FromInt32 (2), //Channels
        NSNumber.FromInt32 (16), //PCMBitDepth
        NSNumber.FromBoolean (false), //IsBigEndianKey
        NSNumber.FromBoolean (false) //IsFloatKey
    };

    NSObject[] keys = new NSObject[] {
        AVAudioSettings.AVSampleRateKey,
        AVAudioSettings.AVFormatIDKey,
        AVAudioSettings.AVNumberOfChannelsKey,
        AVAudioSettings.AVLinearPCMBitDepthKey,
        AVAudioSettings.AVLinearPCMIsBigEndianKey,
        AVAudioSettings.AVLinearPCMIsFloatKey
    };

    AVAudioRecorder recorder;
    NSError error;
    NSDictionary settings;

    public RedordDep()
    {
        settings = NSDictionary.FromObjectsAndKeys(values, keys);
    }

    public string Prepare()
    {
        NSUrl path = NSUrl.FromString(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), DateTime.Now.Ticks.ToString() + ".wav"));
        recorder = AVAudioRecorder.Create(path, new AudioSettings(settings), out error);
        bool prepared = recorder.PrepareToRecord();
        return path.Path;
    }
}

Edit:
I found out that this also happens in other cases when using AVFoundation.
In my case it happened when I tried to initialize a video recorder and audio recorder.

A: After researching this
Stacktrace
I found out that it is related to the security options that are introduced to iOS 10. I just had to add Usage Description Keys I needed.
"NSCameraUsageDescription" and "NSMicrophoneUsageDescription"


text:
Q: How do I kill a function when i start another one? Hey guys I have the following code so when I click on another function I would like to stop the one is running.
So I am clicking on phone_icon and start phoneAnimation() then if I click on alarm_icon I want to stop phoneAnimating() function and start alarmAnimating()
Any idea how do I solve this as now is running the other one in behind?
$('#phone_icon').on('click', function(e){
    e.stopPropagation();
    clearInterval(alarmIsAnimating);
    clearInterval(notificationIsAnimating);
    clearInterval(fbIsAnimating);
    var animation = document.getElementById('phone_sprite');
    var repeat = 0;
    var phonetl = new TimelineMax();
        phonetl.to("#phone_L", 0.5, {x:-403, ease:Power4.easeInOut})
        .to("#f2_copy", 1, {opacity:0, ease:Power4.easeInOut}, "-=1")
        .to("#initial_sprite", .8, {repeat:0, backgroundPosition:"0px -5760px", ease:SteppedEase.config(8)})
        .to("#phone_icon", 0.5, {css:{background: "url(images/active_icon1.png)"}})
        .to("#alarm_icon", 0.5, {css:{background: "url(images/alarm_icon.png)"}}, "-=0.5")
        .to("#text_icon", 0.5, {css:{background: "url(images/text_icon.png)"}}, "-=0.5")
        .to("#fb_icon", 0.5, {css:{background: "url(images/fb_icon.png)"}}, "-=0.5")
        .to("#f2_copy1", 1, {opacity:1, ease:Power4.easeInOut}, "-=1")
        .to(["#f2_copy3", "#f2_copy2", "#f2_copy4"], 1, {opacity:0, ease:Power4.easeInOut}, "-=1")
        .to("#initial_sprite", 1, {opacity:0, ease:Power4.easeInOut}, "-=1")
        .to("#phone_sprite", 1, {opacity:1, ease:Power4.easeInOut}, "-=1");
        phoneAnimating();
        function phoneAnimating() {
            clearInterval(phoneIsAnimating);
            // console.log('phone');
            var frameHeight = 720;
            var frames = 9;
            var frame = 0;
            phoneIsAnimating = setInterval(function () {
            var frameOffset = (++frame % frames) * -frameHeight;
            animation.style.backgroundPosition = "0px " + frameOffset + "px";
                if(frame == 9){
                    clearInterval(phoneIsAnimating);
                        repeat++
                        TweenLite.delayedCall(1,phoneAnimating);
                    }
                }, 100);
        }
    });
    $('#alarm_icon').on('click', function(e){
    e.stopPropagation();
    clearInterval(phoneIsAnimating);
    clearInterval(notificationIsAnimating);
    clearInterval(fbIsAnimating);
    var animation = document.getElementById('alarm_sprite');
    var repeat = 0;
    var alarmIsAnimating;
    var alarmtl = new TimelineMax();
        alarmtl.to("#phone_L", 0.5, {x:-403, ease:Power4.easeInOut})
        .to("#f2_copy", 1, {opacity:0, ease:Power4.easeInOut}, "-=1")
        .to("#initial_sprite", .8, {repeat:0, backgroundPosition:"0px -5760px", ease:SteppedEase.config(8)})
        .to("#alarm_icon", 0.5, {css:{background: "url(images/active_icon2.png)"}})
        .to("#phone_icon", 0.5, {css:{background: "url(images/phone_icon.png)"}}, "-=0.5")
        .to("#text_icon", 0.5, {css:{background: "url(images/text_icon.png)"}}, "-=0.5")
        .to("#fb_icon", 0.5, {css:{background: "url(images/fb_icon.png)"}}, "-=0.5")
        .to("#f2_copy2", 1, {opacity:1, ease:Power4.easeInOut}, "-=1")
        .to(["#f2_copy3", "#f2_copy4", "#f2_copy1"], 1, {opacity:0, ease:Power4.easeInOut}, "-=1")
        .to("#phone_sprite", 0, {opacity:0, ease:Power4.easeInOut}, "-=1")
        .to("#alarm_sprite", 0, {opacity:1, ease:Power4.easeInOut}, "-=1")
        alarmAnimating();
        function alarmAnimating() {
            clearInterval(phoneIsAnimating);
            // console.log('alarm');
            var frameHeight = 720;
            var frames = 9;
            var frame = 0;
            alarmIsAnimating = setInterval(function () {
            var frameOffset = (++frame % frames) * -frameHeight;
            animation.style.backgroundPosition = "0px " + frameOffset + "px";
                if(frame == 9){
                    clearInterval(alarmIsAnimating);
                        repeat++
                        TweenLite.delayedCall(1,alarmAnimating);
                    }
                }, 100);
        }
    });

A: You can use stop function to stop the currently running animation
Here is the Documentation

A:

input = document.getElementById("input");
function start() {
    add = setInterval("input.value++",1000);
}start();
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop"/>

or If you are using animation then
.stop is a method for stopping animations that is running asynchronously (in the background) on the current element. It doesn't interrupt/stop any other code that isn't using the effects library.
Instead you should take a look at .queue which lets you setup custom queues that you can clear or dequeue.
There already exist very good answers on how to use .queue so I'll point you to that question instead: Can somebody explain jQuery queue to me? - Look at the answer by gnarf.


text:
Q: Global variable for language_id available in views and in models I'm trying to share a session variable in both the controllers, the views and the model.
With the following code, it is working in the controllers and in the views :
class ApplicationController < ActionController::Base
    protect_from_forgery
    helper_method :best_language_id

    # Returns the ID of the language to use to display the description.
    def best_language_id
        @best_language_id ||= session[:best_language_id]
        @best_language_id ||= current_project.default_language.id
        return @best_language_id
   end
end

But I can't call it from the model.
I would like to be able to call best_language_id either in the controllers, views and in one model, to get a fallback of the best_language_id if a translation is not found.
Example in my model (not working) :
class Point < ActiveRecord::Base
    # Retuns the attached word in the given language if exists.
    # Otherwise, falls back on another translation
    def word(preffered_language_id)
        word = Word.find(:translation_id => self.translation_id, :language_id => preffered_language_id)
        if word.blank?
            word = translations.where(:translation_id => self.translation_id, :language_id => best_language_id)
        end
        return word
    end
end

I know that model should not include applicationcontroller method calls, but how is it possible to share my best_language_id accross controllers and model ?
Edit : using i18n is not the question here. Translations are not fixed string but variables in a database.
Thanks for helping !

A: I would suggest you switch the situation around, store the best_language_id in the model as a class accessor, then you can set and get it from your controllers and it will still be available in the models.
class Point < ActiveRecord::Base
  cattr_accessor :best_language_id # to store the variable
end

# Persist the content of that variable at the start of every action
class ApplicationController < ActionController::Base
  before_filter :set_best_language

  def set_best_language
    Point.best_language_id = session[:best_language_id]
    Point.best_language_id ||= current_project.default_language.id
  end
end

# Use the variable in a controller
class SomeOtherController < ActionController::Base
  def show
    @best_language = Language.find(Point.best_language_id)
    ...
  end
end

# Use the variable in a model
class SomeOtherController < ActiveRecord::Base
  def some_method
    best_language = Language.find(Point.best_language_id)
    ...
  end
end

A: In your rails app, you have a base module in config/application.rb. It should be named after your application. Let's say its called MyApp. What you could do is define two methods like this:
module MyApp
  ...
  def self.language_id=(value)
    @language_id = value
  end

  def self.language_id
    @language_id ||= 'en' # default vaule
  end
  ...
end

Then, in app/controllers/application_controller.rb add a before_filter like this:
before_filter :language
def language
  MyApp.language_id = session[:language_id] if session[:language_id]
end

Then, from all over the app, you can access the value via
MyApp.language_id

Needless to say that the approach is not thread safe so don't use it in a threaded environment.


text:
Q: Как удалить из столбца строку с пустым списком? Дан датафрейм:
d = {'name': [['rick', 'mike', 'morty'], [], ['brick', 'nick'], ['rick', 'reaven', 'bart', 'homer'], ['rick', 'morty']],
     'Date': ['11/05/2011', '9/02/2010', '1/01/2014', '12/20/2020', '9/30/2009'],
     'Address': ['AR', 'YU', 'RU', 'EU', 'BY']}
df = pd.DataFrame(data = d)

Как удалить строку с пустым списком?

A: Воспользуйтесь методом Series.str.len():
res = df.loc[df["name"].str.len().gt(0)]

результат:
In [104]: res
Out[104]:
                          name        Date Address
0          [rick, mike, morty]  11/05/2011      AR
2                [brick, nick]   1/01/2014      RU
3  [rick, reaven, bart, homer]  12/20/2020      EU
4                [rick, morty]   9/30/2009      BY

A: Можно через apply применить len и потом проверить, что длина списка не нулевая:
df = df[df['name'].apply(len) > 0]

df после этого:
    name                        Date        Address
0   [rick, mike, morty]         11/05/2011  AR
2   [brick, nick]                1/01/2014  RU
3   [rick, reaven, bart, homer] 12/20/2020  EU
4   [rick, morty]                9/30/2009  BY

A: вот так еще тоже работает:
df.loc[df.name.astype(bool)]
'''
                          name        Date Address
0          [rick, mike, morty]  11/05/2011      AR
2                [brick, nick]   1/01/2014      RU
3  [rick, reaven, bart, homer]  12/20/2020      EU
4                [rick, morty]   9/30/2009      BY

A: Если вам нужно удалить сам список, то можно с помощью цикла for таким образом:
for i in d['name']:
    if len(i) == 0:
        del d['name'][d['name'].index(i)]

Обратите внимание, что если пустых списков будет больше одного, то это не сработает. Уточните, если необходимо удалить произвольное количество пустых списков.
Если нужно удалить из словаря весь ключ, где находится пустой список, со всеми значениями:
flag = False
for i in d:
    for j in d[i]:
        if len(j) == 0:
            del d[i]
            flag = True
            break
    if flag:
        break


text:
Q: css position issue within Internet Explorer I've created a jsfiddle:
http://jsfiddle.net/daFalk/dx3xLgLq/2/
its all about the css styles
div.ding-wrap {
    position: absolute;
}

As you can see there is an image well positioned if you open it with chrome or any other normal browser.
But if I open it with internet Explorer the image is gone! I need to change the positioning of ding-wrap to relative.
i would do so, but then my animations (not there) does not work very well. So I need the positioning absolute. How can I teach IE to take me serious?
Thanks, Falk

A: jiangshui gave a push in the right direction. I stopped centering via table and table-cell and used
margin: auto;
height: 100%;

for centering. Sadly, always if I googled vertical centering, everywhere I read only about the first method because the auto-margin shouldnt work. And I never tried. So thanks a lot to jiangshui!
Here the updated jsfiddle:
http://jsfiddle.net/daFalk/dx3xLgLq/5/


text:
Q: Why is $n$ divided by $n$ equal to $1$? I've understood how to apply this operation for many years but I recently was reminded that:
$n^0 = 1$
Which in high school I accepted and just "solved for", but I'm now curious. Why is that true? So my own cursory research on the internet led me to the most common proof (using recurrence):
$b^1 = b$
$b^{n+1} = b^n \cdot b$
$b^0 = \frac{b^1}{b} = 1$
The most common proof for it relies on the fact that $\frac{n}{n} = 1$ so I started wondering why is that so? There's the rather obvious examples given by teachers using a pie but it feels like there's something else there. Maybe that something else involves Mathematics that is out of my league at the moment (the highest amount I've taught myself is through Algebra).

A: $\frac ab$ is, by definition, the solution of the equation $bx=a$. Thus $\frac nn$ is the solution to the equation $nx=n$. Assuming $n\neq0$, this equation has the unique solution $1$.

A: Here is how an algebraist might answer the question.
Take the rationals to be the fraction field of the integers, and embed $\mathbb{Z}\hookrightarrow \mathbb{Q}$ by associating $a$ to the class $[a/1]$.  In $\mathbb{Q}$ we have the relation $[a/b]=[c/d]$ if and only if $ad=bc$.  Apply this to show that $[n/n]=[1/1]=1\in\mathbb{Z}$.

A: Most of the math systems you're familar with (the standard definitions of addition and multiplication over real numbers, rational numbers, or complex numbers) are fields, so you need to look at the field axioms. The most relevant here are:

*

*There exists an additive identity 0 such that for all a, a + 0 = a. For example, in all of the familiar fields I mentioned above, the additive identity is the number 0.

*There exists a multiplicative identity 1 such that for all a, a · 1 = a. For example, in all of the familiar fields I mentioned above, the multiplicative identity is the number 1.

*For all a except 0, there exists a multiplicative inverse (denoted as a-1) such that a · a-1 = 1.
n/n is also written as n · n-1 --- in other words, it is n multiplied by its multiplicative inverse. By the third axiom, this is equal to the multiplicative identity, which is 1.

A: There are many different interpretations of division in elementary mathematics:
The expression $\frac{a}{x}$, or $a\div x$, can be interpreted as:

*

*The number of times that $x$ goes into $a$. For example, $\frac{10}{5}=2$ because $5$ goes into $10$ twice. The symbolic way of putting this is $\frac{a}{x}=q \equiv xq=a$ (here the symbol "$\equiv$" denotes equivalence). With this interpretation, $\frac{x}{x}=1$ because $x$ goes into $x$ once, or because $x1=x$.

*The number that goes into $a$ $x$ times. For example, $\frac{10}{5}=2$ because $2$ goes into $10$ $5$ times. The symbolic way of putting this is $\frac{a}{x}=q \equiv qx=a$. With this interpretation, $\frac{x}{x}=1$ because $1$ goes into $x$ $x$ times, or because $1x=x$. This interpretation is the same as interpretation 1 because $qx=xq$,  the commutativity of multiplication.

*The ratio of $a$ and $x$, i.e. $a$ per $x$. This can be thought of best in terms of rates. Think of two objects, $A$ and $X$, traveling along the number line at constant velocity. $A$ travels from $0$ to $a$ in the same time interval in which $X$ travels from $0$ to $x$. Then $\frac{a}{x}$ is the distance that $A$ travels for each unit distance that $X$ travels, or the distance that $A$ travels in a certain time interval divided by the distance that $X$ travels in that same time interval. For example, $\frac{10}{5}=2$ because in this case $A$ travels a distance of $2$ every time $X$ travels a unit distance, and in any time interval, $A$ will travel twice as far as $X$. With this interpretation, $\frac{x}{x}=1$ because $X$ will travel a distance of $1$ for each unit distance that an object of identical trajectory travels.

*$a$ $x$ths. For example, $\frac{10}{5}$ is $10$ fifths, which is $2$. The symbolic way of putting this is $\frac{a}{x}=a\times\frac{1}{x}$. With this interpretation, $\frac{x}{x}=1$ because $x$ $x$ths of something is $1$.

The above list is not exhaustive; there are other ways of interpreting division.
However, you don't need division to show that $x^{0}=1$. Here is an alternative way.
Let $S$ be a multiset of numbers (a multiset is a set in which elements can appear more than once), for example $\left\{2,3,3,6\right\}$. Let $\Pi(X)$ denote the product of all the numbers in the set $X$, and let $\Sigma(X)$ denote the sum of all the numbers in the set $X$. When adding and multiplying, the order and grouping of the terms or factors has no effect on the result (this follows from an inductive argument on the number of terms/factors that uses the associative and commutative properties).  Thus if $S$ is separated into two disjoint sets $S_{1}$ and $S_{2}$ (for the above example, these could be $S_{1}=\left\{2,3\right\}$ and $S_{2}=\left\{3,6\right\}$), it is the case that $\Pi(S)=\Pi(S_{1})\times\Pi(S_{2})$ and $\Sigma(S)=\Sigma(S_{1})+\Sigma(S_{2})$. The result about the order and grouping of terms/factors only entails this if $S_{1}$ and $S_{2}$ are nonempty, but it would make sense to define $\Pi(X)$ and $\Sigma(X)$ such that it works for all sets $S_{1}$ and $S_{2}$, even empty ones. Let $S_{1}$ be the empty set, denoted $\varnothing$. Then $S_{2}=S$. We want to have $\Pi(S)=\Pi(\varnothing)\times\Pi(S)$ and $\Sigma(S)=\Sigma(\varnothing)+\Sigma(S)$, so we must define $\Pi(\varnothing)=1$ and $\Sigma(\varnothing)=0$.
What we have shown is that the sum of all the elements in the empty set is $0$ and the product of all the elements in the empty set is $1$. When we write $x^{n}$, we are taking the product of all the elements in the multiset that has $x$ in it $n$ times and nothing else. So $x^{0}$ is the product of all the elements in the empty set, or $\Pi(\varnothing)$. Therefore $x^{0}=1$. This argument can also be used to show that $0!=1$, as this is also $\Pi(\varnothing)$.

A: Given $n \neq 0$, lets assume $n/n = x$, where $x \neq 1$. Now,
$n/n = x\\n = x \times n\\n - x\times n = 0\\n\times (1-x) = 0$
Now, as $n \neq 0$, so $\textbf{(1-x) = 0}$ must be true. Otherwise the last line can not be true.
$(1-x) = 0\\x = 1$
We come to a contradiction. So, $n/n = x$, where $x \neq 1$ is false. So, $\textbf{n/n = 1}$.

A: Here is another proof of $b^0=1$ for every non-zero $b$ in $\Bbb Z$, which doesn't require division.
First of all
$$
b^0=b^{0+0}=b^0b^0
$$
means that $b^0$ is an idempotent in $\Bbb Z$. Moreover, it is non-zero, since
$$
0\neq b=b^{1+0}=bb^0
$$
Now observe that the only non-zero idempotent in $\Bbb Z$ is $1$. Indeed, let $e\neq 1$ be another one. Then
$$
e(e-1)=ee-e=e-e=0
$$
which is absurd, since by hypothesis $e\neq 1,0$ and there are no zero-divisors in $\Bbb Z$, i.e. each time $ab=0$ either $a=0$ or $b=0$.

Note: To prove that $a^{m+n}=a^na^m$ you don't need division. It is a straightforward consequence of the associative property of the product.

A: Here's a way to think about it:
The following "proof" relies on the fact that multiplication by 1 doesn't change the value and that division is the inverse of multiplication:
We want to evaluate the fraction $\frac{n}{n}$:
The value will stay the same if we multiply it by 1, so:
$\frac{n}{n} = 1 \cdot \frac{n}{n} $
This expression can also be written as:
$1 \cdot n \div n$
Meaning "1 multiplied by n and then the result divided by n".
Division is the inverse of multiplication, so multiplying by a number and then dividing by that same number has no effect, so basically:
$\frac{n}{n} = 1 \cdot \frac{n}{n} = 1 \cdot n \div n = 1$

A: Basically x/y can be defined as how many times you can take y from x till y becomes 0. So in this respect, 1 can be taken from 1 only 1 times and we are left with 0 and therefore 1/1 is 1.
I hope this is a simple answer without much complications.

A: I have considered a more axiomatic approach to dividing a pie. Consider the real numbers $\mathbb{R}$. It is a field. This comes from properties of equivalence classes of all rational Cauchy-sequences. Then for any $n \in \mathbb{Z} \subset \mathbb{R}$, $n \neq 0$ there is a multiplicative inverse $n'\in \mathbb{R}$, that satisfies $nn'=1$. Denote $n'$ by $\frac{1}{n}$. The equation $nn'=1$ corresponds to taking $n$ pieces of a pie that is divided into $n$ pieces. The fraction $\frac{m}{n}$ means by definition $m \frac{1}{n}$ because it corresponds to taking $m$ pieces, that are of the size $\frac{1}{n}$. The definition of $\frac{m}{n}$ was constructed in an intuitive way but has also an axiomatic formalisation using the multiplicative inverse. Now we can calculate
\begin{equation}
\frac{n}{n} = n \frac{1}{n} = 1
\end{equation}
whenever $n \neq 0$. Note that this isn't the definition in algebra studybooks, but because of the nature of the problem I tried to find an axiomatic formulation to the way, I have learned using fractions in the comprehensive school.

A:
Definition: In mathematics, especially in elementary arithmetic, division ($\div$) is an arithmetic operation. Specifically, if $b$ times $c$
   equals $a$, written:
$\color{red}a = \color{blue}b \times \color{green}c$
where $b$ is not zero, then $a$ divided by $b$ equals $c$, written:
$\color{red}a\div \color{blue}b = \color{green}c$

Using the definition and by letting $\color{green}c=\color{green}1$, $\color{blue}b=\color{blue}{1/n}$ where $n$ is a non zero real number, $\color{blue}b$ times $\color{green}c$ is equal to a number $\color{red}a$:
$$
\color{red}a=\color{blue}{\dfrac1n}\times\color{green}1=\color{red}{\dfrac1n}
$$
Therefore, from the definition:
$$
\color{red}a\div\color{blue}b=\color{green}c
\\\Downarrow\\
\begin{align}
\color{red}{\dfrac1n}\div\color{blue}{\dfrac1n}&=\color{green}c \tag{1}\\\,\\
\color{red}{\dfrac1n}\cdot\dfrac n1 &=\color{green}c \tag{2} \\\,\\
\color{black}{\dfrac nn} &=\color{green}c\\\,\\&=\color{green}1
\end{align}$$
Thus for any non zero real number $r$ we have that: $$\dfrac rr=1.$$
$\blacksquare$

If you search for why the procedure I applied when going from step $\text{(1)}$ to step $\text{(2)}$ is correct, check this answer: Why is $\frac{1}{\frac{1}{X}}=X$?

A: In higher math, you usually take the equation $n/n=1$ as the definition of division by $n$. Specifically, $1/n$ is defined to be the unique number such that $1/n$ times $n$ is 1. Then you go on from there to define $2/n$ and other numbers using ideas called equivalence classes.
So it's that way because mathematicians feel like it. Like Bill Thurston said, math isn't real, it's just a way of organizing human thought.

A: The way that I see $a^{0} = 1$ is that people want to have the following rule to hold in any number system with a multiplication: $a^{m + n} = a^{m}a^{n}$.
In order for this rule to hold, it is inevitable to define that $a^{0} = 1$.

A: You don't need division. $\ b^{n+1} = b\, b^n\stackrel{\large n=0}\Rightarrow b = b\, b^0\,\Rightarrow\,b(b^0\!-1) = 0\,\Rightarrow\, b^0 = 1\,$ if $\,b\ne 0.$

A: For another neat definition of $a^b$ when $a,b$ are nonnegative integers: It is the number of maps from a set $B$ of $b$ elements to a set $A$ of $a$ elements. If $B$ is empty, there is exactly one such map, no matter what $A$ is. Why? To describe such a map we need to specify for each element of $B$, which element of $A$ it is mapped to. So, let's try to do this explicitly when $B$ is empty. Ready? Here we go. Starting ... done.

A: Any algebraic proof that division of a number by itself equals 1 is a tautology; the proof invariably accepts that it is true, therefore it's true because it's true.
For instance, the top-voted answer states that $a/b$ is the solution to the equation $bx=a$ because it is "the definition of division" (which is true). However, to algebraically show this in small logical steps, we divide both sides of this equation by $b$, producing the intermediate $bx/b = a/b$, and then by the associative property of both multiplication and division, $(b/b)x = a/b$. Now, to take the last step, we must assume two things to be true: that $b/b=1$ so that $1*x = a/b$, and that $x*1=x$ so that $x=a/b$.
Therefore, we cannot prove $n/n=1$ except in terms of itself (not even by generalizing using abstract algebra and its definition of multiplication). It is an axiom, a postulate, as is $n*1=n$ (the multiplicative identity, which is also axiomatic in the abstract realm); something self-evident that forms the basis of more complex reasoning. You must accept it as true for our system of mathematics to function.
If $n/n \neq 1$, then multiplying both sides by $n$ produces $n \neq 1*n$, and thus if you still accept the multiplicative identity axiom, $n \neq n$ violating the reflexive property of equality. To reject that $n/n=1$ thus means you must either also reject that 1 is the multiplicative identity (and thus it changes $n$ into "not $n$"), or you must reject that equality is a reflexive comparison operation (that something always equals itself). If you do either of those, you're no longer speaking our mathematical language.

A: Because $1$ is the multiplicative identity element and the multiplication is injective in $\mathbb{R}\setminus\{0\}$. And that's why $\frac00$ isn't defined, the multipication isn't injective in $\mathbb{R}$. And $0^0$ is defined just as $\lim\limits_{x\to0}x^x$.


text:
Q: Set unique field in list of dictionaries to be inserted into mongo db I have a list of dictionaries that look something like this;
json_data = [
  {
    "CODE": "018906",
    "X": "29813.66349",
    "Y": "28697.520760000003"
  },
  {
    "CODE": "018907",
    "X": "30041.8389",
    "Y": "28602.98724"
  },
  {
    "CODE": "018910",
    "X": "31966.120789999997",
    "Y": "29115.75337"
  },
]

I tried to insert json_data into a mongodb collection mongo_collection.
mongo_collection.insert_many(json_data)
It ran successfully. However, I want the key field CODE to be unique and insert should fail if there is a duplicate. The line above will insert every document even if there is duplicate CODE. How can I make CODE key unique? I am open to using python libraries like mongoengine.
I would like CODE to be something like a primary key in a relational database.
I am using python 3.7, mongodb 4.2.7 and pymongo.

A: Before inserting,
You would need to create an index in MongoDB and mark CODE field as a unique index
creating index in mongo
db.mongo_collection.createIndex({CODE:1}, {unique:true})

This would ensure you get a duplicate key error if you try to insert CODE that already exists.
If you don't have access to MongoDB server.
You would need to populated _id with value as same as CODE. Since _id is a default primary index in mongo.
json_data = [
  {
    "_id": "018906",
    "CODE": "018906",
    "X": "29813.66349",
    "Y": "28697.520760000003"
  },
  {
    "_id": "018907",
    "CODE": "018907",
    "X": "30041.8389",
    "Y": "28602.98724"
  },
  {
    "_id": "018910",
    "CODE": "018910",
    "X": "31966.120789999997",
    "Y": "29115.75337"
  },
]

A: I would like to answer my own question to build on Anurag Wagh's answer as the syntax he used is not python. I have marked his answer as the correct one.
Since I am using pymongo, the syntax of the code should be;
import pymongo
mongo_collection.create_index([("CODE", pymongo.ASCENDING)], unique=True)


text:
Q: How is the date argument formatted in the euronext data download url? I'd like to download historical stock prices from nyx.com with a script. The download URL has to following from:
https://europeanequities.nyx.com/nyx_eu_listings/price_chart/download_historical?typefile=csv&layout=vertical&typedate=dmy&separator=point&mic=XPAR&isin=FR0010557264&name=AB%20SCIENCE&namefile=Price_Data_Historical&from=1356998400000&to=1386115200000&adjusted=1&base=0
The format of most arguments is obvious, except for the "from" and "to" arguments, which determine the begin and end date of the historical prices. In this example, the begin date is January 1, 2013 and the end date is December 4, 2013. How are these dates transformed into numbers like 1356998400000 and 1386115200000?
P.S. I'd rather not use Yahoo finance due to the large amount of errors in the data, especially for the European Markets.

A: In case you are still interested by the answer : The numbers used for "to" and "from" fields are timestamps with respect to the millisecond and not to the second as usual.
Basicaly, this is the number of milli-seconds elapsed since January the first 1970 0h00m00s000 UTC.
For the first number, 1356998400000, you can truncate the last three 0 to convert it to a classic timestamp (remove milli-seconds part). Any timstamp convertor will map 1356998400 to 1/1/2013 1:00:00
For the second number, once truncated, 1386115200 converts to 12/04/2013 1:00:00
Hop it'll help and thanks for the link to nyx.com ! Was looking for something like that for a long time !


text:
Q: lastInsertId get from different function I have a form, wich sends information to the database (When filled in)
Form function:
function train_add() {
            $sql = "INSERT INTO train_information "
        . "(train_id, image, train_name, tare_weight, number_of_bogies, number_of_axles, wheel_diameter_min, wheel_diameter_max)"
        . "VALUES (train_id, :image, :train_name, :tare_weight, :number_of_bogies, :number_of_axles, :wheel_diameter_min, :wheel_diameter_max) ";
            $sth = $this->pdo->prepare($sql);
            $sth->bindParam(':image', $_POST['image'], PDO::PARAM_STR);
            $sth->bindParam(':train_name', $_POST['train_name'], PDO::PARAM_STR);
            $sth->bindParam(':tare_weight', $_POST['tare_weight'], PDO::PARAM_STR);
            $sth->bindParam(':number_of_bogies', $_POST['number_of_bogies'], PDO::PARAM_STR);
            $sth->bindParam(':number_of_axles', $_POST['number_of_axles'], PDO::PARAM_STR);
            $sth->bindParam(':wheel_diameter_min', $_POST['wheel_diameter_min'], PDO::PARAM_STR);
            $sth->bindParam(':wheel_diameter_max', $_POST['wheel_diameter_max'], PDO::PARAM_STR);
            $sth->execute();
            return $this->pdo->lastInsertId('train_id');
    }

Right. So when the form is filled in, it is send to the database (works).
The user will be redirected in 10 seconds (Did this for myself to see if any errors come up).
<?php
        //Train information is send to the database, and selects the ID of the just added train//
        $add_train = $database->train_add();
    ?>

    <meta http-equiv="Refresh" content="10;url=http://localhost:8080/show_axle_table.php?train_id="<?php ['$id'] ?> >

show_axle_table.php:
<?php
    $show_axle = $database->axles();
?>

                Train id
                Number of bogies
                Number of axles

            <?php
                foreach($show_axle as $res){
                //Loop trough results, generate a tablerow every time
            ?>

                <?php
                echo "" . $res['train_id'] . "	";
                echo "" . $res['number_of_bogies'] . "	";
                echo "" . $res['number_of_axles'] . "	";
                ?>

        <?php
            }
        ?>

And the function:
function axles(){
        $id2 = $this->train_add($id);
        $sql = "SELECT * FROM train_information WHERE train_id = '$id2'";
        $sth = $this->pdo->prepare($sql);
        $sth->bindParam(":id2", $_GET["train_id"], PDO::PARAM_STR);
        $sth->execute();
        return $sth->fetchAll();
    }

Now the table shows me a ID of a train. But it adds 1 so everything else is empty.
For example:
User fills in form. Sends it to Database (train_add) It gets and id of 1 and is done.
Then the page redirects to the show_axle_table.php. Function should get the last inserted id. but it shows me a ID of 2.
Also i want the ID to be shown in the top of my page like:
show_axle_table.php?train_id="<?php ['$id'] ?>

But right now it shows nothing. (train_id=)

A: Update like this:
<?php
        //Train information is send to the database, and selects the ID of the just added train//
        if (!(isset($_GET['train_id]) && $_GET['train_id'])) {
            $add_train = $database->train_add();
        }
    ?>

    <meta http-equiv="Refresh" content="10;url=http://localhost:8080/show_axle_table.php?train_id="<?php echo $add_train; ?> >

<?php
    $show_axle = $database->axles($_GET['train_id']);
?>

                Train id
                Number of bogies
                Number of axles

            <?php
                foreach($show_axle as $res){
                //Loop trough results, generate a tablerow every time
            ?>

                <?php
                echo "" . $res['train_id'] . "	";
                echo "" . $res['number_of_bogies'] . "	";
                echo "" . $res['number_of_axles'] . "	";
                ?>

        <?php
            }
        ?>

And function as
function axles($id){
        $sql = "SELECT * FROM train_information WHERE train_id = '$id'";
        $sth = $this->pdo->prepare($sql);
        $sth->bindParam(":id2", $_GET["train_id"], PDO::PARAM_STR);
        $sth->execute();
        return $sth->fetchAll();
    }


text:
Q: Angular 2 pass a parameter that's on the submit button For various reasons I have 2 submit buttons in a form. But I need to be able to work out which submit button was clicked on. So far I am using the below, but how could I add a different parameter on each submit button?
<button type="submit" [disabled]="!f.valid">Approve</button>

Perhaps I could add a data tag to the button and pass the event to the ngSubmit function somehow?


text:
Q: How do I draw an Ideal line between two headers? My HTML code has this structure:
h1 {
  text-align: center;
  font-size: 20pt;
  padding-bottom: 0;
}

h2 {
  text-align: center;
  font-size: 16pt;
}

  ...

Title

Sub

  ...

I want to "draw" a line between those two headings like this:

It should adjust to the width of the headings:

(Excuse my image editing skills)
Is there a simple css-only way to do so?

A: The easiest and most flexible way i think is to use Flexbox. Just add some left and right padding to h1 and h2 elements so line can always be a bit longer then text.

body {
  text-align: center;
}
.container {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
h1 {
  font-size: 20px;
  padding: 0 10px;
}
h2 {
  font-size: 16px;
  padding: 0 10px;
}
.line {
  height: 3px;
  width: 100%;
  background: red;
}

Lorem ispum

Sub

Ispum

Lorem ipsum dolor sit amet.

Update: You can actually do this with  pseudo-element on .container but you need to specify order so that line shows after h1 element.

body {
  text-align: center;
}
.container {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
.container > h1 {
  order: 1;
  font-size: 20px;
  padding: 0 10px;
}
.container > h2 {
  padding: 0 10px;
  order: 3;
}
.container:before {
  content: '';
  height: 3px;
  width: 100%;
  background: red;
  order: 2;
}

Lorem ispum

Sub

Ispum

Lorem ipsum dolor sit amet.

A: You can handle this problem with a simply pseudo element. No html structure changing or non-support css of cross browers.
We need to use table display on the parent and make a new element (your border with pseudo) on the
.
Look at this example:

#container {
  display: table;
  margin: 0 auto;
  text-align: center;
}

h1:after {
  content:"";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  border-bottom: 3px solid red;
}

h1, h2 {
  margin: 5px 0;
  padding: 0 10px 5px;
}

h1 {
  position: relative;
  font-size: 20pt;
}

h2 {
  font-size: 16pt;
}

long long title

Sub

h1

Sub

h1

long long subtitle

Fiddle demo

A: Try this:
#container {
  text-align: center;
}

h1 {
  border-bottom: 2px solid red;
  padding-bottom: 10px;
}

/* h2 {
  padding-top: 0px;
  margin-top: 0px;
} */


text:
Q: How to ensure app is deployed before moving to next stage using DevOps YAML pipeline? I have a yaml pipeline that is deploying a web API application. Immediately after deployment, I need to run another job/task, that updates APIM with the new endpoint swagger file.
The problem I have, is that the endpoint is not available for 'some' time when performing the apim@5 task. This results in a failure.
Is there any way I can force the pipeline to wait until the endpoint returns 200 OK before continuing? Maybe with a timeout?
Here's the pipeline:
- stage: DeployApp
  variables:
  jobs:
  - deployment: DeployApiApp
    strategy:
      runOnce:
        deploy:
          steps:
          - task: AzureRmWebAppDeployment@4
            inputs:
              ConnectionType: 'AzureRM'
              azureSubscription: 'MySub'
              appType: 'webAppLinux'
              WebAppName: $(appName)
              packageForLinux: '$(Pipeline.Workspace)/drop/myapp.zip'
              RuntimeStack: 'DOTNETCORE|5.0'

  - job:
    dependsOn:
    - DeployApiApp
    pool:
      vmImage: 'windows-latest'
    displayName: Update APIM APIs
    steps:
      - task: apim@5
        inputs:
          ConnectedServiceNameARM: 'MyServiceConnection'
          ResourceGroupName: 'rg-$(resourceSuffix)'
          ApiPortalName: 'apim-$(resourceSuffix)'
          OpenAPISpec: 'v3'
          Format: 'json'
          Authorization: 'None'
          SwaggerPicker: 'Url'
          swaggerlocation: 'https://$(appName).azurewebsites.net/swagger/v1/swagger.json'
          targetapi: 'myApi'
          DisplayName: 'MyApi'
          pathapi: 'api'
          subscriptionRequired: false
          TemplateSelector: 'CORS'

A: I usually put a smoke test step right after deployment to make sure the app is running and warmed-up.
Something like:
- script: curl https://$(appName).azurewebsites.net
  displayName: 'smoke test'

If you expect it to take more time and possibly throw some errors before it's ready, you can add retries:
- pwsh: |
    $url = "https://$(appName).azurewebsites.net"
    write-host "testing '$url'"
    $retries = 5
    do {
      $retries -= 1
      curl --show-error --fail $url
      if ($lastExitCode -ne 0 -and $retries -ge 0) {
        start-sleep -seconds 5
      }
    } while($retries -ge 0)
  displayName: 'smoke test'

A: I come up with a solution by using Delay Task and Invoke REST API for this type of scenario. These are run on an agentless Job
I'll give you a visual editor for the pipeline just for your understanding, From the below visual editor image you can see I set a delay of 10 min after that I call a invoke rest API which can help to call your API and get the response you need


text:
Q: Can anyone help me with my C code in this Visual Studio scanf error C6031 #include <stdio.h>
int main(void)
{
    int num1, num2, num3;

    printf("Enter First Number");
    scanf("%d", &num1);
    printf("Enter First Number");
    scanf("%d", &num2);
    printf("Enter First Number");
    scanf("%d", &num3);

    printf("The numbers in  reverse order : %d %d d% ", num1, num2, num3);

    return 0;
}

A: #include <stdio.h>
int main(void)
{
    int num1, num2, num3;

    printf("Enter First Number");
    scanf("%d", &num1);
    printf("Enter second Number");
    scanf("%d", &num2);
    printf("Enter third Number");
    scanf("%d", &num3);

    printf("The numbers in  reverse order : %d %d %d ", num3, num2, num1 );

    return 0;
}


text:
Q: Assign data to view in cakephp 3.6 In cakephp 1.1 we can use $this->data = array(value), so in ctp file, control (input, checkbox, ...) can received data automatically.
How can i do the same in cakephp 3.6?
I have try some solution but they don't work.
Thank you very much.

A: In cakephp 3.6, you can use Controller set method to pass data on the ctp file
Cake\Controller\Controller::set(string $var, mixed $value)

The Controller::set() method is the main way to send data from your
  controller to your view. Once you've used Controller::set(), the
  variable can be accessed in your view:

$form = $this->Model->get($id); // to get data from the database
$this->set('form', $form); // to pass data on the ctp file

Then you can directly pass to your form to automatically detect data:
$this->Form->create($form);

CakePhp -> Controllers -> Setting View Variables


text:
Q: Need an approach to get the color codes from a css file I need an approach to find out the colors available in a CSS file and export it to an excel file
.download-hero, .download-version-toggle, a.is-version {
    color: #eaf5e9;
    background: #026e00
}

So I need to search if there is a color element. If so then I need to export it to an excel sheet like below.
.download-hero                   #eaf5e9
.download-version-toggle         #eaf5e9
a.is-version                     #eaf5e9

A: I agree with @georg that you shouldn't be doing this yourself due to complexity of parsing CSS. However, if the CSS you are parsing is relatively simple and predictable you could use regex to achieve it.
This example could be used for basic CSS (won't support media queries for example):

const css = `.download-hero, .download-version-toggle, a.is-version {
    color: #eaf5e9;
    background: #026e00
}

a > b {
    background-color: #026e00
    color: black;
}`;

const selectorExp = /\s*([^{]+?)\s*\{\s*([^}]+?)\s*\}/g;
const colorExp = /(^|[\s;])color\s*:\s*([^;]+)/i;

let selectorMatch;
let colors = [];

while (selectorMatch = selectorExp.exec(css)) {
  const [match, selectors, rules] = selectorMatch;
  const colorMatch = colorExp.exec(rules);

  if (colorMatch) {
    colors = colors.concat(selectors.split(/\s*,\s*/g).map(s => ({
      selector: s,
      color: colorMatch[2],
    })));
  }
}

console.log(colors);


text:
Q: Microcontroller Vol Maximum Voltage compatibility I am having this microcontroller - S32K142 64 pins - 5V Core voltage
I have the below RESET signal connection which is provided by the MCU to the below transistor (which provides RESET to another microcontroller)

Transistor Datasheet BCR116W
I am checking the Vol and Voh compatibility between the microcontroller pin out and the Q0101 Transistor.
Suppose, if the Microcontroller outputs high, from the Microcontroller datasheet, Voh and Vol are not provided directly. They have only mentioned as Vdd-0.8V for Voh and 0.8V for Vol.
My questions :

*

*I am assuming the Voh of the microcontroller to be 3.2V (4V-0.8V=3.2V) (min). Is my assumption correct?

*If suppose my microcontroller provides a high to the RESET line, I am guaranteed atleast a 3.2V on the RESET, which happens to be greater than the worst case maximum turn on voltage of the transistor (1.4V).
Since, 3.2V > 1.4V - Transistor will turn ON. (Collector current is in the 250uA range)
But if I give low at the RESET pin of the microcontroller, since the Vol(max) as specified in the datasheet is only 0.8V, and the maximum turn off voltage of the transistor as given in the datasheet is 0.8V, there seems to be a mismatch in the compatibility, right?
Since, in worst case conditions, my Microcontroller outputs a 0.8V on the RESET for LOW signal, the maximum voltage that needs to be provided for a guaranteed turn off of the transistor at the worst case scenario is less than 0.4V (as mentioned in the table on page 3). Am I correct?
If my microcontroller provides 0.8V and the transistor turn off voltage threshold is 0.4V, the transistor might turn on and trigger falsely right?
Is my understanding correct?
If this is the case, what is the work around in the design?

A: The \$V_{oh}\$ and \$V_{ol}\$ specs you're referring to on page 31 of the datasheet aren't really specs on what output voltage the chip will provide. They're test conditions for the \$I_{oh}\$ and \$I_{ol}\$ specs.
The spec is saying, for example, if you externally force the output pin to +0.8 V when the chip is outputting low, the chip is guaranteed to sink at least 5 mA.
Since you don't have to sink any current at all to keep your transistor base below threshold, the outputs in your circuit will certainly achieve a lower output voltage than 0.8 V. In fact, since in your circuit the micro doesn't have to sink any current at all to pull the transistor base low (\$R_B\$ takes care of that), you should achieve very close to 0 V, and you should have no trouble turning the transistor fully off.


text:
Q: What should I do to move a sprite randomly between two specific placements? What should I do to move a sprite randomly between two specific placements.
For example, how can I implement this:
If direction = 90
Then, got to x:10 y:20 or x:30 y:50
(I have just started using scratch and have no coding experience so I won't be able to understand any code.)

A: Supplementary to Mithrandir's answer:
If you don't want to use a variable, you can do it like this:
This solution is basically the same but saves a little bit of time and space if you don't need to use the variable anymore.

Or, in pseudocode:
if (direction) = 90 then
  if {pick random (1) to (2)} = 1 then
    go to x: (10) y: (20)
  else
    go to x: (30) y: (50)

A: Here's one way you can do it:

if (direction) = 90 then
  set (variable) to {pick random (1) to (2)}
  if (variable) = 1 then
    go to x: (10) y: (20)
  else
    go to x: (30) y: (50)

The way this works is, when the trigger ((direction) = (90)) is met, we choose where to go by picking randomly between 1 and 2. The project then sets a variable to the value of the number picked. We can then use that value to decide which option gets picked. If the number 1 was picked, then go to one option; if it was the other (since there are no other options there's no need to out in an explicit IF (variable) = 2), go to the other spot.
Remember that you will need a hat block (a starting block) to start the script, though, such as WHEN GREEN FLAG CLICKED. Also note that if you just use an IF block immediately after a hat block, the script will just check it once immediately after the project starts. If you want this to happen in the middle of the project, wrapping this whole thing inside a FOREVER block might be a good thing to do.


text:
Q: Simple parameterized select query takes time to execute in C# I have a table structure like below :
CREATE TABLE [dbo].[MainTbl](
[RowNum] [int] IDENTITY(1,1) NOT NULL,
[TxtID] [varchar](20) NOT NULL,
[TxtKey] [varchar](20) NOT NULL,
[TrnDate] [datetime] NOT NULL,
[SrcID] [varchar](20) NOT NULL DEFAULT (''),
[ElemName] [varchar](20) NOT NULL,
[TblXml] [varchar](max) NOT NULL,
[ActiveStatus] [varchar](20) NOT NULL DEFAULT (''),
[DevLvl] [int] NOT NULL DEFAULT ((0)),
[Archive] [bit] NULL CONSTRAINT [DF_MainTbl_Archive]  DEFAULT ((0)),

CONSTRAINT [pkMainTbl] PRIMARY KEY CLUSTERED
([RowNum] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

and executing below query to fetch xml :
select TblXml from MainTbl with (nolock)
where TrnDate < @TrnDate and TxtID = @TxtID and TxtKey = @TxtKey
and ActiveStatus != 'NonActive' and ElemName = 'xyz' order by TrnDate desc

This query gets executed in SSMS in 5 seconds, but while executing via C# code,
It takes around 5+ minutes.
My C# code accepts query case no. in "BuildQuery" prepares above statement and
return a sqlcommand, I pass parameters and execute it, but "sqlCommand.ExecuteReader();" takes much time.
private bool MainFunction(parameters)
{
    CheckXMLDate(4,'9/6/2016 1:00:00 PM','ABC','123' );
}

________________________________

public bool CheckXMLDate(bldqry,TrnDate,TxtID,TxtKey )
{
    SqlCommand sqlCommand = BuildQuery(bldqry);

    sqlCommand.Parameters.AddWithValue("@TrnDate", TrnDate);
    sqlCommand.Parameters.AddWithValue("@TxtID", TxtID);
    sqlCommand.Parameters.AddWithValue("@TxtKey", TxtKey);
    SqlDataReader dataReader = sqlCommand.ExecuteReader();

    //Some statements like below...
    if (check == success)
   {    dataReader.Close();
        return true;}

    dataReader.Close();
    return false;
}
_______________________________________

public SqlCommand BuildQuery(int caseNum)
{
string QryString = string.Empty;
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Connection = con;

switch (caseNum)
{
case 4:
        {
            QryString = "select TblXml from MainTbl with (nolock) "+
                        "where TrnDate < @TrnDate "+
                        "and TxtID = @TxtID "+
                        "and TxtKey = @TxtKey " +
                        "and ActiveStatus != 'NonActive' and ElemName = 'xyz' order by TrnDate desc";
            break;
        }
 default:
        { break; }
}
sqlCommand.CommandText = QryString;
sqlCommand.CommandTimeout = 800;
return sqlCommand;
}

All parameters are of string type here.

A: Below changes at the time of passing parameters have improved the query's performance and it is executing again in seconds.
sqlCommand.Parameters.Add("@TrnDate", SqlDbType.VarChar).Value = TrnDate;
sqlCommand.Parameters.Add("@TxtID", SqlDbType.VarChar).Value = TxtID;
sqlCommand.Parameters.Add("@TxtKey", SqlDbType.VarChar).Value = TxtKey;

Thanks everyone for all the suggestions!

A: You dont appear to have any index to optimize the query.  create a multiple-field index on ( ElemName, TxtID, TxtKey, ActiveStatus, TrnDate )


text:
Q: Flood fill algorithm maze I ma trying to make my program read a maze like this:
    #.#######
    #.......#
    ####.####
    #....#..#
    #.####.##

and print out the reachable zones and non-reachable zones in the maze, which should look like this:
    #+#######
    #+++++++#
    ####+####
    #++++#--#
    #+####-##

Walls are represented with "#", and passable cells are represented with ".".
The "+" that replaces the cells means that those cells are reachable from the top entry point of the maze. The "-" symbol are the cells that can't be reached if you enter the top of the maze.
For example, in the above maze, all the cells are reachable except for the cells in the bottom right-hand corner. This is because those cells cannot be reached from the entry point at the top of the maze.
I am trying to use some recursion to flood fill the maze, and determine the reachable zones, but I am having trouble with that.
This is what I have so far:
    int
    flood_fill(m_t * maze, int row, int col) {

        int direction;

        direction = flood_fill(maze, row+1, col); /* down */
        if (!direction) {
            direction = flood_fill(maze, row, col+1); /* right */
        }

        if (!direction) {
            direction = flood_fill(maze, row-1, col); /* up */
        }

        if (!direction) {
            direction = flood_fill(maze, row, col-1); /* left */
        }

        if (direction) {
            maze->M[row][col].type = path;
        }

        return direction;
    }

I know that my flood_fill function is not doing the right thing, and I'm having difficulty getting it right. Can anyone help me please me get my flood filling part of the code right, so I can call the function elsewhere in the code and determine which cells can be reached.

A: try this
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_HEIGHT 100
#define MAX_WIDTH  100
#define wall '#'
#define path_cell '.'

typedef struct {
    char type;
    int reachable;
    int visited;
} mazecells_t;

typedef struct {
    int height;
    int width;
    mazecells_t M[MAX_HEIGHT][MAX_WIDTH];
} m_t;

void readmaze(m_t *maze);
void print(m_t *m);
void print_reachable(m_t *m);

int main(void) {
    m_t MAZE;

    readmaze(&MAZE);
    print(&MAZE);
    puts("");
    print_reachable(&MAZE);

    return 0;
}

void readmaze(m_t *maze) {
    int row=0, col=0;
    char ch;
    FILE *fp = stdin;//fopen("map.txt", "r");
    while(EOF != fscanf(fp, "%c", &ch)){
        if(ch == wall || ch == path_cell){
            maze->M[row][col].type = ch;
            maze->M[row][col].reachable = 0;
            maze->M[row][col].visited = 0;
            ++col;
        } else if(ch == '\n'){
            maze->width = col;
            col = 0;
            ++row;
        }
    }
    if(col != 0)
        ++row;
    //fclose(fp);
    maze->height = row;
}

void print(m_t *m){
    for(int r = 0; r < m->height; ++r){
        for(int c = 0; c < m->width; ++c){
            putchar(m->M[r][c].type);
        }
        putchar('\n');
    }
}

typedef enum dir {
    UP, RIGHT, DOWN, LEFT, FORWARD
} DIR;

typedef struct pos {
    int r, c;
    DIR dir;
} Pos;

typedef struct node {
    Pos pos;
    struct node *next;
} Node;

typedef struct queque {
    Node *head, *tail;
} Queque;

Queque *new_queque(void){
    Queque *q = malloc(sizeof(*q));
    q->head = q->tail = NULL;
    return q;
}

void enque(Queque *q, Pos pos){
    Node *node = malloc(sizeof(*node));
    node->pos = pos;
    node->next = NULL;
    if(q->head == NULL){
        q->head = q->tail = node;
    } else {
        q->tail = q->tail->next = node;
    }
}

Pos deque(Queque *q){
    Pos pos = q->head->pos;
    Node *temp = q->head;
    if((q->head = q->head->next)==NULL)
        q->tail = NULL;
    free(temp);
    return pos;
}

bool isEmpty_que(Queque *q){
    return q->head == NULL;
}

Pos dxdy(DIR curr, DIR next){
    Pos d = { 0, 0, 0};
    switch(curr){
    case UP:
        switch(next){
        case LEFT:
            d.c -= 1;
            break;
        case FORWARD:
            d.r -= 1;
            break;
        case RIGHT:
            d.c += 1;
            break;
        }
        break;
    case RIGHT:
        switch(next){
        case LEFT:
            d.r -= 1;
            break;
        case FORWARD:
            d.c += 1;
            break;
        case RIGHT:
            d.r += 1;
            break;
        }
        break;
    case DOWN:
        switch(next){
        case LEFT:
            d.c += 1;
            break;
        case FORWARD:
            d.r += 1;
            break;
        case RIGHT:
            d.c -= 1;
            break;
        }
        break;
    case LEFT:
        switch(next){
        case LEFT:
            d.r += 1;
            break;
        case FORWARD:
            d.c -= 1;
            break;
        case RIGHT:
            d.r -= 1;
            break;
        }
        break;
    }
    return d;
}

Pos next_pos(Pos pos, DIR dir){
    Pos dxy = dxdy(pos.dir, dir);
    switch(dir){
    case RIGHT:
        pos.dir = (pos.dir + 1) % 4;
        break;
    case LEFT:
        if((pos.dir = (pos.dir - 1)) < 0)
            pos.dir += 4;
        break;
    case FORWARD:
        break;
    }
    pos.r += dxy.r;
    pos.c += dxy.c;
    return pos;
}
static inline bool isValid(m_t *m, Pos pos){
    if(pos.r < 0 || pos.r >= m->height || pos.c < 0 || pos.c >= m->width || m->M[pos.r][pos.c].type == wall)
        return false;
    return true;
}
static inline bool isValidAndUnvisit(m_t *m, Pos pos){
    return isValid(m, pos) && !m->M[pos.r][pos.c].reachable;
}

void print_reachable(m_t *m){
    int i;
    for(i = 0; i < m->width; ++i)
        if(m->M[0][i].type == path_cell)
            break;
    Pos pos = { 0, i, DOWN};
    Queque *q = new_queque();
    enque(q, pos);
    while(!isEmpty_que(q)){
        pos = deque(q);
        if(!m->M[pos.r][pos.c].reachable){
            m->M[pos.r][pos.c].reachable = 1;

            Pos next = next_pos(pos, LEFT);
            if(isValidAndUnvisit(m, next))
                enque(q, next);
             next = next_pos(pos, FORWARD);
            if(isValidAndUnvisit(m, next))
                enque(q, next);
             next = next_pos(pos, RIGHT);
            if(isValidAndUnvisit(m, next))
                enque(q, next);
        }
    }
    free(q);
    for(int r = 0; r < m->height; ++r){
        for(int c = 0; c < m->width; ++c){
            if(m->M[r][c].reachable)
                putchar('+');
            else if(m->M[r][c].type == path_cell)
                putchar('-');
            else
                putchar(m->M[r][c].type);
        }
        putchar('\n');
    }
}

A: You need to check if the current position is a path, a visited path or a wall.
If it is a path, change it to reachable and visited and then call flood_fill in each direction.
If it is a wall or a visited path then return without further calls to flood_fill.
After flood_fill has returned, any position that is an unvisited path is  unreachable.
Edit:
The code for flood_fill could look something like this:
void
flood_fill(m_t * maze, int row, int col) {

    if (row < 0 || col < 0 || row >= MAX_HEIGHT || col >= MAX_WIDTH) {
        /* Out of bounds */
        return;
    }
    if (maze->M[row][col].type != path_cell) {
        /* Not a path cell */
        return;
    }
    if (maze->M[row][col].visited) {
        /* We have already processed this cell */
        return;
    }

    /* We have now established that the cell is a reachable path cell */
    maze->M[row][col].visited = 1;
    maze->M[row][col].reachable = 1;
    maze->M[row][col].type = '+';  /* Not sure if you want this line or if you exchange the symbol in the presentation */

    /* Check the surrounding cells */
    flood_fill(maze, row+1, col); /* down */
    flood_fill(maze, row, col+1); /* right */
    flood_fill(maze, row-1, col); /* up */
    flood_fill(maze, row, col-1); /* left */
}

A: First, you can find a very nice explanation for the maze recursion here.
In your case the function should look like this:
void
flood_fill(m_t * maze, int row, int col)
{
    // If row,col is outside maze
    if ( row < 0 || row >= maze->height || col < 0 || col >= maze->width) return;
    // If row,col is not open
    if (maze->M[row][col].type != '.') return;
    // Mark row,col as part of path.
    maze->M[row][col].type = '+';
    // Go Up
    flood_fill(maze, row, col - 1);
    // Go Right
    flood_fill(maze, row + 1, col);
    // Go Down
    flood_fill(maze, row, col + 1);
    // Go Left
    flood_fill(maze, row - 1, col);

    return;
}

Result after calling this function with your example matrix will be:
#+#######
#+++++++#
####+####
#++++#..#
#+####.##

After running this you can just go over the matrix again and mark every . cell with - and you're done.
Note: You don't need to change your matrix before calling this function. You only need to call this function with the index of the beginning of the maze when you find it. In your example it will be flood_fill(maze,0,1).