text:
Q: Set Author of a saved post as its parent post author I try to change author of saved harmonogram item with author of parent but those to functions seems not to work - empty i think. When i set the author id with constant value everything works.
 $parent_post_id = wp_get_post_parent_id($post_id);

   $post_author_id = get_post_field( 'post_author', $post_id );

Here is whole function
    function func_auto_update_post_author( $post_id ) {
    $post_type = get_post_type($post_id);

if ( "harmonogram" != $post_type ) return;

   //$parent_post_id = get_queried_object_id();
   $parent_post_id = wp_get_post_parent_id($post_id);

   $post_author_id = get_post_field( 'post_author',  $parent_post_id );
         $my_post = array(
            'ID'            => $post_id,
            'post_author'   => $post_author_id,
        );

        remove_action('save_post', 'func_auto_update_post_author');
        wp_update_post($my_post);
        add_action( 'save_post', 'func_auto_update_post_author');
}
add_action( 'save_post', 'func_auto_update_post_author');

A: Try below Code :
function func_auto_update_post_author( $post_id )
{
    $post_type = get_post_type($post_id);
    if ( "harmonogram" != $post_type ) return;
    $parent_post_id = wp_get_post_parent_id($post_id);
    if($parent_post_id)
    {
         $post_author_id = get_post_field( 'post_author', $parent_post_id );
         $my_post = array(
            'ID'            => $post_id,
            'post_author'   => $post_author_id
        );
        wp_update_post($my_post);
     }
}
add_action( 'save_post', 'func_auto_update_post_author');

you can track if any error occurred during post update by putting below code in above action hook:
$post_id = wp_update_post( $my_post, true );
if (is_wp_error($post_id)) {
    $errors = $post_id->get_error_messages();
    foreach ($errors as $error) {
        echo $error;
    }
}

Hope this will help!


text:
Q: How can I multiply a constant value with each line of a text file in Python? I have written codes to read the lines of a txt file. I just want to multiply each line with a constant value "60". I'm not sure how to write the codes in a correct way?
data = []
with open('data.txt', 'r') as filehandle:
    for line in filehandle:
        currentPlace = line[:-1]
        data.append(currentPlace)
for i in data:
    print(i * 60)

A: data = []
with open('data.txt', 'r') as filehandle:
    for line in filehandle:
        currentPlace = line[:-1]
        data.append(currentPlace)
for i in data:
    print(float(i) * 60)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to setup user pool authentication for API Gateway I'm trying to setup security on an API using Cognito user pools. I'm getting back 401 Unauthorized.
The API and User Pools are existing, and I've been using the user pool to log into an application. I'm now trying to secure the API calls.
I created an authorizer on the API,

Then I added the authorizer to one GET method in the API

Then finally I tried to test the API in Postman. I'm using the AWS Signature authorization.

Calling the method returns 401. The method functioned before with no security, and turning off the authorizer makes it work again (without security).
Any ideas what step I'm missing?

A: The AWS Signature authorization is different than a Custom Authorizer.
The AWS Signature authorization (Postman) requests an AWS AccessKey and SecretKey to authenticate requests. This corresponds to IAM Authentication in API Gateway. The AccessKey and SecretKey are received through IAM.
A Custom Authorizer takes a JWT called #id_token that is issued by your specified Cognito User Pool. To test the validity of the token, go to your custom authorizer and click test, and then copy and paste the token into the text area.
The way to perform the Custom Authorizer authentication is this:

*

*obtain an #id_token from the your user pool by following AWS Configuration

*Configure API gateway with a Cognito custom Authorizer with your user pool as the source (Seems that you have done correctly)

*Use OAuth 2.0 as Authorization in postman, with your #id_token as the Access Token, Or add the header: Authorization with the value Bearer and the #id_token
Drop a comment if you want me to add the AWS Signature Auth Flow.

A: For authorization using Postman when using Cognito user pools, chose No Auth. Then add a header Authorization (the value in token source field of your authorizer) and copy the id_token into that header value. I did not have to add anything else besides that to make it work (i.e. no bearer).


text:
Q: Using global variables in pytest I am trying to write a test as follows and an ending up getting the following error:
def test_retry():
  hits = 0

  def f():
    global hits
    hits += 1
    1 / 0

  with pytest.raises(ZeroDivisionError):
    f()

and get the following error:
>       hits += 1
E       NameError: name 'hits' is not defined

but am curious why this code doesn't work. Does pytest somehow alter the global variables?
I know this can be solved using a list like hits = [0], but i'm trying to understand why the code doesn't work.
I've also tried using pytest_configure, and that works too.

A: Use nonlocal instead. hits is not a global variable.
nonlocal hits


text:
Q: mmcli can't find modem on Dell Latitude 5401 mmcli can't find any modem on my laptop running Ubuntu 20.04.02.
lb01548:~$ sudo mmcli --scan-modems
successfully requested to scan devices
apastuchov@lb01548:~$ sudo mmcli --list-modems
No modems were found

If I understand the Dell Latitude 5401 documentation correctly, the laptop is shipped with Intel XMM 7360 Global LTE modem.
But neither lspci
$ lspci
00:00.0 Host bridge: Intel Corporation 8th Gen Core Processor Host Bridge/DRAM Registers (rev 0d)
00:02.0 VGA compatible controller: Intel Corporation UHD Graphics 630 (Mobile) (rev 02)
00:04.0 Signal processing controller: Intel Corporation Xeon E3-1200 v5/E3-1500 v5/6th Gen Core Processor Thermal Subsystem (rev 0d)
00:08.0 System peripheral: Intel Corporation Xeon E3-1200 v5/v6 / E3-1500 v5 / 6th/7th/8th Gen Core Processor Gaussian Mixture Model
00:12.0 Signal processing controller: Intel Corporation Cannon Lake PCH Thermal Controller (rev 10)
00:14.0 USB controller: Intel Corporation Cannon Lake PCH USB 3.1 xHCI Host Controller (rev 10)
00:14.2 RAM memory: Intel Corporation Cannon Lake PCH Shared SRAM (rev 10)
00:14.3 Network controller: Intel Corporation Wireless-AC 9560 [Jefferson Peak] (rev 10)
00:15.0 Serial bus controller [0c80]: Intel Corporation Cannon Lake PCH Serial IO I2C Controller #0 (rev 10)
00:15.1 Serial bus controller [0c80]: Intel Corporation Cannon Lake PCH Serial IO I2C Controller #1 (rev 10)
00:16.0 Communication controller: Intel Corporation Cannon Lake PCH HECI Controller (rev 10)
00:16.3 Serial controller: Intel Corporation Cannon Lake PCH Active Management Technology - SOL (rev 10)
00:17.0 SATA controller: Intel Corporation Cannon Lake Mobile PCH SATA AHCI Controller (rev 10)
00:1c.0 PCI bridge: Intel Corporation Cannon Lake PCH PCI Express Root Port #1 (rev f0)
00:1c.5 PCI bridge: Intel Corporation Cannon Lake PCH PCI Express Root Port #6 (rev f0)
00:1d.0 PCI bridge: Intel Corporation Cannon Lake PCH PCI Express Root Port #9 (rev f0)
00:1f.0 ISA bridge: Intel Corporation Device a30e (rev 10)
00:1f.3 Audio device: Intel Corporation Cannon Lake PCH cAVS (rev 10)
00:1f.4 SMBus: Intel Corporation Cannon Lake PCH SMBus Controller (rev 10)
00:1f.5 Serial bus controller [0c80]: Intel Corporation Cannon Lake PCH SPI Controller (rev 10)
00:1f.6 Ethernet controller: Intel Corporation Ethernet Connection (7) I219-LM (rev 10)
01:00.0 PCI bridge: Intel Corporation JHL6340 Thunderbolt 3 Bridge (C step) [Alpine Ridge 2C 2016] (rev 02)
02:00.0 PCI bridge: Intel Corporation JHL6340 Thunderbolt 3 Bridge (C step) [Alpine Ridge 2C 2016] (rev 02)
02:01.0 PCI bridge: Intel Corporation JHL6340 Thunderbolt 3 Bridge (C step) [Alpine Ridge 2C 2016] (rev 02)
02:02.0 PCI bridge: Intel Corporation JHL6340 Thunderbolt 3 Bridge (C step) [Alpine Ridge 2C 2016] (rev 02)
03:00.0 System peripheral: Intel Corporation JHL6340 Thunderbolt 3 NHI (C step) [Alpine Ridge 2C 2016] (rev 02)
39:00.0 USB controller: Intel Corporation JHL6340 Thunderbolt 3 USB 3.1 Controller (C step) [Alpine Ridge 2C 2016] (rev 02)
3a:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS525A PCI Express Card Reader (rev 01)
3b:00.0 Non-Volatile memory controller: Micron Technology Inc Device 5410 (rev 01)

nor lsusb list it
$ lsusb
Bus 004 Device 013: ID 0bda:8153 Realtek Semiconductor Corp. RTL8153 Gigabit Ethernet Adapter
Bus 004 Device 012: ID 0bda:0413 Realtek Semiconductor Corp.
Bus 004 Device 011: ID 0bda:0487 Realtek Semiconductor Corp. Dell dock
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 014: ID 413c:b06e Dell Computer Corp. Dell dock
Bus 001 Device 018: ID 413c:b06f Dell Computer Corp. Dell dock
Bus 001 Device 017: ID 0bda:402e Realtek Semiconductor Corp.
Bus 001 Device 016: ID 413c:2113 Dell Computer Corp.
Bus 001 Device 015: ID 413c:301a Dell Computer Corp.
Bus 001 Device 013: ID 0bda:5413 Realtek Semiconductor Corp.
Bus 001 Device 012: ID 0bda:5487 Realtek Semiconductor Corp. Dell dock
Bus 001 Device 008: ID 8087:0aaa Intel Corp.
Bus 001 Device 005: ID 0bda:565c Realtek Semiconductor Corp. Integrated_Webcam_HD
Bus 001 Device 003: ID 0a5c:5843 Broadcom Corp. 58200
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Does that mean there is no modem on my laptop?

A: You can try to determine the answer by yourself by:
a) looking full model number on laptop to understand its hardware configuration;
b) locate SIM slot on laptop (see page 9 in guide);
c) non-destructive laptop disassembly to locate possible LTE modem (see review, WWAN on image) option.


text:
Q: Analytic continuation of a holomorphic function in some domain Quite generally I thought that every holomorphic function defined in some domain can be analytically continued into the entire complex plane. However the dedekind eta function seems to not have such an analytic continuation to the lower half as is stated here Dedekind Eta Function.
So what is the problem here precisely?
As an example the zeta function defined via the dirichlet series is only convergent for s>1. Probably it also converges for s=1 if Im(s) is not equal zero. Still it can be continued.
Now the dedekind eta (or similar functions as the jacobi theta) are only defined for Im(t)>0. Again I would assume it to converge on the real axis if t is not an integer. So what prevents it of being continued?


text:
Q: Finding a prime number at least a 100 digits long that contains 273042282802155991 I am new to Java and one of my class assignments is to find a prime number at least 100 digits long that contains the numbers 273042282802155991.
I have this so far but when I compile it and run it it seems to be in a continuous loop.
I'm not sure if I've done something wrong.
public static void main(String[] args) {
    BigInteger y = BigInteger.valueOf(304877713615599127L);
    System.out.println(RandomPrime(y));
}

public static BigInteger RandomPrime(BigInteger x)
{
    BigInteger i;

    for (i = BigInteger.valueOf(2); i.compareTo(x)<0; i.add(i)) {
        if ((x.remainder(i).equals(BigInteger.ZERO))) {
            x.divide(i).equals(x);
            i.subtract(i);
        }
    }
    return i;
}

A: One tip is that these statements do nothing:
x.divide(i).equals(x);
i.subtract(i);

Same with part of your for loop:
i.add(i)

They don't modify the instances themselves, but return new values - values that you're failing to check and do anything with.  BigIntegers are "immutable".  They can't be changed - but they can be operated upon and return new values.
If you actually wanted to do something like this, you would have to do:
i = i.add(i);

Also, why would you subtract i from i?  Wouldn't you always expect this to be 0?

A: Since this is homework ...

*

*There is a method on BigInteger that tests for primality.  This is much much faster than attempting to factorize a number.  (If you take an approach that involves attempting to factorize 100 digit numbers you will fail.  Factorization is believed to be an NP-complete problem.  Certainly, there is no known polynomial time solution.)

*The question is asking for a prime number that contains a given sequence of digits when it is represented as a sequence of decimal digits.

*The approach of generating "random" primes and then testing if they contain those digits is infeasible.  (Some simple high-school maths tells you that the probability that a randomly generated 100 digit number contains a given 18 digit sequence is ...  82 / 1018.  And you haven't tested for primality yet ...

*But there's another way to do it ... think about it!
Only start writing code once you've figured out in your head how your algorithm will work, and done the mental estimates to confirm that it will give an answer in a reasonable length of time.

When I say infeasible, I mean infeasible for you.  Given a large enough number of computers, enough time and some high-powered mathematics, it may be possible to do some of these things.  Thus, technically they may be computationally feasible. But they are not feasible as a homework exercise.  I'm sure that the point of this exercise is to get you to think about how to do this the smart way ...

A: You need to implement/use miller-rabin algorithm
Handbook of Applied Cryptography
chapter 4.24
http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf


text:
Q: Does my mobile app need a database or should I save everything to files instead? I have created a video editor using React Native. I need to choose a way to save all of the user's projects locally. Each project has a video file, thumbnails (images) and its current Redux state.
My first idea is to save everything in files using RNFS. Each Project's folder would have a video file, Thumbnails folder and a state.txt file containing my application's current state (current text size selected, background color, etc...).
Do I need a database like SQLITE or should I save everything in files? I know I'll have to use RNFS for the binary data like videos and images. But what about the state.txt file? is that a good idea? The idea of each user having their own local database just for that sounds strange to me.

A: You have your Redux state that just represents local state. Have a look at https://github.com/rt2zz/redux-persist
This allows you to serialize the Redux State and save it using whatever storage you provide, but you can use asyncStorage in the react native apps.

A: You are right about using RNFS for videos etc. For the metadata in state.txt, in my opinion, it would be better to go with async-storage or other offline storage options (like Realm )
It will be much more performant to query it instead of reading from a file.


text:
Q: Can I have a method that returns an array value? I have a few questions regarding arrays in C#.

*

*In a Method we can have one return value.  Can we return an array?

*If returning an array is not possible, how we can use the array collected in that method and use in a calling method?

Below is my code.
public ArtWorkData[,] getExcelFile(int sheetNumber)
    {
        string[,] excRecord = new string[rowCount, colCount];
        excRecord[0, 0] = { {"TOPRIGHT", "TOPLEFT"},
                            {"MIDRIGHT", "MIDLEFT},
                            {"BOTRIGHT", "BOTLEFT"} }

        return excRecord;
     }

I want to know the logic of it and how we can pass the array out of the method.  Thank you guys.

A: An array is a reference type, so you can return a reference to it just like any reference type. Arrays also implement the IEnumerable generic interface, so you can also cast it to that if it makes you feel better.
For example:
public int[] GetNumbers()
{
    int[] numbers = new int[5];
    numbers[0]=34;
    return numbers;
}

public void DoStuff()
{
    IEnumerable<int> data = GetNumbers();
    ...

}

Returning a reference to a reference type does not copy the object - it copies a reference to it. The function that you return the array reference to can change the contents of the original array!


text:
Q: DNS query format little-big endian problem in header structure I have a question about DNS query Format ....
I know this structure as the structure of DNS query header ...
typedef struct _DNS_HEADER {
    unsigned short id;       // identification number
    unsigned char qr :1;     // query/response flag
    unsigned char opcode :4; // purpose of message
    unsigned char aa :1;     // authoritative answer
    unsigned char tc :1;     // truncated message
    unsigned char rd :1;     // recursion desired
    unsigned char ra :1;     // recursion available
    unsigned char z :1;      // its z! reserved
    unsigned char ad :1;     // authenticated data
    unsigned char cd :1;     // checking disabled
    unsigned char rcode :4;  // response code
    unsigned short q_count;  // number of question entries
    unsigned short ans_count; // number of answer entries
    unsigned short auth_count; // number of authority entries
    unsigned short add_count; // number of resource entries
} DNS_HEADER;

+ question query and ...
but there is a problem here:
I created a socket socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP) and i created a query request:
id = htons(10000);
qr = 0;
opcode = 0
aa = 0
tc = 0
rd = 1
ra = 0
z = 0
ad = 0
cd = 0
q_count = 1
ans_count = 0
auth_count = 0
add_count = 0

and my question ->
3,'w','w','w',4,'s','i','t','e',3,'c','o','m',0

TYPE = htons(1)
CLASS = htons(1)

I sent this request to my special DNS server (bind) and I think there was a problem. Sometimes DNS server didn't responded me and even on response, it wasn't a true response (everything was 0 and nothing received except same header (12-BYTE))
I searched and I found out that there is a problem with my DNS header and it Must be like this ->
typedef struct _DNS_HEADER {
    unsigned short id;       // identification number

    unsigned char rd :1;     // recursion desired
    unsigned char tc :1;     // truncated message
    unsigned char aa :1;     // authoritative answer
    unsigned char opcode :4; // purpose of message
    unsigned char qr :1;     // query/response flag

    unsigned char rcode :4;  // response code
    unsigned char cd :1;     // checking disabled
    unsigned char ad :1;     // authenticated data
    unsigned char z :1;      // its z! reserved
    unsigned char ra :1;     // recursion available

    unsigned short q_count;  // number of question entries
    unsigned short ans_count; // number of answer entries
    unsigned short auth_count; // number of authority entries
    unsigned short add_count; // number of resource entries
} DNS_HEADER;

something about little-big endian. I changed my structure to this structure and I sent request and DONE - everything worked and there wasn't any problem, but this is my problem: I don't get it what this is this. Yes, I read about little-big endian a little but still i don't get it:

*

*Why haven't other websites that teaches about DNS format mentioned this? They teach with the first structure.

*What is this? Why we must change the higher 8 bits of the second 16 bits to be the lower 8 bits of the second 16 bits?

A:
Why haven't other websites that teaches about DNS format mentioned this? They teach with the first structure.

I can't possibly answer that. Most networking litterature I've come across mentions network byte order and the motivation for it.

Why we must change the higher 8 bits of the second 16 bits to be the lower 8 bits of the second 16 bits?

The motivation for it is found in "[IEN-137] Cohen, D., "ON HOLY WARS AND A PLEA FOR PEACE", IEN 137, USC/ISI, April 1980." that is referred to in a Internet Engineering Task Force draft: Network Byte Order

Background and Motivation

The document "ON HOLY WARS AND A PLEA FOR PEACE" [IEN-137] written
in 1980 argues that the industry should settle on a single byte
order.  Since then, the IETF has largely settled on a single byte
order known as "Network Byte Order" and this memo is intended to
record that rough concensus.  Unfortunately, the "holy war"
continues among CPU manufacturers.

The last sentence is what this comes down to.
Some CPU models use Big-Endian and others use Little-Endian. There are even those using a mix.
Two bytes (in binary form) representing a std::uint16_t:
Big-Endian: 10000000 00000000 means 32768 (decimal).
Little-Endian: 10000000 00000000 means 128 (decimal).
If there was no agreement on how to interpret these two bytes, communication would be very hard.


text:
Q: How to test StateSpec.function - how to create a State object I have a stateful function(in scala) that I am using to check the data of incoming objects.
The function is
def updateGeneratedTs(thingId: String,
generatedTsRaw: Option[String],state: State[String]): Option[String]

This is then called using
StateSpec.function(updateGeneratedTs _)

I want to test this but I don't know how to create a State object.  I've tried using StateImpl but this doesn't work.


text:
Q: How to Create Page for Search? I Put the Database Search for my Plugin.
But When Searching gives 404 Error !
What do I do to fix 404 Error?
My Code is:

<?php
function qrn_search_code(){

 global $wpdb,$table_prefix;

 if($_POST['submit']) {
  if($_POST['search']) {

                    $search = $wpdb->get_results("SELECT ID, code FROM ".$table_prefix."qrn_dessini WHERE code LIKE '%".$_POST['search']."%' ORDER BY ID DESC;");
   print_r($search);

  }
 }

 <form  method="POST" id="searchform">
    <input  type="text" name="name" class="qr_search" placeholder="جستجوی کد محصول ...">
    <input  type="submit" name="submit" value="Search" class="qr_submit">
    </form>
}
add_shortcode('search_code','qrn_search_code');
?>

Thanks

A: I notice you have a beginning php tag at the end of your function, and also no ending:
<?php
}
add_shortcode('mysearch','search_code');

So I would try to change this to start:
}
<?php
add_shortcode('mysearch','search_code');
?>


text:
Q: Is there a way to change color of a highchart graph by clicking on the line Hi I am plotting my graph using highchart and I want to know if there is any way you could change the color of the line plotted by clicking on the line and change it with a color picker or something. I don't want to change it from the options with series.color. I want to let the user change it according to his likeness. Thank you.
Update
A chart like this : Line Graph Example

A: In a click event function you can update the series with a color that is taken from some input, for example:
plotOptions: {
  spline: {
    events: {
      click: function() {
        this.update({
          color: $('#colorInput').val()
        });
      }
    }
  }
}

Live demo: http://jsfiddle.net/BlackLabel/qgmfzkju/1/
API Reference:
https://api.highcharts.com/highcharts/series.spline.events.click
https://api.highcharts.com/class-reference/Highcharts.Series#update


text:
Q: Логические операторы c++ Начал учить с++, на теме логических операторов после пары минут экспериментов наткнулся на то, что есть некоторые нелогичные моменты у логических операторов. А именно - как-будто в с++ есть три возможных boolean значения.
Интересные моменты моих экспериментов:
true == 5 дает false (хотя всё true, что не 0)
false == 5 дает false (тут было бы все нормально, если бы не предыдущее выражение)
true && 5 дает true (тут мой мозг взорвался, потому что оператор && возвращает true, если оба операнда - true,
а два операнда не могут быть true, если один операнд != другой операнд (5 != true даст true), а всего существует только 2 варианта значения (true, false).

Как можно формализовать такие знания в какую-то систему, которую проще запомнить (ведь она должна быть, иначе смысла в логических выражений не будет, если они будут нелогичны)?

A: Все просто. Как thumb rule (ну, простое правило "на пальцах") - приведите разнородные типы в арифметических операциях к большему типу. Т.е. в
true == 5

не 5 приводится к bool, а true превращается в int, равный 1. Сравнение дает результат bool, но его операнды - арифметические типы.
Там, где оператор для логических операндов (&&, ||) - приводим операнды к типу bool.
Вот и все.

A: У вас интерференция между топиками "Типы данных и из преобразование" и "Логические операторы".
В первом случае, ваше true приводится к типу int и происходит сравнение 1==5 с понятным итогом false.
Во втором случае, 0==5 с аналогичным итогом
В последнем случае, приведения типов первого операнда не будет, зато приведется тип второго операнда, 5 превратится в true
Для того, чтобы не путаться, не пытайтесь сравнивать переменные разных типов. Всегда делайте явное приведение при помощи static_cast<>

A: Это следствие правил конвертации в C/C++
Подробнее по пунктам:
true == 5

Тут true сконвертился в int, и получилось сравнение 1 == 5 , что равно false
false == 5

Тут false сконвертился в int, и получилось сравнение 0 == 5 , что равно false
true && 5

Тут 5 сконвертился в true, и получилось true && true , что равно true


text:
Q: which database should I use? I am planning to build a web application and android app, which will manage huge numbers of notification (push notification), and can work in slow internet connection too. I need to send and get instant notifications. Number of users can be thousands or millions, application will have multiple servers (web farm), multiple database. Now I need to decide that which database will be best for this kind of application and which language should I use for programming. Please help me out. Any suggestions will be appreciated

A: I Blindly Suggest you to Use Parse Cloud Database,as it provides SDK for All mobile Environments like Android and IOS for easy implementation and also it recently Launched a Javascript SDK to use.Its free for Trial.MultiPlatform Support and Secure
Check it out Here: https://www.parse.com/

A: Well, first you need to decide what your immediate needs are. Are you going to use this on a platforms that could potentially have hundreds of people accessing information at the same time? Then you need to estimate your future needs.
This will help you to decide your database system.
As per my experience i am suggesting you to use MYSQL database.

A: Are you sure you going to get to thousands and millions users ? Everyone starts from scratch (read: zero users, except some friends). By this I mean, that you have to concentrate on what's the real issue within your development (growing app user base is different story):

*

*Creation of Android app and it's lifecycle (updates, support of previous versions & etc).

*Back-end. Will I also work on Back-end. Working on 2 'projects' (Android app and it's back-end) isn't easy. Not everyone is experienced enough to work on multiple assignments at the same time.

*Valuate an option of using SaaS/Paas backend. Most of the have trial or free version for developer.

Third option is great. Get cheap/free web host. Store there configuration, that your Android app will download when it starts. In configuration you should declare what's the back-end and how to communicate with it. You can use any of known services like https://www.firebase.com or https://parse.com/plans or even use Google App engine free tier / AWS free tier.
About developing app for Android - if your app doesn't need any complex calculation or libraries - just write it with JavaScript. It's fast enough. Though, Java apps are always faster and easier to debug.
Good luck !


text:
Q: Json com Array dentro de array PHP me encontro com um problema.
tenho uma API em URL passando
{
"id": "1",
"codeReferenceAdditional": "33B",
"isActive": true,
"personType": 1,
"profileType": 3,
"accessProfile": "Administradores",
"businessName": "Movidesk",
"corporateName": "Movimentti sistemas",
"cpfCnpj": "012345678900",
"userName": "admin",
"password": null,
"role": null,
"bossId": null,
"classification": null,
"createdDate": "2014-12-17T18:00:43.3339728",
"observations": "Cadastro realizado via api de pessoas.",
"addresses": [
  {
    "addressType": "Comercial",
    "country": "Brasil",
    "postalCode": "89035200",
    "state": "Santa Catarina",
    "district": "Vila Nova",
    "street": "Rua Joinville",
    "number": "209",
    "complement": "Sala 201",
    "reference": "Próximo a FURB",
    "isDefault": true
  }
],

Estou usando a seguinte estrutura em php para ler as informações
 $json = file_get_contents("https://api");

   $cliente = json_decode($json);

  echo "id: $cliente->id
";
  echo "nome: $cliente->corporateName
";
  echo "cpf/cnpj: $cliente->cpfCnpj
 ";
  echo "Endereço: $cliente->addresses[0]->city";

porem dá o seguinte erro no navegador
Notice: Array to string conversion in C:\xampp\htdocs\Maps\index.php on line 30
Endereço: Array[0]->city

não estou conseguindo converter este segundo array.

A: O problema está em utilizar o array dento da string.
O PHP está tentando converter o $cliente->addresses para string e não a expressão completa $cliente->addresses[0]->city
Altere para algum dos seguintes modos e deve funcionar:
echo "Endereço: " . $cliente->addresses[0]->city;

Ou então:
echo "Endereço: {$cliente->addresses[0]->city} ";


text:
Q: how can I link edge collection to the graph in Arangodb using a Java driver The only way I find it is working is when I provide the definition at the graph creation time using:
  GraphEntity graph = driver.createGraph(graphName, edgeDefinitions, orphans, bWait);

If I try something like:
  GraphEntity graph = driver.createGraph(graphName, bWait);
  graph.setEdgeDefinitions(edgeDefinitions);

it ignores the modified value and when actually trying to create an edge returns:
  com.arangodb.ArangoException: [1203]collection not found

When creating a new graph it does not matter much, but when I try at some point to add a new edge collection to the existing graph, it becomes a problem.
Also - in Java (driver) I find no way to add edges directly to the edge collection, only via graph (unless I use my own REST calls) Is it by design?

A: 1st:
This is a bug.
graph.setEdgeDefinitions(edgeDefinitions) does not persist. So creating an edge leads to an exception. Will be fixed asap.
2nd:
Unfortunately the createEdge() method was moved to the graph module, without regarding the need, to add edges directly.
Will be fixed too...
It would be great if you could add 2 Issues to https://github.com/arangodb/arangodb-java-driver/issues they will be fixed asap.


text:
Q: Relating Models across Databases in Cakephp I'm working with Databases that I cannot alter. I three tables, 2 of which are in a different database than the main table.
Voucher - Main Table
CustKey FiscPer FiscYear etc.
1884     6      2011

FiscPer is the Month Number.

LU_MONTH - Table 1 in different DB

MONTH_ID MONTH_OF_YEAR YEAR_ID
200806   2011            6

FACT_DATA - Table 2 in different DB

SCHOOLKEY MONTH_ID
1884       200806

I am trying to make them relate in Cakephp. The tables are not set up in the way CakePHP wants them. I am trying to make the Voucher Model grab the information in FACT_DATA using LU_MONTH as the middle join table. Any help please?

A: If you look through the CakePHP book - specifically the part on Model Attributes, you'll likely find what you want - useDbConfig, useTable ...etc


text:
Q: Adding Headers to AWS API Gateway Response using Chalice My use-case requires my app to return CORS headers when error response is 401.
This functionality was added by AWS last year (See this). It can be done using Cloudformation and Swagger template but I'm not sure if it's yet possible with Chalice.

A: I solved my problem by using a python script that adds the CORS headers for 401 response and redeploys the API. This redeploying of API takes a second or two since it doesn't have to deploy all Lambdas like Chalice.
deploy.sh
#!/usr/bin/env bash

cd services
A="$(chalice deploy --stage $1)"
cd ..
python update_api_response_headers.py "$A" "$1"

update_api_response_headers.py
import boto3
import sys
import re

if len(sys.argv) != 3:
    print("usage: python script.py <CHALICE_DEPLOYMENT_RESULT> <STAGE>")
    exit()

search = re.search('URL: https:\\/\\/([a-zA-Z0-9]+).+', sys.argv[1])
api_id = search.group(1)
print(api_id)
if not api_id:
    print(sys.argv[1])
    exit()
client = boto3.client('apigateway')

response = client.put_gateway_response(
    restApiId=api_id,
    responseType='UNAUTHORIZED',
    statusCode='401',
    responseParameters={
        "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
        "gatewayresponse.header.Access-Control-Allow-Headers": "'*'"
    }
)
response = client.create_deployment(
    restApiId=api_id,
    stageName=sys.argv[2])

print(sys.argv[1])

Services folder contains my chalice app. deploy.sh and update_api_response_headers.py are placed one level above the chalice app. To deploy the app I simply have to use:
./deploy.sh stage_name


text:
Q: How can I tell if GNU GSL is installed? How can I find out if GNU Scientific Library is installed?
OSX 10.11

A: Apple doesn't install it (afaik), so you'll need Fink or MacPorts or homebrew or a manual install. Assuming a properly configured PKG_CONFIG_PATH for Fink or MacPorts or homebrew or the manual install, in this case MacPorts, pkg-config might indicate the presence of gsl (and, bonus, the various compiler flags to use).
% echo $PKG_CONFIG_PATH
/opt/local/lib/pkgconfig
% pkg-config --cflags --libs gsl
-I/opt/local/include -L/opt/local/lib -lgsl -lgslcblas -lm
%


text:
Q: How does one prove that $\lim_{x\to\infty} x^{d/2}\log\frac{1-e^{-\beta(x-\mu)(n+1)}}{1-e^{-\beta(x-\mu)}} = 0$? How would one go about proving
\begin{equation}
\lim_{x\to\infty} x^{d/2}\log\frac{1-e^{-\beta(x-\mu)(n+1)}}{1-e^{-\beta(x-\mu)}} = 0
\end{equation}
where $n, d\in\mathbb{N}$ and $x\in\mathbb{R^+}, \mu\in\mathbb{R}$? If this does not hold, will putting any bounds on $d, n,$ and/or $\mu$ make the limit hold?
While I tried using L'Hospital, I couldn't get anything using that.
PS: This limit came from a Stat Mech calculation on Ideal Quantum Gases which the textbook skipped, if anyone was interested where this came from.

A: Note that we have for $n\ge 1$
$$\begin{align}
\log\left(\frac{1-e^{-\beta(n+1)(x-\mu)}}{1-e^{-\beta(x-\mu)}}\right)&=\log\left(1+\sum_{k=1}^n e^{-\beta k (x-\mu)}\right)
\end{align}$$
Using $\frac x{1+x}\le \log(1+x)\le x$, we find
$$\frac{\sum_{k=1}^n x^{d/2}e^{-\beta k(x-\mu)}}{1+\sum_{k=1}^n e^{-\beta k(x-\mu)}}\le x^{d/2}\log\left(\frac{1-e^{-\beta(n+1)(x-\mu)}}{1-e^{-\beta(x-\mu)}}\right)\le \sum_{k=1}^n x^{d/2}e^{-\beta k(x-\mu)}$$
Now use the squeeze theorem.


text:
Q: What to fill into main class in Intellij to pack all the examples into one jar? I'm trying to build a jar with Intellij, it requires a main class. The example I am using is storm-starter. I want to pack all the examples to this jar.
What should I fill to main class so that I can pack all the examples into one jar?


text:
Q: selecting 1 image from each product if there were n different products, if not, select more than 1 image from each products til n is reached In the project's design schema, one product may have many images.
Now I want to select n images from products with the situation:

*

*If n products were defined, select 1 image from each.

*Else select more images from each product limit n
Do we also need a PHP side action to reach the goal?
The schema is as expected:
product (id, title, ...)
image (id, product_id, filename, ...)

I cannot even think of a query like this, that's why I haven't unfortunately tried anything.
The query should look like this:
SELECT * FROM image ..with..those..hard..conditions.. LIMIT n

A: If I understand it well -- you need n images. If possible from different products. Otherwise, several images from the same product is acceptable as fallback.
From now, the only solution I could think of, is to build a temporary table, with numbered rows such as there will be one "image" of each product at the "top" -- and filed with the rest of the images.
Once that table is build, your query is just a SELECT ... LIMIT n.
This will perform horribly -- and if you choose that solution of something inspired -- you should consolidate the image table off-line or on schedule basis.
see http://sqlfiddle.com/#!2/81274/2
--
-- test values
--
create table P (id int, title char(20));
insert into P values
  (1, "product 1"),
  (2, "product 2"),
  (3, "product 3");

create table I (pid int, filename char(40));
insert into I values
   (1, "image p1-1"),
   (1, "image p1-2"),
   (3, "image p3-1"),
   (3, "image p3-2"),
   (3, "image p3-3");

--
-- "ordered" image table
--
create table T(n int primary key auto_increment not null,
                         filename char(20));

--
-- consolidate images (once in a while)
--
delete from T;
insert into T(filename)
    select filename from I group by pid;
insert into T(filename)
    select filename from I order by rand();

--
-- do the actual query
--
select * from T limit n;

EDIT Here is a completely different idea. Not using a consolidation table/view -- so this might be seen as better:
http://sqlfiddle.com/#!2/57ea9/4
select distinct(filename) from
    (select 1 as p, filename from I group by pid
     union (select 2 as p, filename from I order by rand() limit 3)) as T
order by p limit 3

The key point here is I don't have to really "number" the rows. Only to keep track of which rows are coming from the first SELECT. That is the purpose of p. I set both LIMIT clause to the same value for simplicity. I don't think you have to "optimize" that part since the benefit would be very small -- and ORDER BY RAND() is so terrible that you don't have to think about "performances" here ;)
Please note I don't have fully tested this solution. Let me know if there is some corner cases (well.. any case) that don't work.

A: http://sqlfiddle.com/#!2/32198/2/0
create view T as select (select filename from I where pid = id order by filename limit 1) as singleImage from P having singleImage is not null;

select * from (
  select singleImage from T
  union all (select filename from I where filename not in
    (select singleImage from T) order by rand() limit 5)
  ) as MoreThanN limit 5;

If your N is rather small, you may benefit from my technique for selecting random rows from large tables: although it is intended for selecting a single row, it could be adapted to select a few random rows relatively easily.
Here's the SQL with Sylvain Leroux's examples:
-- Test values
create table P (id int, title char(20));
insert into P values
  (1, "product 1"),
  (2, "product 2"),
  (3, "product 3");

create table I (pid int, filename char(40));
insert into I values
   (1, "image p1-1"),
   (1, "image p1-2"),
   (3, "image p3-1"),
   (3, "image p3-2"),
   (3, "image p3-3"),
   (3, "image p3-4"),
   (3, "image p3-5");

-- View to avoid repeating the query
create view T as select (select filename from I where pid = id order by filename limit 1) as singleImage from P having singleImage is not null;

-- Query
select * from (
  select singleImage from T
  union all (select filename from I where filename not in
    (select singleImage from T) order by rand() limit 5)
  ) as MoreThanN limit 5;


text:
Q: how can i set function.prototype.property using function name I have a printName function as below:
function printName(name) {
  console.log('Name is': , name);
}

Now i want to execute printName.callAfter(3000, 'foo'), which should log

'Name is: foo' after 3 seconds.

I tried writing :
myName.prototype.callAfter = function(time, name) {
  setTimeout(function() {
    printName(name)
  }, time);
}

But its only giving me myName.prototype.callAfter as a defined function but myName.callAfter is undefined.
Please help. Thanks in advance

A: The prototype you should be applying to is (literally) Function not the name of the function. When you do this you can then execute callAfter on any defined function.
The below appears to do what you wanted.

function printName(name) {
  console.log('Name is: ' , name);
}

Object.defineProperty(Function.prototype, "callAfter", {
  value: function(delay, args) {
    var func = this;
    setTimeout(function(){
      func.apply(func,args);
    }, delay);
  }
});
printName("Instant");
printName.callAfter(3000,["After 3 seconds"]);

*(I'm using Object.defineProperty there so that callAfter isn't enumerable, which is frequently important when extending built-in prototypes.)*
You should be aware that extending built-in objects has some gotchas to be aware of.

*

*Why is extending native objects a bad practice?

*http://perfectionkills.com/extending-native-builtins/

A: I think I have what you want working in this jsfiddle: https://jsfiddle.net/kd13ugwt/
function printName(name) {
  console.log('Name is: ' , name);
}

printName.callAfter = function(time, name) {
  setTimeout(function() {
    printName(name)
  }, time);
}

printName.callAfter(3000, 'foo');


text:
Q: How can I figure out and mark the highest value in my diagram? Update my modified code -> the wrong point is marked! see the colorbar! :)
Input_Matrix = textread('Rainflow_Input1.txt')
[zeilen,spalten]=size(Input_Matrix)
x = Input_Matrix(:,1)
y = Input_Matrix(:,2)
z = Input_Matrix(:,3)
colorbar('location','Manual', 'position', [0.93 0.1 0.02 0.81]);

az = 0;
el = 90;
view(az, el);

%scatter3(x,y,z,'filled')%Problem i dont know to make it filled
view(0,90)% view from above !!!http://de.mathworks.com/help/matlab/ref/view.html
a = 30;%markersize
scatter3(x, y, z, a, z, 'filled');
view(0, 90)
idx = find(max(z)) ;
hold on
plot3(x(idx),y(idx),z(idx),'*r')
colorbar
datacursormode on

How can I figure out the highest value in my diagram? I want to mark it in my diagram. So the x y and z value should be displayed from the highest value -> z!. Thank you for your help guys. I really appreciate it.
Input_Matrix = textread('Rainflow_Input1.txt')
[zeilen,spalten]=size(Input_Matrix)
x = Input_Matrix(:,1)
y = Input_Matrix(:,2)
z = Input_Matrix(:,3)
colorbar('location','Manual', 'position', [0.93 0.1 0.02 0.81]);

az = 0;
el = 90;
view(az, el);

%scatter3(x,y,z,'filled')%Problem i dont know to make it filled
view(0,90)% view from above !!!http://de.mathworks.com/help/matlab/ref/view.html
a = 30;%markersize
scatter3(x, y, z, a, z, 'filled');
view(0, 90)
colorbar;
datacursormode on
;

My input:
-220.8  228 50045
-222    201.6   50045
-220.2  198 200176
-224.4  196.8   200176
-220.8  192 200176
-221.4  190.8   50044
-226.2  176.4   200176
-199.2  156 50044
-201.6  153.6   50045
-219    147.6   50044
-252.6  133.2   50044
-210    129.6   200176
-250.8  127.2   50044
-201    126 50044
-229.2  124.8   50044
-183    123.6   200176
-168    122.4   200176
-275.4  118.8   200176
-261    13.2    400352
-259.8  13.2    200176
-258.6  13.2    200176
-257.4  13.2    290176

A: The maximum value (of z  I assume) of your data will be m in index ind
[m,ind]=max(z);

If you are worried that there are more than one, you can then always do
indexes=find(z==m);

To mark them, after the call to scatter3 do a hold on and call scatter3 just with the maximum valued data, and another format e.g. '*' and maybe some other color


text:
Q: Classic ASP, SQL Server, Windows Azure, Radio button UPDATE SET command - Unexpected behavior I've inherited a classic ASP app and migrated to Windows Azure, SQL and all things work OK -except- one odd issue maybe you'd know about?
Scenario
Select rows of data order by matching unique ID - present to user interface. Two rows per 'set'. One already marked in field 'MasterSelect' with a 'Y'. ASP code called via radio button OnClick clears (or should) both fields in both records, then sets the new record's field to have a 'Y' whether it's the top or bottom selection. A toggle if you will.
Works like a charm on (local) and half-way works on Azure.
**(local)** ('x' = choose radio button)

x #1 -->  'Y'
  #2 -->  ' '

  #1 -->  ' '
x #2 -->  'Y'

x #1 -->  'Y'
  #2 -->  ' '

**(Azure)**

x #1 -->  'Y'
  #2 -->  ' '

  #1 -->  'Y'  <--- (Should be blank)
x #2 -->  'Y'

x #1 -->  'Y'
  #2 -->  ' '

Here's the code:
' If updating the master select field then need to clear all previous selects for that dupid
if updfield="masterselect" then
    strSQL = "select FileName,DupeID from OnLineContactsM where OnLineRecID=" & keyvalue
    cn.execute("exec insertactivity '','','ajaxUpdate.asp','" & strSQL & "'")
    set rs=cn.execute(strSQL)

    if not rs.eof then
        fn = rs("FileName")
        DID = rs("DupeID")
        strSQL = "update OnLineContactsM set MasterSelect='' where FileName like'" & fn & "' and DupeID='" & DID & "'"
        cn.execute(strSQL)
        'cn.execute("exec insertactivity '','','ajaxUpdate.asp','" & DID & "'")
    end if
end if

The behavior on the remote location is that the top row never gets cleared out but the bottom row always works as expected. AND if I manually run the exact line of code manually, regardless of pointing at (local) or (remote) the code runs flawlessly - on both platforms?!?!?
I thought maybe there'd be some code elsewhere than what I've presented that might reset the first record but would then be unable to explain why the (local) copy did not exhibit that behavior. In other words because things work as expected and always have until Azure came into the picture we were golden.
So, my conclusion would naturally lead me to some environmentally-related cause but I'm at the point where I need wiser heads than mine apparently is.
I've looked at this from all sorts of angles (cache, indexes, code compare, etc) and have concluded bug, incompatibility or environment-related issue. I have search almost all day without anything definitive.
Would anyone have any suggestions on what might be causing the behavioral differences?
TIA!!!

A: Things to check:

*

*DB Collation may be different (case sensitive)

*Some db configs may introduce bugs like SET ARITHIGNORE or SET NOCOUNT

*Transactions: Maybe Azure SQL it's adding an outer transac that not commiting


text:
Q: Table in dynatable prints rows of undefined I installed dynatable plugin in my server and I wanted to create table from data written in JSON. My table with script:

                                    Status
                                    MPK
                                    Restaurant Name
                                    Phone Number
                                    Project Start Date
                                    Project End Sales Date
                                    Project Installation Date
                                    Project End Date
                                    General Manager
                                    IT Manager
                                    Edit

And my wszystkie_prace.json file looks like this:
[
    {
        "Project Type": "Opening Restaurant",
        "MPK": "108006",
        "Old MPK": "234",
        "Restaurant Name": "PL SBX Restauracja Test1",
        "Phone Number": "+48111222333",
        "Project Start Date": "Apr  6 2016 10:00:00:000PM",
        "Project End Sales Date": "Apr  7 2016 10:00:00:000PM",
        "Project Installation Date": "Apr  6 2016 10:00:00:000PM",
        "Project End Date": "Apr  9 2016 10:00:00:000PM",
        "Restaurant Manager": "Zenon Pietrucha",
        "IT Manager": "Andrzej Marchewka",
        "Notes": "Notatka random sdijbwodenhwoidchwoncdown"
    },
    {
        "Project Type": "Closing Restaurant",
        "MPK": "103120",
        "Old MPK": "2134",
        "Restaurant Name": "PL KFC Restauracja Test2",
        "Phone Number": "+48123123123",
        "Project Start Date": "May  2 2016 06:00:00:000AM",
        "Project End Sales Date": "May  3 2016 08:00:00:000PM",
        "Project Installation Date": "May  7 2016 06:00:00:000AM",
        "Project End Date": "May  8 2016 06:00:00:000AM",
        "Restaurant Manager": "Tomasz Ziemniak",
        "IT Manager": "Andrzej Marchewka",
        "Notes": "sodicmwpd efvwefvwefv wefvwefv wefvwe fv ewfvwe\r\nfvwef\r\nvwe\r\nfv\r\nwefv\r\nwef"
    }
]

I'm following official documentation (https://www.dynatable.com/#existing-json), but all I get is set of undefined.

The number of rows is okay, but still I don't know how to deal with this problem.

A: Your code is alright you just have to change the naming style of key literals  like Project Type etc. in your wszystkie_prace.json file ,dyntable follows camel casing for naming keys in json so when there is a single word it goes all in lowercase eg MKP as mkp, if it's multiword it should be written in camelCase eg.Project Type as projectType ,former is what you write in the tr tag inside th later is what correspondingly you write for the key in json
For reference
JSON
[{
    "projectType": "Opening Restaurant",
    "mpk": "108006",
    "oldMpk": "234",
    "restaurantName": "PL SBX Restauracja Test1",
    "phoneNumber": "+48111222333",
    "projectStartDate": "Apr  6 2016 10:00:00:000PM",
    "projectEndSalesDate": "Apr  7 2016 10:00:00:000PM",
    "projectInstallationDate": "Apr  6 2016 10:00:00:000PM",
    "projectEndDate": "Apr  9 2016 10:00:00:000PM",
    "restaurantManager": "Zenon Pietrucha",
    "itManager": "Andrzej Marchewka",
    "notes": "Notatka random sdijbwodenhwoidchwoncdown"
},

//more stuff for other rows

]

HTML

Status

               Project Type
               MPK
               Restaurant Name
               Phone Number
               Project Start Date
               Project End Sales Date
               Project Installation Date
               Project End Date
               General Manager
               IT Manager
               Edit

UPDATE: Sorry i didn't knew (havn't used dynatable since a long time ) but it looks like there are now 4 more naming formats available .
I suggest you to use the lowercase format since i found it the most straightforward
change script to

new json
[
    {
    "project type": "Opening Restaurant",
    "mpk": "108006",
    "old mpk": "234",
    "restaurant name": "PL SBX Restauracja Test1",
    "phone number": "+48111222333",
    "project start date": "Apr  6 2016 10:00:00:000PM",
    "project end sales ate": "Apr  7 2016 10:00:00:000PM",
    "project installation date": "Apr  6 2016 10:00:00:000PM",
    "project end date": "Apr  9 2016 10:00:00:000PM",
    "restaurant manager": "Zenon Pietrucha",
    "it manager": "Andrzej Marchewka",
    "notes": "Notatka random sdijbwodenhwoidchwoncdown",
    "general manager" : "mr .cool",
    "status" : "Active"
    }
]

If willing to explore other naming formats
https://www.dynatable.com/#converting-attribute-names


text:
Q: How to get product Notify Qty by product id in magento 2?
$productId = $orderItem->getProductId();

A: Would something like this work? This should return the notify stock quantity value for the first stock item found for a given product ID.
/**
 * @param StockItemCriteriaInterfaceFactory $stockItemCriteriaFactory
 * @param StockItemRepositoryInterface $stockItemRepository
 */
public function __construct(
    \Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory $stockItemCriteriaFactory,
    \Magento\CatalogInventory\Api\StockItemRepositoryInterface $stockItemRepository
) {
    $this->stockItemCriteriaFactory = $stockItemCriteriaFactory;
    $this->stockItemRepository = $stockItemRepository;
}

/**
 * @param int $productId
 * @return float|null
 */
public function getNotifyStockQtyFromProductId(int $productId): ?float
{
    $criteria = $this->stockItemCriteriaFactory->create();
    $criteria->setProductsFilter($productId);
    $stockItemCollection = $this->stockItemRepository->getList($criteria);
    $stockItems = $stockItemCollection->getItems();

    if (empty($stockItems)) {
        // No stock item found for product.
        return null;
    }

    /** @var \Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem */
    $stockItem = reset($stockItems);
    return $stockItem->getNotifyStockQty();
}

A: May be you should know little: Low stock notification alert the merchant that the salable quantity of a stock has reached a critical threshold.
The Notify Quantity fields (Catalog > Products > specific product > Assigned Sources section) override all other settings. The merchant can assign a different threshold for each source for the specific product.
So, the Notify Qty is the API interface method StockConfiguration.php Model as:
$this->stockConfiguration->getNotifyStockQty($this->getStoreId());


text:
Q: Number of triangles formed by n lines and m parallel lines. This question was posted back in 2012, but a proper answer was never given.
Here's the question I'm stuck on: "How many triangles are formed by $n$ lines, and $m$ parallel lines, where no 3 lines can intersect at one point."
These $m$ parallel lines are all parallel to each other, so all $m$ lines have the same slope.  I've been trying to draw out cases and cannot find some type of pattern.  Any help would be great.
We did this for $n$ non-parallel lines, and found out that the amount of triangles formed was $\binom{n}{3}$.
So we'd have $n-m$ non-parallel lines, and we were trying to find a pattern by drawming more lines, and more non/parallel lines with no success.

A: A triangle can be formed either by 3 of the non-parallel lines or 2 of the non-parallel lines combined with one of the parallel lines (no triangle can be formed with 2 or more of the parallel lines).
therefore, the total number of triangles is $\binom{n-m}{3}$ + $\binom {n-m}{2}$ * m


text:
Q: postgres how to rewrite merge statement using INSERT and UPDATE I got Merge statement in Oracle (migrating to EDB Postgres), but unfortunately, EDB postgres doesn't support merge statement.
So how to rewrite below merge statement using INSERT and UPDATE.
BEGIN

        Merge into sds_dia_error_per_min_data using dual
        on (sde_date = in_date and sde_inst_name = in_inst_name
        and sde_interface_name = in_interface_name and sde_command_code = in_command_code and sde_result_code = in_result_code)
        when matched then
        update set
        sde_error_sent = sde_error_sent + in_error_sent,
        sde_error_received = sde_error_received + in_error_received
        WHEN NOT MATCHED THEN
        Insert (sde_date,sde_inst_name,sde_interface_name,sde_command_code,sde_result_code,sde_error_sent,
        sde_error_received)
        values
        (in_date,in_inst_name,in_interface_name,
        in_command_code,in_result_code,in_error_sent,
        in_error_received);

        out_status := 0 ;
COMMIT;


text:
Q: How to use javascript variable to change the height of the div using cssText var randomHeight = Math.floor((Math.random()*100)+50);
document.getElementById("child").style.cssText="background-color:red; height:randomHeight+'px'; width:100px;";

A: You need string concatenation or Template literals. Also element should be display:block;

Concatenation

var randomHeight = Math.floor((Math.random()*100)+50);
document.getElementById("child").style.cssText="display:block;background-color:red; height:"+randomHeight+"px; width:100px;";
ABC

Template literals

var randomHeight = Math.floor((Math.random()*100)+50);
document.getElementById("child1").style.cssText=`display:block;background-color:red; height:${randomHeight}px; width:100px;`;
Def


text:
Q: Firebase : How to put the currently returned node's key into a POJO as a field I hope to improve the title of this question
Assume I have the following.
abstract class getMessage {
      public getMessage(String k) {
         get(k);
      }

      public abstract void Success(Message message);
      private void get(final String k) {
         DatabaseReference r    = DB.child("chat/messages/" + k);
         r.addListenerForSingleValueEvent(new ValueEventListener(){
            @Override
            public void onDataChange(DataSnapshot d) {
               Message msg = d.getValue(Message.class);
               Success(msg);
            }

            @Override
            public void onCancelled(DatabaseError e) {
               Log.w("Get Message", e.toException());
            }
         });
      }
   }

The Message Class has a field "messageid", which should be the key of the returned node, but the returned data is the child of this key.

Before this, I inserted the fields with :
Long time         = d.child("time").getValue();
Long String       = d.child("text").getValue();
Long messageid    = d.getKey();
Message message   = new Message(time, messageid, text);

As you can see above, I was able to take the "messageid" and put it into the Message object, but using the new approach(First Code block), I don't know how to do this.
Is it possible?
EDIT
THE Message Class :
public class Message implements Serializable {
   private String  name;
   private String  msg;
   private String  icon;
   private String  recipient;
   private String  sender;
   private String  shared;
   private Boolean group;
   private Object  time;
   private String  messageid;
   private Boolean local;
   private Boolean delivered;
   private Boolean read;
   private HashMap<String, Boolean> allowed;

   private String file;
   private Boolean attachment;
   private Boolean state;

   public Message(String Name, String Msg, String Recipient, String Sender, String Shared, Boolean Group, String Icon,
                  Object Time, String Messageid, Boolean Local, Boolean Delivered, Boolean Read,
                  HashMap<String, Boolean> Allowed, String File, Boolean Attachment, Boolean State) {
      name = Name;
      msg = Msg;
      recipient = Recipient;
      sender = Sender;
      shared = Shared;
      group = Group;
      time = Time;
      icon = Icon;
      messageid = Messageid;
      local = Local;
      delivered = Delivered;
      read = Read;
      file  = File;
      allowed   = Allowed;
      attachment    = Attachment;
      state         = State;
   }

   public Message() {

   }

   public Boolean getAttachment() {
      return attachment;
   }

   public Boolean getState() {
      return state;
   }

   public HashMap<String, Boolean> getAllowed() {
      return allowed;
   }

   public String getFile() {
      return file;
   }

   public Boolean getDelivered() {
      return delivered;
   }

   public Boolean getRead() {
      return read;
   }

   public Boolean getLocal() {
      return local;
   }

   public String getMessageid() {
      return messageid;
   }

   public String getName() {
      return name;
   }

   public Object getTime() {
      return time;
   }

   public String getMsg() {
      return msg;
   }

   public Boolean getGroup() {
      return group;
   }

   public String getRecipient() {
      return recipient;
   }

   public String getSender() {
      return sender;
   }

   public String getShared() {
      return shared;
   }

   public String getIcon() {
      return icon;
   }
}

A: You can do this by adding a setter to the Message class and then call that method to set the key.
public void setMessageid(String messageId) {
    this.messageid = messageId;
}

inside the onDataChange method
Message msg = d.getValue(Message.class);
msg.setMessageId(d.getKey());
Success(msg);


text:
Q: Dead code in while loop java If dead codes are illegal in java, why does the following code compile fine without any compile time error :
int i= 5;

while (i<2) {
  //some code here
}

Since the while condition is not getting satisfied, it will never go into the loop, so I assume this should be dead code. But it is getting compiled perfectly.

A: Java has a very tightly defined set of rules for defining reachability at compile time. (Note that a program can never know in full generality.)
Your case is not one of those, so compilation passes.
(It would be annoying if the reachability rules were constantly changing as that would cause code to break on successive version updates.)

A: Java cannot determine the value of a variable in general without simply running the program. If it runs your program, it risks failing to terminate. So there is no general way to determine whether or not that loop will always run or not. There will always be cases that the compiler gets wrong, so it uses basic heuristics to handle the easy cases and leaves it at that.
Further reading


text:
Q: Retrieve data from two columns of csv file based on user input I have this csv file named sample.csv:
CODE     HOME_TEAM     AWAY_TEAM
0001        Lakers          Jazz
0002       Raptors        Lakers
0003      Warriors      Portland
0004     Mavericks        Lakers
0005       Celtics     Mavericks

I wish to print every game the team participated based on the user input.  Suppose that in the example above, the user inputs "Lakers," the program should print:
CODE     HOME_TEAM     AWAY_TEAM
0001        Lakers          Jazz
0002       Raptors        Lakers
0004     Mavericks        Lakers

So far, what I've coded (see below) prints the information separately.
import pandas as pd

df = pd.read_csv("sample.csv")

select_Team = input("Which team do you like to see: ")
df2 = df[df["HOME_TEAM"] == select_Team]
df3 = df[df["AWAY_TEAM"] == select_Team]
print(df2)
print(df3)

What should I do to present the information as one (like the one I've shown above)?

A: If you want to include both conditions
df2 = df[(df["HOME_TEAM"] == select_Team) | (df["AWAY_TEAM"] == select_Team)]

A: Let us try eq with any PS is the team is more than one change eq to isin
out = df[df.eq('Lakers').any(1)] # df[df.isin(['Lakers']).any(1)]
Out[462]:
   CODE  HOME_TEAM AWAY_TEAM
0     1     Lakers      Jazz
1     2    Raptors    Lakers
3     4  Mavericks    Lakers

A: You can also create some logic to raise a value error if the team entered is not in the DataFrame:
select_Team = input("Which team do you like to see: ")

df2 = df[(df['HOME_TEAM'].str.lower() == select_Team.lower()) | (df['AWAY_TEAM'].str.lower() == select_Team.lower())]
if len(df2) == 0:
    raise ValueError(f"{select_Team} is not in the DataFrame. The teams available are {set(df[['HOME_TEAM', 'AWAY_TEAM']].stack())}")
else:
    print(df2)


text:
Q: Find SIM Service number or sim card number in windows? I'm trying to find the SIM service number (mobile number) in windows via the command line, or powershell.
I've run through all the netsh mbn show * commands.
None show the mobile service number (eg: +6143xxxxx)
The alternative is to find the Sim card number.
The ICCID is NOT the same as the imprinting on the sims, so the ICCID number isn't helpful.
I need to audit out laptops and extract this info. I feel like it's something that should be available considering it's using the mobile service.
Really battling to find info on this via the goog, with Win10 Mob coming up a lot :(
Keen to have your help and assistant guys.
Cheers,

A: The solution to this was getting the list of device numbers + IMEIs from my carrier.
Combined with the cmd
netsh mbn sh interface

This has enabled me to get / correlate the info required.


text:
Q: How to navigate to any view inside of a NavigationView I have these 3 different views they all connect to each other through a NavigationView. I am trying to find a way to navigate to a page earlier in the NavigationView but I want the transition to seem like it is going backwards.
struct Testing: View {

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination:testing2()) { Text("Go to two") }
            }
            .navigationBarTitle("Navigation")
        }
    }
}

struct testing2 : View {

    var body: some View{
        VStack {
            NavigationLink(destination: testing3()) { Text("Go to third") }
        }
        .navigationBarTitle("Second Page")
    }
}

struct testing3 : View {

    var body: some View{
        VStack {
            Text("Go back to first")
        }
        .navigationBarTitle("Third Page")
    }
}

I have found a solution for this using a combination of an Observable Object, an Environment variable and tags and selections on the NavigationLink.
Is their a simpler solution to making the navigation transition go to a specific page and if it is a view that is before the current view preform the backwards transition?

A: A basic workaround is to add a @Binding and pass it along. check the binding index on appear. if it's not the index presentation.wrappedValue.dismiss until it is. A more complicated way is to add a Navigator class that handles all navigation logic.

A: Much simpler solution is to modify your third view as following:
struct testing3 : View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var body: some View{
        VStack {
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
                self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("Go back to first")
            }

        }
        .navigationBarTitle("Third Page")
    }
}


text:
Q: Identify Colors using android Camera Currently working on one academic project regarding color detection in android. I am trying to detect color using android cameras that would during live preview or after the picture is taken.
I am looking for something like this image. This is ColorGrab android application screenshot. Basically I wanted to identify every color as a particular one color. Lets take a example for that, suppose application detected #FF6CBB but this color is actually similar to pink but I want to mark this color as RED in my list. So Basically I want to convert all colors in basic 8 to 10 colors. So any color code which should be fall in particular range and that range should represent only one color.
In this image color code is not actually hex code of Red but we can make this detected color code in Red Color category.
Overall my program goal should be identify any color code of the color wheel as a one color among of particular 10 colors. How and which way I can compute this thing, Shall I use shortest euclidean distance between two colors?
Can anybody please tell me algorithm or way to compute this thing.
image 1

example of color distribution

A: k-nearest neighbors (k=1 in your case) with euclidean distance might work in your case, because you only have 3 dimensions (this method suffer from the curse of dimensionality )
You can also expirement with different distance measures such as Hamming distance


text:
Q: how can I access to my controller in ajax for codeigniter? I have been trying to use site_url,base_url, url directly but nothing change, also gives me error 404
function mostrarDatos(valor){
    $.ajax({
        url:"http://localhost/empresa/empleados/mostrar",
        type:"POST",
        data:{buscar:valor},
        success:function(respuesta){
            //alert(respuesta);
            var registros = eval(respuesta);

            html ="

";
            html +="
#	Nombres	Apellidos	DNI	Telefono	Email	Accion
";
            html +="

";
            for (var i = 0; i < registros.length; i++) {
                html +="
"+registros[i]["id_empleado"]+"	"+registros[i]["nombres_empleado"]+"	"+registros[i]["apellidos_empleado"]+"	"+registros[i]["dni_empleado"]+"	"+registros[i]["telefono_empleado"]+"	"+registros[i]["email_empleado"]+"	E <button class='btn btn-danger' type='button' value='"+registros[i]["id_empleado"]+"'>X</button>
";
            };
            html +="

";
            $("#listaEmpleados").html(html);
        }
    });
}

controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Empleados extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model("Empleados_model");
    }

    public function index()
    {
        $this->load->view('frontend/empleados');
    }

    public function guardar()
    {
        //El metodo is_ajax_request() de la libreria input permite verificar
        //si se esta accediendo mediante el metodo AJAX
        if ($this->input->is_ajax_request())
        {
            $nombres = $this->input->post("nombres");
            $apellidos = $this->input->post("apellidos");
            $dni = $this->input->post("dni");
            $telefono = $this->input->post("telefono");
            $email = $this->input->post("email");

            $datos = array(
                "nombres_empleado" => $nombres,
                "apellidos_empleado" => $apellidos,
                "dni_empleado" => $dni,
                "telefono_empleado" => $telefono,
                "email_empleado" => $email
            );
            if($this->Empleados_model->guardar($datos)==true)
            {
                echo "Registro Guardado";
            }
            else
            {
                echo "No se pudo guardar los datos";
            }
        }
        else
        {
            show_404();
        }
    }

    public function mostrar()
    {
        if ($this->input->is_ajax_request())
        {
            $buscar = $this->input->post("buscar");
            $datos = $this->Empleados_model->mostrar($buscar);
            echo json_encode($datos);
        }
        else
        {
            show_404();
        }
    }

    public function actualizar()
    {
        if ($this->input->is_ajax_request())
        {
            $idsele = $this->input->post("idsele");
            $nombres = $this->input->post("nombressele");
            $apellidos = $this->input->post("apellidossele");
            $dni = $this->input->post("dnisele");
            $telefono = $this->input->post("telefonosele");
            $email = $this->input->post("emailsele");
            $datos = array(
                "nombres_empleado" => $nombres,
                "apellidos_empleado" => $apellidos,
                "dni_empleado" => $dni,
                "telefono_empleado" => $telefono,
                "email_empleado" => $email
            );
            if($this->Empleados_model->actualizar($idsele,$datos) == true)
            {
                echo "Registro Actualizado";
            }
            else
            {
                echo "No se pudo actualizar los datos";
            }
        }
        else
        {
            show_404();
        }
    }

    public function eliminar()
    {
        if ($this->input->is_ajax_request())
        {
            $idsele = $this->input->post("id");
            if($this->Empleados_model->eliminar($idsele) == true)
            {
                echo "Registro Eliminado";
            }
            else
            {
                echo "No se pudo eliminar los datos";
            }
        }
        else
        {
            show_404();
        }
    }

}

A: start by a simple ajax call, and once the call is working fine start calling the model and the other controller logic, so I would suggest you to make a button on the view with an id="test_btn" and then in the javascript use this code
$("#test_btn").click(function()
    {

        var target_url = '<?php echo(base_url()."empleados/mostrar") ; ?>';
        var data_to_send = {buscar:"123"};

        $.ajax(
        {
            url : target_url,
            data: data_to_send,
            type: "POST",
            success: function(return_data)
            {
                alert(return_data)

            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                console.log('textStatus='+textStatus);
                console.log('errorThrown='+errorThrown);
            }
        });

        // prevent default
        return false;
    });

and then in the empleados controller just read the data and return it to the view like so
public function mostrar()
    {
        $buscar = $this->input->post('buscar',TRUE);

        echo($buscar);
    }

then you should get an alert "123"
once you get the alert , then start adding your other logic , just go one step at a time . also use you browser console (F12) that will help you see the call errors and successful calls
hope that helps !


text:
Q: How to put javascript in html file Let me re-explain the whole question.
I want to add this in my website http://www.w3schools.com/howto/howto_js_slideshow.asp
So for this, i have to make a external java file (internal may work, but i want external).
So when i paste the java code in my html file in body tag, the script works fine. So that means, nothing wrong with the script. But when i put the same thing in a different external file, the script is not working.
So the problem must be in the head tag, where i write the external file location. This is my head tag
        <head>
<title>FFH</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
  <link rel="shortcut icon" type="image/x-icon" href="images/ffh.ico" />`
  <script type="text/javascript" src="myscript.js"></script>

Yes, the "myscript.js" is in the same folder and i am 100% sure about it.

A: put your html file and javascript file under the same folder.

A: Following can be a reason for your issue

*

*Invalid src path in the script tag

*Javascript might be disabled in your browser.

*You have a script error/exception that stopped entire page's script execution.

*Maybe you have an Ajax request that won't work if your open it as a local file protocol.  e.g., file://

What can you do?
It is right time for you to know about and use your developer tools available in your favorite browser.
See if it shows 404 or some other error. Then update your SO question with the exact error message that you see. We would be happy to help.
Revised answer based on provided w3c link:
Now we know the exact problem.
You can not add that script tag to the head of the HTML. Because the elements that you refer in the script are not available at that time of execution. Move the script tag just before the end of body tag (all your carousal tags/elements should be present before the script tag) . Then It would work as expected.
If you still want that script tag to be in the head section, then you have to initialize your carousal/slider in DOM ready event or window.Onload event.
Still my earlier comment is relevant,  because you can use developer tools in your browser to find out the exact error statement.

A: As stated in other answers, script-tag may not work if it is located in <head> tag. Try adding it right before </body>.
+don't call it java, they have nothing else in common except name :)


text:
Q: Crawl through all golf course pages with Scrapy I am trying to scrape golf course details of all golf courses in the world using this directory:
https://www.golfadvisor.com/course-directory
While I wrote the parse function to scrape the actual courses:
def parse_filter_course(self, response):

        # checking if it is an actual course page. excluded it for final ran, didnt fully
        # exists = response.css('.CoursePageSidebar-map').get()
        # if exists:

        # the page is split in multiple sections with different amount of details specified on each.
        # I decided to use nested for loop (for section in sections, for detail in section) to retrieve data.
        about_section = response.css('.CourseAbout-information-item')
        details_section = response.css('.CourseAbout-details-item')
        rental_section = response.css('.CourseAbout-rentalsServices-item')
        practice_section = response.css('.CourseAbout-practiceInstruction-item')
        policies_section = response.css('.CourseAbout-policies-item')

        sections = [
            about_section,
            details_section,
            rental_section,
            practice_section,
            policies_section
        ]
        # created a default list dict to add new details from for loops
        dict = defaultdict(list)
        # also have details added NOT from for loop sections, but hard coded using css and xpath selectors.
        dict = {
            'link': response.url,
            'Name': response.css('.CoursePage-pageLeadHeading::text').get().strip(),
            'Review Rating': response.css('.CoursePage-stars .RatingStarItem-stars-value::text').get('').strip(),
            'Number of Reviews': response.css('.CoursePage-stars .desktop::text').get('').strip().replace(' Reviews',''),
            '% Recommend this course': response.css('.RatingRecommendation-percentValue::text').get('').strip().replace('%',''),
            'Address': response.css('.CoursePageSidebar-addressFirst::text').get('').strip(),
            'Phone Number': response.css('.CoursePageSidebar-phoneNumber::text').get('').strip(),
            # website has a redirecting link, did not figure out how to get the main during scraping process
            'Website': urljoin('https://www.golfadvisor.com/', response.css('.CoursePageSidebar-courseWebsite .Link::attr(href)').get()),
            'Latitude': response.css('.CoursePageSidebar-map::attr(data-latitude)').get('').strip(),
            'Longitude': response.css('.CoursePageSidebar-map::attr(data-longitude)').get('').strip(),
            'Description': response.css('.CourseAbout-description p::text').get('').strip(),
            # here, I was suggested to use xpath to retrieve text. should it be used for the fields above and why?
            'Food & Beverage': response.xpath('//h3[.="Available Facilities"]/following-sibling::text()[1]').get('').strip(),
            'Available Facilities': response.xpath('//h3[.="Food & Beverage"]/following-sibling::text()[1]').get('').strip(),
            # another example of using xpath for microdata
            'Country': response.xpath("(//meta[@itemprop='addressCountry'])/@content").get('')
        }
        # nested for loop I mentioned above
        for section in sections:
            for item in section:
                dict[item.css('.CourseValue-label::text').get().strip()] = item.css('.CourseValue-value::text').get('').strip()

    yield dict

I am struggling with crawling through all golf courses in the directory.
I had few approaches:

*

*From previous scraping experience, I used scrapy.spider crawler and multiple parse functions for each step to first: scrape all country links from world directory, second: scrape all states/region links from the country directory, third: scrape courses in the region directory.

But I faced the difficulty right away, since some countries don't have regions/states directory, but rather course directory. And I didn't know how to skip one parse function and instead of scraping state/region links start scraping course details.

*So I came across crawlspider, and wrote a rule with link extractor to visit only pages with 'courses/' in the path and ignore pages with 'page=', ' in the path, since those were duplicate course links that lead to the same golf course that was scraped multiple times.

    class GolfCourseSpider(CrawlSpider):
        name = 'golfadvisor'
        allowed_domains = ['golfadvisor.com']
        start_urls = ['https://www.golfadvisor.com/course-directory']
        # use rules to visit only pages with 'courses/' in the path and exclude pages with 'page=1, page=2, etc'
        # since those are duplicate links to the same course
        rules = [
            Rule(LinkExtractor(allow=('courses/'), deny=('page=')), callback='parse_filter_course', follow=True),
        ]

With this method I was able to scrape ~20k courses out of 36k.

*Instead of one start url I extracted country urls and used those as a start urls.
That gave me 26k courses out of 36k.

Can you suggest a better way of crawling through all course pages?
Thank you

A: I would recommend usage of SitemapSpider for this case
as according website's robots.txt - it has sitemaps that contain all 36K course links
import scrapy

class GolfAdvisorComSpider(scrapy.spiders.SitemapSpider):
    name = "golfadvisorcom"
    custom_settings = {"DOWNLOAD_DELAY":1,

                       }
    sitemap_urls = [
        'https://www.golfadvisor.com/sitemap1.xml',
        'https://www.golfadvisor.com/sitemap2.xml'
    ]

    def sitemap_filter(self, entries):
        for entry in entries:
            if "/courses/" in entry.get("loc"):
                yield entry

    def parse(self, response):
        ...
        #parse course data


text:
Q: How to end a recursive function? I'm trying to do a simple example of recursion functions (Both Direct and Indirect) and I can't seem to get it to end can you please help me and explain why? (Also I'm trying to do both Direct and Indirect in this program) Thank you for your help.
int Print();
int main()
{
    Print();
    return 1;
}
int Print()
{
    int i=0;
    do
    {
        printf("%d",i);
        i++;
    }while(i<10);
    if(i==9)
        return 1;
    Print();
}

Edit: The recursion direct and indirect, the direct is supposed to be called from inside the same function and the indirect is supossed to be called from outside the function, also I apologize for not formatting and skipping the while

A: Let i be a parameter of the function.
#include <stdio.h>

int Print(int);
int main()
{
    Print(9);
    return 1;
}
int Print(int i)
{
    if (i <= 0) {
      return 1;
    }
    printf("%d",i);
    return Print(i-1);
}

The do...while part seems weird, are you sure you need that?

A: i will never be 9 in your case. Hence calling of Print() again and again.

A: For starters according to the C Standard the function main without parameters shall be declared like
int main( void )

As for the recursive function (that shall be declared when it is defined like int Print( void )) then there are several problems.
The first one is that the function returns nothing though it has the return type int.
int Print()
{
    // ...
    Print();
}

Secondly due to the do-while loop
do
{
    printf("%d",i);
    i++;
}while(i<10);

the condition in this statement
if(i==9)
    return 1;

is never true because after the loop the variable i is equal to 10. So the function has an indefinite recursion.
And instead of a loop you should use a call to the function itself.
The functions can be defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>

void direct_print( void )
{
    enum { N = 10 };
    static int i = N;

    if ( --i )
    {
        direct_print();
    }
    printf( "%d ", i );
    ++i;
}

void reverse_print( void )
{
    enum { N = 10 };
    static int i = N;

    printf( "%d ", --i );

    if ( i )
    {
        reverse_print();
    }
    ++i;
}

int main(void)
{
    direct_print();
    putchar( '\n' );
    reverse_print();
    putchar( '\n' );

    return 0;
}

Its output is
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0

Or a more straightfoward approach to define the functions direct_print and reverse_print is the following
#include <stdio.h>

void direct_print( void )
{
    const unsigned int N = 10;
    static unsigned int i;

    if ( i < N )
    {
        printf( "%u ", i++ );
        direct_print();
    }
    else
    {
        i = 0;
    }
}

void reverse_print( void )
{
    const unsigned int N = 10;
    static unsigned int i;

    if ( i < N )
    {
        printf( "%u ", N - ++i );
        reverse_print();
    }
    else
    {
        i = 0;
    }
}

int main(void)
{
    direct_print();
    putchar( '\n' );
    reverse_print();
    putchar( '\n' );

    return 0;
}

Take into account that the functions would be more flexible if instead of the magic number 10 within the bodies of the functions they used a parameter.
For example
#include <stdio.h>

void direct_print( unsigned int n )
{
    static unsigned int i;

    if ( i == 0 ) i = n;

    if ( n )
    {
        printf( "%u ", i - n );
        direct_print( n - 1 );
    }

    if ( i == n ) i = 0;
}

void reverse_print( unsigned int n )
{
    if ( n-- )
    {
        printf( "%u ", n );
        reverse_print( n );
    }
}

int main(void)
{
    direct_print( 10 );
    putchar( '\n' );
    reverse_print( 10 );
    putchar( '\n' );

    return 0;
}

The output is the same as shown for the previous program
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0

A: Vlad from Moscow did already great writeup on the OP problems.
I would like to add a solution with the stop_condition.
#include<stdio.h>

void Print(int i, int stop_condition);

int main(void)
{
  Print(0, 10);
  putchar( '\n' );

  return 0;
}

void Print(int i, int stop_condition)
{
    printf("%d ",i++);

    if(i<stop_condition)
        return Print(i, stop_condition);
}

Output:
0 1 2 3 4 5 6 7 8 9

A: In your function return condition if(i==9) will never meet, as it is always i=10. So your Print() function being keep calling recursively forever. First of all you need a situation exactly at what condition/situation you need to use a recursive function? In your example you are printing values from 1 to 9 with the help of a while loop. Now how can you achieve the same by using a recursive function?
 void Print(int i)
 {
       if( i == 0 )//when i become 0 you are not printing but returning
          return;
       else
          Print(--i);//decrement the value by one each time you are calling it recursively
       printf("%d\n",i);
}

And you are calling it like:-
Print(10); // now it will print from 1 till 10;

But how it works? When you first time call this function with parameter 10, in the condition if(i == 0) it will fail as value of i in the first call is 10. In that condition O/S will store all the intermediate data/output (in this case it will store i = 10;) and function's IP(instruction pointer, last execution status that is Print(--i); which was the last executed statement in each  recursive functions) in a stack. And it will call with Print(9); in the first recursive call(Print(--i)). This whole process will continue till Print(0). But when it call with Print(0) function will return without printing the value as it will return after condition if( i == 0 ) because here i became 0. From this point it will return to the previous call. How it returns to previous call? Once a recursive function return it pops the stack and get the IP first and it's intermediate outputs i.e. value of i. In this case when it returns for the first time, i's current values is 1, so in the printf it will print 1. As that is the last line of the function and as per IP that is the remaining instruction to be execute. So it will return normally. Now it will get the IP from the stack where function's variable i's intermediate value was 2 so it will print 2 and return and this will continue till it reached in first call where it's value was 10 and after it print 10 it will return to main.
Hope this will help you.

A: This is an finite loop using recursion, factorial of 5
              i = 5;
              fact=1;
               while(i)
              {
                 fact = fact*i;
                  i- -;
              }


text:
Q: How is Gauss' Law (integral form) arrived at from Coulomb's Law, and how is the differential form arrived at from that? On a similar note: when using Gauss' Law, do you even begin with Coulomb's law, or does one take it as given that flux is the surface integral of the Electric field in the direction of the normal to the surface at a point?

A: Let us for simplicity consider $n$ point charges $q_1$, $\ldots$, $q_n$, at positions $\vec{r}_1$, $\ldots$, $\vec{r}_n$, in the electrostatic limit, with vacuum permittivity $\epsilon_0$.
Now let us sketch one possible strategy to prove Gauss' law from Coulomb's law:

*

*Deduce from Coulomb's law that the electric field at position $\vec{r}$ is
$$\tag{1} \vec{E}(\vec{r})~=~ \sum_{i=1}^n\frac{q_i }{4\pi\epsilon_0}\frac{\vec{r}-\vec{r}_i}{|\vec{r}-\vec{r}_i|^3} .  $$

*Deduce the charge density
$$\tag{2} \rho(\vec{r})~=~\sum_{i=1}^n q_i\delta^3(\vec{r}-\vec{r}_i). $$

*Recall the following mathematical identity
$$\tag{3}\vec{\nabla}\cdot \frac{\vec{r}}{|\vec{r}|^3}~=~4\pi\delta^3(\vec{r}) .$$
(This Phys.SE answer may be useful in proving eq.(3), which may also be written as $\nabla^2\frac{1}{|\vec{r}|}=-4\pi\delta^3(\vec{r})$).

*Use eqs. (1)-(3) to prove Gauss' law in differential form
$$\tag{4} \vec{\nabla}\cdot \vec{E}~=~\frac{\rho}{\epsilon_0} .$$

*Deduce Gauss' law in integral form via the divergence theorem.

A: @Qmechanic's already provided a nice answer.
I would like to provide another one.
Consider a charge $q$ be enclosed by any surface (not necessarily a sphere).
Something like this -

Now, you write the flux coming out of this weird surface -
$$
\phi_E = \displaystyle \oint_S \mathbf{E} \cdot \mathrm{d\mathbf{S}}
$$
We know that -
$$
\mathbf{E} = E \vec{r} = \dfrac{1}{4\pi \epsilon_0} \dfrac{q}{r^2}\vec{r}
$$
So, here in this weird surface. there is no fixed radius, is there? And the surface area that is considered here is not a continuous one.
So, I would get -
$$
\phi_E = \dfrac{q}{4\pi \epsilon_0} \displaystyle \oint_S \dfrac{\mathrm{d\mathbf{S}}}{r^2} \tag{1}
$$
Recall that the term $\dfrac{\mathrm{d\mathbf{S}}}{r^2}$ is the very definition for the steradian - which is equal to $\dfrac{1}{4\pi}$ of a complete sphere. This holds good for any surface.
Simply put, this is the 3D analogue of the $2\pi$ rotation in a circle.
Here, we have its differential element, i.e, $d\Omega = \dfrac{\mathrm{d\mathbf{S}}}{r^2}$
Integrating it entirely, we have
$$
\displaystyle \oint_S \dfrac{\mathrm{d\mathbf{S}}}{r^2} = \displaystyle \oint_S d\Omega = 4\pi$$
Plugging this back into (1), we have -
$$
\phi_E = \dfrac{q}{\epsilon_0}
$$
Which implies -
$$ \displaystyle \oint_S \mathbf{E} \cdot \mathrm{d\mathbf{S}} = \dfrac{q}{\epsilon_0}
$$
Ok, since we're done with deriving the integral form of Gauss's law (Which holds true for any closed surface), the following differential form can be obtained by applying the divergence theorem -
$$
\nabla \cdot \mathbf{E} = \dfrac{\rho}{\epsilon_0}
$$

A: @Qmechanic's proof is a nice general way to prove Gauss Law from Coulumb's Law.However I would like to add a simpler proof which I discovered on YouTube.

Source:https://www.youtube.com/watch?v=X_CHPTZfUGo

A: vs_292, just missed a small point.The dot product.The surface $ds$ should be along the electric field i.e along $\bf{r}$ (position vector).
Proof of Gauss' theorem (with solid zero):
$$\phi = \frac{q}{\epsilon_0}$$
$$d\phi = \vec{E}\cdot d\vec{s}=E\hat{r}\cdot d\vec{s}$$
$$phi = \oint_\limits{s}E\hat{r}\cdot d\vec{s}$$
Here this is the projection of $d\vec{s}$ along $\hat{r}$.
$$d\Omega = \frac{ds'}{r^2}$$
$$\phi = \oint_\limits{s} Eds' = \oint_\limits{s}\frac{1}{r\pi\epsilon_0}\cdot\frac{q}{r^2}ds'$$
$$\Rightarrow\phi=\frac{1}{r\pi\epsilon_0}q\oint_\limits{s}\frac{ds'}{r^2}$$
$$\Rightarrow\phi = \frac{1}{4\pi\epsilon_0}q\oint_\limits{s}d\Omega$$
$$\boxed{\Rightarrow\phi = \frac{1}{4\pi\epsilon_0}q4\pi = \frac{q}{\epsilon_0}}$$
Accompanying picture for the diagrams:

Source: Edupoint Youtube Channel.


text:
Q: Find two different "ways" to show that the following limit doesn't exist $\lim_{(x,y)\to (0,0 )} \frac{x^3y}{x^6 + y^2}$. $$\lim_{(x,y)\to (0,0 )} \frac{x^3y}{x^6 + y^2}$$
I tried to approach it by the $y$-axis:
$$\lim_ {(y)\to (0),(x=0)} =\lim_ {(y) \to (0)}=\frac{0 \cdot y}{0+y^2}=0$$
by the $x$-axis:
$$\lim_ {(x)\to (0),(y=0)} =\lim_ {(x) \to (0)}=\frac{x^3 \cdot 0}{x^6+0^2}=0$$
by $y=x$
$$\lim_ {(x)\to (0),(y=x)} =\lim_ {(x) \to (0)}=\frac{x^3+x}{x^6+x^2}=\frac{x^4}{x^6+x^2}=0$$
Is there any other "way" which gives a different result from $0$? Are my calculations correct?

A: (Community Wiki so that the question registers an answer.)
As above, approaching the origin along the curve $y = x^3$ suggests a limit that approaches $1/2$.
Since it is shown in the OP that other approaches yield a limit that suggests $0$, the limit of the expression cannot exist: $0 \neq 1/2$.

A: An other good method here is also to try with sequences. For instance here if I take $$(x_n,y_n) = (\frac{1}{n},\frac{1}{n^3})$$ which converges to 0 then $$\frac{x_n^3y_n}{x_n^6+y_n^2} = 1/2$$
But if I take $$(\frac{1}{n},\frac{1}{n}))$$ we find as a limit 0. The limits are different for two sequences that converge to 0 so the limit doesn't exist.
I specifically chose this sequence because you can see that  the power of x in all its occurrence is 3 times the power of y in all its occurrences and since its a quotient it works out well. I don't know if that's well explained though, tell me if not.


text:
Q: Spacetime diagram of LCDM I have a question concerning the LCDM spacetime diagram https://i.stack.imgur.com/Uzjtg.png published on the Physics Forum Stack Exchange website
Can space expand with unlimited speed?
How are the set of curves for z = constant (= 1, 3, 10, 50) constructed or calculated, ie what is the mathematical relation plotted in this comoving diagram?

A: To answer your question, we should think like this;
What is the proper distance to a galaxy which we observe as $z=1$?
Let us take the FLRW metric,
$$ds^2=-c^2dt^2+a(t)^2[dr^2+S_{\kappa}(r)d\Omega^2]$$
For the path of light, we can write
$$r=\int_{t_e}^{t_o}\frac {cdt} {a}$$
Now this integral has limit in time. But time is not an observable quantity in cosmology. Hence we should covert the integral limit to redshift by doing some calculations.
If we change the integral limit to redshift, the above integral becomes,
$$r=cH_0^{-1}\int_{z_{now}}^{z_{emitted}}\frac {dz} {E(z)}$$
for $$E(z)=\sqrt{\Omega_{\Lambda}+\Omega_m(1+z)^3+\Omega_r(1+z)^4+\Omega_{\kappa}(1+z)^2}$$
or we can use the simplifed version,
$$E(z)=\sqrt{0.69+0.31(1+z)^3}$$
Now, to find the $r$ at $z=1$, we should simply set $z_{now}=0$ and $z_{emitted}=1$. Because at the time of emission the desired $z$ should be $1$ and at the time of emission $z=0$
So the result is,
$$r=cH_0^{-1}\int_{0}^{1}\frac {dz} {E(z)}$$
$$r=cH_0^{-1}\int_{0}^{1}\frac {dz} {\sqrt{0.69+0.31(1+z)^3}}$$
If you calculate the integral for, $c=3\times 10^8m/s$ and $H_0^{-1}=4.4133353\times 10^{17}s$
$r=10.73256352744068\,\text{Gly}$
So when the galaxy emits a light at a proper distance of $r=10.73 Gly$, the redshift value will be $z=1$
For $z=3$ just change the integral limits and calculate the above integral and it would give you the proper distance for $z=3$.
To find the numerical solution of the above integral, you can use this site
https://www.integral-calculator.com
Note: Since we are taking $z_{now}=0$ proper distance = comoving distance
Here are my findings for different z values,
$$z=1,r=10.73256352744068\,\text{Gly}$$
$$z=3, r=20.567781637223106\,\text{Gly}$$
$$z=10,r=30.486114555308745\,\text{Gly}$$
$$z=50,r=38.602145131495604\,\text{Gly}$$
$$z=1000,r=44.052504979871436\,\text{Gly}$$
And the picture you shared is kind of confusing. I think this is better.

As we can see the redshift values are fixed for a comoving coordinate, with respect to their current proper distances $r$, for $a(t_0)=1$


text:
Q: Is Java Memory Model Sequential Consistency different from Leslie Lamport Definition? JLS-17.4.3 defines the program order per thread where any reordering within the program for the thread would preserve intra-thread semantics. And then it defines sequential consistency in terms of the program-order. It says that the sequential consistency is a total order of all actions consistent with the program order.
Now I have this question where the program order is defined per thread and sequential consistency is defined across all threads. Doesn't this violates the sequential consistency defined by Leslie Lapmort ? -

the result of any execution is the same as
  if the operations of all the processors were
  executed in some sequential order, and the operations
  of each individual processor appear
  in this sequence in the order specified by its
  program.

For an example what if the compiler reorders store and loads looking at the code for a particular thread (The program order of the thread)

Edited : Following section pertains to this session from from youtube.
Java Memory Model Pragmatics
 - 48th min
First sample shows two executions by two threads. The order of each execution preserves intra-thread semantics. The next sample shows the same set of executions but the execution on the left side has reordered it's actions for the Thread-1.
Now if we just think of the program order of Thread-1, the reordering is legal. But what the presenter says is that it violates the sequential consistency. But when I read the JLS, I get the impression that the reordered execution is valid and preserves sequential consistency because of having two legal program orders. Am I wrong on this and if so could you please explain what's wrong with that reasoning ?
int a=0, int b=0;

Thread - 1     Thread - 2
----------     -----------

r1 = a;         b=2;
r2 = b;         a=1;

After reordering

int a=0, int b=0;

Thread - 1     Thread - 2
----------     ----------
r2 = b;
                    b=2;
                    a=1;

r1 = a;

A: I don't think the definitions are inconsistent.  I think they are (just) stated in different ways.
But this is moot for the Java Memory Model because of the following caveat at the end of JLS 7.4.3

"If we were to use sequential consistency as our memory model, many of the compiler and processor optimizations that we have discussed would be illegal. For example, in the trace in Table 17.3, as soon as the write of 3 to p.x occurred, subsequent reads of that location would be required to see that value."

In other words, the JMM does not use Sequential Consistency as its basis.

Regarding that example in the video.  What he is saying is the following (my comments in italics):

*

*SC is easier for the programmer to understand.  His opinion, but probably true.

*The example violates SC.  True, but the JMM doesn't guarantee SC anyway.  Indeed, the JLS itself has an example of a "surprising result" that is due to the JMM not guaranteeing SC!

*Someone should submit a JEP for SC in the JMM.  Debatable whether they should, but they certainly could.

*Actually analyzing potential optimizations to see if they violate SC is hard.  Which is maybe a good reason for the JMM to not guarantee SC.  If fewer optimizations are sound with SC versus the existing JMM, then SC is liable to make JIT compiled code slower in some cases.
AFAIK, he is saying nothing that is contentious from a technical perspective.


text:
Q: Interp1 not defined in Octave GUI for Windows Is anyone else getting the error: interp1 undefined near line... when using the Octave GUI (Octave version 4.0.0) on Windows 10? I was just at another computer using Debian and it worked fine.
Update: just checked it again by SSH'ing into that Debian server and it recognized interp1. Not sure why the difference on Windows version of Octave GUI.