text:
Q: Add multiple values to arraylist from user input I'm trying to add to my array list, then print out the list off all the programmers. Instead it just prints out the single programmer I just entered the details for. My question is. How do you correctly put the information entered into my Array list Programmer? Adding one array to another.
public Programmer(int id, String name, double pay, String time, int managerId) {
    this.mId = id;
    this.mName = name;
    this.mPay = pay;``
    this.mTime = time;
    this.mManagerId = managerId;
    this.mManager = null;

case 4:

    String nameadd, time , manager;
    double pay;
    int manageradd;

    System.out.println("Enter new car data:");

    nameadd = in.getString("Name: ");
    pay = in.getDouble("Wage: ");
    time = in.getString("Part or Full Time: ");
    manageradd = in.getInt("Manager ID: ");

    p = ui.insert(nameadd, time, pay, manageradd );
    System.out.println(p.getName() + ": WAGE: €" + p.getPay()+ " STATUS:" + p.getTime() + " MANAGER: " + p.getManager());

    }

    break;

And heres my View
public Programmer insert(String nameadd, String time, double pay, int manageradd) {

    Programmer p;

    p = new Programmer(0, nameadd, pay, time, manageradd);

    return p;
}

A: At the start of your method or inside your class initialize the list.
List<Programmer> listOfProgrammers = new ArrayList<Programmer>();

Then you can add your programmers when they are created.
listOfProgrammers.add(p);


text:
Q: Gitlab showing 404 while running behind nginx reverse proxy, all within a docker network As the title says, I'm trying to serve Gitlab through an nginx reverse proxy, with both programs being run in separate docker containers connected through a docker network. A picture as an example:
Linux Host
 ____________________________
|                            |
| Docker                     |
|  __________________________|
| |                          |
| | Docker network (test-net)|
| |  ________________________|
| | |                        |
| | | nginx        gitlab    | Only nginx has a port bound to the host (443).
| | | |   |        |   |     | TLS is terminated at nginx as well.
| | | |   |   -->  |   |     | in my test, I have nginx running as localhost.
| | | |___|        |___|     | To access gitlab, hit https://localhost/git/
| | |________________________|
| |__________________________|
|____________________________|

nginx runs with this docker command:
docker run -dit --network=test-net --name=nginx -p 443:443 -v "$PWD/conf":/etc/nginx:ro nginx:alpine && docker logs -f nginx
nginx.conf
<Removed unnecessary config from here, very basic setup>
http {
    keepalive_timeout 65;
    server {
        listen 443 ssl;
        server_name localhost;
        ssl_certificate localhost.crt;
        ssl_certificate_key localhost.key;
        ssl_protocols   TLSv1.2;
        ssl_ciphers HIGH:!aNULL:!MD5;
        location /git/ {
            proxy_pass http://test/;
        }
    }
}

gitlab.rb
<only relevant parts added here>
external_url 'https://localhost'
nginx['listen_port'] = 80
nginx['listen_https'] = false
nginx['proxy_set_headers'] = {
 "Host" => "$http_host_with_default",
 "X-Real-IP" => "$remote_addr",
 "X-Forwarded-For" => "$proxy_add_x_forwarded_for",
 "X-Forwarded-Proto" => "http",
 "Upgrade" => "$http_upgrade",
 "X-Forwarded-Ssl" => "on",
 "Connection" => "$connection_upgrade"
}
nginx['custom_error_pages'] = {
  '404' => {
    'title' => '404',
    'header' => 'You\'ve been hit by !! You\'ve been struck by ! A false URL.',
    'message' => 'Double check that URL! Is it correct?'
  }
}

docker-compose.yml for gitlab:
version: '3.7'
services:
  gitlab:
    image: 'internal-docker-repo:1234/gitlab/gitlab-ce:11.8.3-ce.0'
    restart: always
    hostname: 'test'
    container_name: test
    volumes:
      - './config:/etc/gitlab:rw'
    networks:
      - net
networks:
  net:
    external: true
    name: test-net

Internally (to docker networks) nginx is known as nginx and gitlab is known as test. I have confirmed I can ping each container from inside the other, using their container names.
As it is now, it almost works. When I go to https://localhost/git/ on my linux host I get a 404 error page from gitlab, but no login screen.

I'm obviously missing something but I'm not sure what it is. It's hard for me to tell if it's an NGinx configuration issue or a Gitlab configuration issue.
Log output when I hit https://localhost/git/
nginx log output:
172.19.0.1 - - [07/Jan/2020:21:28:35 +0000] "GET /git/ HTTP/1.1" 404 2289 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0"

gitlab log output:
test      | ==> /var/log/gitlab/nginx/gitlab_access.log <==
test      | 172.19.0.3 - - [07/Jan/2020:21:28:35 +0000] "GET / HTTP/1.0" 404 2289 "" "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0"
test      |
test      | ==> /var/log/gitlab/gitlab-workhorse/current <==
test      | 2020-01-07_21:28:35.10649 test 127.0.0.1:0 - - [2020/01/07:21:28:35 +0000] "GET / HTTP/1.1" 404 3108 "" "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0" 0.001
test      |

A: I think at least one of the problems (if not the most important) is the fact that gitlab expects https://localhost as the URL in your browser. Unfortunately, you're not giving it that, but https://localhost/git, although the request obviously reaches the backend (which is the gitlab container).
Changing the external url directive on the inner nginx to "https://localhost/git" might work as a quick fix. Obviously you need to reconfigure gitlab afterwards:
sudo gitlab-ctl reconfig

If I were you, though, I would use a dedicated domain for gitlab (so a separate server block in nginx), as this would be cleaner to my mind.
Something to the effect of:
server {
        listen 443 ssl;
        server_name gitlab.example.com;
        ssl_certificate localhost.crt;
        ssl_certificate_key localhost.key;
        ssl_protocols   TLSv1.2;
        ssl_ciphers HIGH:!aNULL:!MD5;
        location / {
            proxy_pass http://test/;
              }
        }

And then change the external_url, of course, to gitlab.example.com.
Since you're using the localhost anyway, I don't think it would be much bother if you added this new domain in /etc/hosts :
127.0.0.1 gitlab.example.com

A: Cause
The reason you can't get connected is because of the location in Nginx mismatch the external_url URL defined in gitlab.rb.
In your Nginx configuration, you specify location /git/, while in the Gitlab configuration, you use https://localhost. This will cause the error: when a client requests to access https://localhost/git it will always tail the "git/" at the end of URI, however, your Gitlab is configured to access via https://localhost, so it will never be able to find the webpage!
Solution:
As either change the location /git/ to location / or change the https://localhost to https://localhost/git.
Example
Here is my full configuration on my docker, you can take this as reference:
*Note: 172.16.0.10 is the IP of the Gitlab server, gitlab.drive.nr resolves the IP of the Nginx server
Nginx docker:
$ cat nginx-r.sh
sudo docker run -itd --name=nginx-r \
    --network=testenv \
    --ip 172.16.0.3 \
    --dns 172.16.0.2 \
    -h rproxy.drive.nr \
    -p 80:80 -p 443:443 \
    -v nginx-config:/etc/nginx \
    -v nginx-certs:/etc/ssl/private \
    nginx:alpine

Gitlab docker:
$ cat gitlab.sh
sudo docker run --detach \
  --hostname gitlab.drive.nr \
  --name gitlab \
  --restart always \
  --network testenv \
  --ip 172.16.0.10 \
  --dns 172.16.0.2 \
  --volume gitlab-config:/etc/gitlab \
  --volume gitlab-logs:/var/log/gitlab \
  --volume gitlab-data:/var/opt/gitlab \
  gitlab/gitlab-ce:latest

Nginx configurations:
# cat conf.d/sites-enabled/gitlab.conf
server {
  listen   80;
  location / {
    return 301 https://172.16.0.10;
    }
}

server {
  listen   443 ssl;
  server_name   gitlab.drive.nr;
  ssl_certificate /etc/ssl/private/gitlab.crt;
  ssl_certificate_key /etc/ssl/private/gitlab.key;
  ssl_session_cache builtin:1000 shared:SSL:10m;
  location /git {
    proxy_pass http://172.16.0.10;
  }
}

Gitlab configurations:
# cat gitlab-config/gitlab.rb |grep -v ^#
external_url 'http://gitlab.drive.nr/git'

Test Drive

Log on Nginx:
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git HTTP/1.1" 302 102 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git/users/sign_in HTTP/1.1" 302 150 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git/users/password/edit?reset_password_token=ayjmm32J3Ry_gDR8JbzU HTTP/1.1" 200 9502 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git/assets/application-aeddf31361633b3d1196c6483f25c484855e0f243e7f7e62686a4de9e10ec03b.css HTTP/1.1" 200 149097 "https://gitlab.drive.nr/git/users/password/edit?reset_password_token=ayjmm32J3Ry_gDR8JbzU" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git/assets/print-74c3df10dad473d66660c828e3aa54ca3bfeac6d8bb708643331403fe7211e60.css HTTP/1.1" 200 382 "https://gitlab.drive.nr/git/users/password/edit?reset_password_token=ayjmm32J3Ry_gDR8JbzU" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git/assets/webpack/runtime.ee78bc38.bundle.js HTTP/1.1" 200 2134 "https://gitlab.drive.nr/git/users/password/edit?reset_password_token=ayjmm32J3Ry_gDR8JbzU" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git/assets/highlight/themes/white-3144068cf4f603d290f553b653926358ddcd02493b9728f62417682657fc58c0.css HTTP/1.1" 200 864 "https://gitlab.drive.nr/git/users/password/edit?reset_password_token=ayjmm32J3Ry_gDR8JbzU" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git/assets/webpack/main.b91d0a07.chunk.js HTTP/1.1" 200 830262 "https://gitlab.drive.nr/git/users/password/edit?reset_password_token=ayjmm32J3Ry_gDR8JbzU" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:26 +0000] "GET /git/assets/webpack/default.ca6f81b2.chunk.js HTTP/1.1" 200 159 "https://gitlab.drive.nr/git/users/password/edit?reset_password_token=ayjmm32J3Ry_gDR8JbzU" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:27 +0000] "GET /git/assets/icons-e91700f3f1ecff110fc2c35aa62aec8f2aad69d1bfb35844186a11175a79e25f.svg HTTP/1.1" 200 25983 "https://gitlab.drive.nr/git/users/password/edit?reset_password_token=ayjmm32J3Ry_gDR8JbzU" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:27 +0000] "GET /git/assets/touch-icon-ipad-retina-8ebe416f5313483d9c1bc772b5bbe03ecad52a54eba443e5215a22caed2a16a2.png HTTP/1.1" 200 5662 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"
172.16.0.1 - - [14/Jan/2020:23:35:27 +0000] "GET /git/assets/favicon-7901bd695fb93edb07975966062049829afb56cf11511236e61bcf425070e36e.png HTTP/1.1" 200 1611 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" "-"

A: I was facing the exact problem described here.
The following settings made it work.
GitLab Docker:
      GITLAB_OMNIBUS_CONFIG: |
        external_url 'http://<domain>/gitlab/'

[...]

    ports:
      - "8929:80"

NGINX:
   location /gitlab/ {

      #  ## https://github.com/gitlabhq/gitlabhq/issues/694
      #  ## Some requests take more than 30 seconds.
       proxy_read_timeout      300;
       proxy_connect_timeout   300;
       proxy_redirect          off;

       proxy_http_version 1.1;

       proxy_set_header    Host                $http_host;
       proxy_set_header    X-Real-IP           $remote_addr;
       proxy_set_header    X-Forwarded-Ssl     on;
       proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
       proxy_set_header    X-Forwarded-Proto   $scheme;

       proxy_pass http://<domain>:8929/gitlab/;
}

A: I had a similar problem (both Gitlab and Nginx running as Docker containers).
The cause of my error was mistakenly using the https protocol when defining the external_url setting.
I.e. it should be:
external_url 'http://MY_DOMAIN'

rather than:
external_url 'https://MY_DOMAIN'

My Nginx config was handling the http -> https redirection for me.
I hope this helps people encountering the same problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: design android app with two views this is my project goals and what I have to write:
image
I designed XML interface files.
page 1:
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.android.mytodolist.MainActivity">

    <Button
        android:id="@+id/btnAddItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add New"
        android:textAllCaps="true"
        android:layout_marginBottom="4dp"
        android:layout_marginRight="4dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:onClick="onAddItemClick"/>

    <ListView
        android:id="@+id/itemList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginBottom="4dp"
        android:layout_above="@+id/btnAddItem" />

    </RelativeLayout>

and this is second page:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.android.mytodolist.MainActivity">

<Button
    android:id="@+id/btnSaveItem"
    android:layout_width="128dp"
    android:layout_height="64dp"
    android:text="Save"
    android:textAllCaps="true"
    android:layout_marginBottom="4dp"
    android:layout_marginEnd="4dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:onClick="onAddItemClick"/>

<Button
    android:id="@+id/btnCancelItem"
    android:layout_width="128dp"
    android:layout_height="64dp"
    android:text="Cancel"
    android:textAllCaps="true"
    android:layout_marginBottom="4dp"
    android:layout_marginStart="4dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:onClick="onCancelItemClick"/>

<EditText
    android:id="@+id/txtNewItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:ems="10"
    android:inputType="textPersonName"
    android:hint="New Item" />

for task 1.2 i Add this code:
    public void onAddItemClick(View view) {

    Intent main2 = new Intent(MainActivity.this,Main2Activity.class);
    MainActivity.this.startActivity(main2);
}

i need help to write rest of code, especially how to come up with arryList and arryAdaptor so user can see result of saved items on first page and add or edit items on second page and adding time to edit text and also save and cancel button.
if anyone can help me with that it will be appreciated.

A: To take some data to another Activity, you can put the data in a Bundle object and then put that Bundle object to the intent and then get that bundle in another activity and then get those data from there? What do you actually want to do? Tell me?
Creating the Bundle from the First Activity.
Intent mIntent = new Intent(this, Example.class);
 Bundle mBundle = new Bundle();
 mBundle.putString(key, value);
 mIntent.putExtras(mBundle);

In the second Activity to get the data, you can write this.
String value = getIntent().getExtras().getString(key)


text:
Q: Problem with sort by category? When I have products in categories ( I have sub-categories in this category) I don't have sort by category just sort by price. I want to add sort by category with sort by price.
For example :
if i have computer category and i have laptop and Desktop sub-categories. I have many products also in computer category. When i am in computer catalog i wish to show also in navigation layer :
Sort by
 Category :
   Laptop(1)
   Desktop(2)

What is the problem ?

A: Why don't you use logic like this
when we use order by as single column we have result as

primary sort                         secondary sort
1.  50 | This article rocks          | Feb 4, 2009    3.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

AFTER using following query

ORDER BY article_rating, article_time DESC

which will result as

primary sort                         secondary sort
1.  50 | This article rocks          | Feb 2, 2009    3.
1.  50 | This article rocks, too     | Feb 4, 2009    4.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

Hope above will help you.


text:
Q: Apache sends wrong server principal name to Kerberos I am trying to authenticate my apache against kerberos.
I have two websites running on the same server, and I use VirtualHosts to achieve that and set DNS to have two names for this server to have a separate one for each website.
I added recently a new ldap/Kerberos server and trying to connect one of my websites to it, but I failed to get the correct credentials to get it works.
After adding some debugs, I found that apache looks for HTTP/fist-server-name instead of HTTP/second-server-name and for that reason couldn't find the correct principal in Kerberos database and keytab.
How to force apache to do its check against the second server name to validate the call from my second website? It looks adding ServerName attribute in apache configuration is not enough to do that!
I am able to do that by changing the server name orders in hosts file, but this can't help if I want to authenticate from the both server names!
Thanks.

A: I'm assuming that you're using mod_auth_kerb.  You need to add:
KrbServiceName Any

to your Apache configuration.  This will tell mod_auth_kerb to accept authentications to any principal for which there is a key stored in the keytab it uses, rather than making assumptions about what principal will be used and only accepting authentications to that principal.

A: You need to identify which Kerberos SPN you want to use for each website. You can check what SPNs are listed in your keytab by running: klist -k <Keytab> -- make sure that you're checking the keytab file that Apache uses.
In the VirtualHost declaration you need to change the KrbServiceName value to match the one that you identified from the keytab. Restart Apache and it should start using that when communicating with Kerberos.
An example would look something like:
 KrbServiceName HTTP/yourservice.domain@REALM.COM

Make sure that AD has a service account and SPN that matches and that it can resolve via DNS back to the Apache server.

A: I found this recently in the MIT Kerberos documentation on Principal names and DNS:

Applications can choose to use a default hostname component in their service principal name when accepting authentication, which avoids some sorts of hostname mismatches. Because not all relevant applications do this yet, using the krb5.conf setting:

[libdefaults]
    ignore_acceptor_hostname = true

will allow the Kerberos library to override the application's choice of service principal hostname and will allow a server program to accept incoming authentications using any key in its keytab that matches the service name and realm name (if given). This setting defaults to "false" and is available in releases krb5-1.10 and later.


text:
Q: htlatex with greek encoding I used htlatex to the following code (say foo.tex)
\documentclass[10pt]{article}
\usepackage{tikz}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amscd}
\usepackage{makeidx}
\usepackage{graphicx}
\usepackage[english,greek]{babel}
\usepackage[iso-8859-7]{inputenc}
\usepackage{multibib}

\begin{document}

αβγδ
{\it αβγδ}

\end{document}

I execute
mk4ht htlatex foo.tex "xhtml,mathml"
and the html file gave me the following
αβγδ abgd
I would expect
αβγδ *αβγδ*
That is can not translate right the \it with the greek characters.
Any idea?
Thank you.

A: This is caused by how tex4ht process fonts - special conversion files for each used font is used. This file is obviously missing for Greek italics. Simple solution is to disable italics font with tex4ht.
First of all, you should edit your source file and use
\textit{αβγδ}

instead of
{\it αβγδ}

because this form cannot be easily converted to html with this technique.
Then create custom config file config.cfg:
\Preamble{xhtml, mathml}
\begin{document}
\renewcommand\textit[1]{\ifvmode\ShowPar\fi\NoFonts\HCode{}#1\HCode{}\EndNoFonts}
\EndPreamble

This configuration will prevent usage of italics font and will insert  tags.
Compile with:
htlatex  foo.tex "config, charset=utf-8" " -cunihtf -utf8"

Result:

αβγδ αβγδ


text:
Q: Is there anyway to change the appearance of the EditText? I want my edittext to be appeared as shown in pic1. My current edittext looks like pic2. Is there any way to change it through the edittext's properties? and why it is changing?
pic1

pic2

A: You can change the look of an EditText by changing the background image.
As has been pointed out, the reason it looks different is because of the android version. I don't recommend you use the old assets directly, but you could certainly make your own to look exactly how you want.


text:
Q: Loop is skipping first record of Data Table vb.net The following loop is driving me nuts is missing the frist record even though its not their bare in mind im a c# programmer transition Can someone help and tell me what I am doing wrong here
    WriteToLogAndRaiseFeedback("Setting Department Codes Started " & Now.ToShortTimeString(), True)
    Dim i As Int16
    i = 0
    For Each thisEntry As DataRow In findDepartmentsForGemini.Rows
        i = i + 1
        connection.ExecuteNonQuerySql(scriptBuilder.setGeminiDepartmentCodes(findDepartmentsForGemini.Rows(i).Item(0), findDepartmentsForGemini.Rows(i).Item(2)))

    Next

    WriteToLogAndRaiseFeedback("Setting Department Codes Completed" & Now.ToShortTimeString(), True)

A: Arrays start at index zero, so, your increment of the variable i before accessing the row, causes the skip of the first row.
However, it is not clear why you need to use this variable as indexer.
You have already the reference at the DataRow that you want to use thanks to the enumerator triggered by the foreach
For Each thisEntry As DataRow In findDepartmentsForGemini.Rows
    connection.ExecuteNonQuerySql(scriptBuilder.setGeminiDepartmentCodes _
                                  (thisEntry.Item(0), thisEntry.Item(2)))


text:
Q: Binary search two unsigned integers A function which inputs two unsigned integers a and b and finds whether the lowest byte of b appears exactly as it is in a (starting at any position) or not. ex:
    Enter a:53
    Enter b:13
    Binary of b: 00000000 00000000 00000000 00001101
    Binary of a: 00000000 00000000 00000000 00110101
    Yes, lowest byte of b appears in a.

GUYS this is my home work but i cant do it pls help me thank you for your helping

A: Here is some pseudo-code to get you started:
found = FALSE
for shift = 0 to 24
    if least significant byte of a == least significant byte of b then
        found = TRUE
        break
    endif
    shift a right by 1 bit
endfor

Now all you have to do is turn this into C code.


text:
Q: RXJS: Return the manipulated value of outer observable I am trying to call two observables, with the response from second I manipulate the first and then return a new observable.
return this.http.get(requestUrl)
            .map((response: User) => {
                sessionManager.currentUser = response;
                return this.isFirstTimeUser(response.id);
            })
            .do((response: any) => {
                console.log(response);
                sessionManager.currentUser.firstTimeLogin = response === 'true';
                return Observable.create(sessionManager.currentUser);
            })
            .toPromise();

isFirstTimeUser(response.id) is another function that returns an observable.
private isFirstTimeUser(userId: number): Observable<any> {
        const requestUrl = 'someUrl';
        return this.http.get(requestUrl, {responseType: 'text'});
    }

All I want to do is get the user object from the first http call, make another request using the user's id in the second call and then after I get back the response from the second observable, I update a property of the first response and return the updated first response. How do I achieve this? What rxjs function should I be looking at?

A: The solution you're looking for is something like that:
getUser(): Observable<any>{
    return this.http.get(reqUrl)
        .do((res: User) => {
            sessionManager.currentUser = res;
        })
        .switchMap((res: User) => {
            return this.isFirstTimeUser(res.id);
        })
        .do((res: any) => {
            console.log(response);
        }
        .map((res: any) => {
            sessionManager.currentUser.firstTimeLogin = res === 'true';
            return sessionManager.currentUser;
        });
}

Then you just need to subscribe to getUser() and you should be alright. It is still not the best code according to rxjs functional paradigm of pure functions. I guess using concatMap with projection function would get us closer to ideal, but  it will work.
The reason it's not ideal is because there's a required side effect in the first .do() block, we update the sessionManager value - a variable outside the function (a big no no in functional world) and then we access it again in .map() function. concatMap with projection function as a 2nd argument would get us around this.

A: You were close in your example.
You want to use switchMap which unsubscribes to the incoming observable, and subscribes to the next observable.
return this.http.get(requestUrl)
        .switchMap((response: User) => {
            sessionManager.currentUser = response;
            return this.isFirstTimeUser(response.id);
        })
        .map((response: any) => {
            console.log(response);
            sessionManager.currentUser.firstTimeLogin = response === 'true';
            return sessionManager.currentUser;
        })
        .toPromise();

The response will be passed to isFirstTimeuser() and the following .map() will be applied to the observabled returned by that function.
It's called switchMap because the observable returned by this.http.get() is unsubscribed and the next observable is used. This won't be a problem with this.http.get(), but keep in mind that switchMap only works for the first emitted value.

A: Use mergeMap
return this.http.get(requestUrl)
            .mergeMap((response: User) => {
                const currentUser = response;
                currentUser.firstTimeLogin = this.isFirstTimeUser(response.id) === 'true'
                return Observable.of(currentUser);
            })


text:
Q: Differnece Between MYSQL(Binary) and MySql in LAMP/WAMP/MAMP
*

*What is difference between MySQL(Binary) and MySql in (LAMP,MAMP, WAMP) ?

*Which one is better to use?

*On What Criteria  i should select one of them?

Regardless of Operating System.
  Which of mysql will be better to use for web as well as standalone development.

A: If I understand what you are asking,

*

*There is no appreciable difference between MySQL running on Windows/Linux/Mac environments.

*Whichever you find easiest.

*As a windows user I develop using WampServer on a windows PC, that gets me Apache/MySQL and PHP all in one easy to install package. However it is normal and in many ways preferable to use a *nix  environment for implementing your LIVE website on.


text:
Q: Create lines from points arcpy I have a points shapefile, and a file that tells me which of the points have a line between them. I am using arcpy to create a new shapefile to hold the lines and then create the lines based on the specifications in the file. For creating the lines, I am reading the coords of the points from the point shapefile itself.
out_path = arcpy.env.workspace
out_name = arcpy.ValidateTableName("the_lines")
geometry_type = "POLYLINE"
has_m = "DISABLED"
has_z = "DISABLED"
spatial_reference = arcpy.Describe(points_shp).spatialReference # Use Describe to get a SpatialReference object
# Execute CreateFeatureclass
arcpy.CreateFeatureclass_management(out_path, out_name, geometry_type,spatial_reference = spatial_reference)

array = arcpy.Array()
point = arcpy.Point()
tie_shp_file = arcpy.env.workspace + "/" + out_name
insert_cursor = arcpy.InsertCursor(tie_shp_file)
feat = insert_cursor.newRow()

for line in all_lines:   #all_lines is of the form array([[0, 3],[0, 7],[1, 3]) indicating line [from, to]
    #from
    point.x=coords_pts[str(pt[line[0]])][0]
    point.y=coords_pts[str(pt[line[0]])][1]
    print "FROM: " + str(pt[line[0]]) + " COORDS_X: " + str(coords_pts[str(pt[line[0]])][0]) + " COORDS_Y: " + str(coords_pts[str(pt[line[0]])][1])
    array.add(point)
    #to
    point.x=coords_pts[str(pt[line[1]])][0]
    point.y=coords_pts[str(pt[line[1]])][1]
    print "TO: " + str(pt[line[1]]) + " COORDS_X: " + str(coords_pts[str(pt[line[1]])][0]) + " COORDS_Y: " + str(coords_pts[str(pt[line[1]])][1])
    array.add(point)
    print "ARRAY: " + str(array)
    polyline=arcpy.Polyline(array)# Create a Polyline object based on the array of points
    array.removeAll() #Clear the array
    feat.shape = polyline
    insert_cursor.insertRow(feat)

coords_points is a dictionary that has the form:
 {'10': (8594242.514466941, 3330642.8703512326)...}
i.e. {'Oid_str': (x,y)}

The code is creating the required number of entries in the shapefile but no lines are being shown and the lengths of the line is shown as 0.
Where am I going wrong?

A: Your code looks OK, but you use lower case x and y instead of upper case X and Y. Maybe that could help...
Also, I recommend using
arcpy.da.InsertCursor
if you have ArcGIS 10.1 or higher, for example :
cursor = arcpy.da.InsertCursor(fc2, ("SHAPE@","ID"))

for line in lines:
    i = i+1
    coordList=[]

    coordList.append([ coords_pts[str(pt[line[0]])][0], coords_pts[str(pt[line[0]])][1]])
    coordList.append([ coords_pts[str(pt[line[1]])][0], coords_pts[str(pt[line[1]])][1]])

   polyline = arcpy.Polyline(arcpy.Array([arcpy.Point(*coords) for coords in coordList]))
   cursor.insertRow((polyline,i)))


text:
Q: How to access model attribute in dust.js section I want to know how to access model attribute which is array, inside dust section {#} {/}.
MODEL:

"a":new array();

"b":{
 "c":new array();
}

DUST TEMPLATE:

{#a}
 want to access {c} here...
{/a}

Thanks

A: To access {#c} when you are inside the {#a}. First you need to go up with {#b} then inside there you need to go down to c with {#a}.
So you will need something like this:
{#a}
    {name}
    {#b}
      {#c}
         {name}
      {/c}
    {/b}
{/a}

Demo JSFiddle.


text:
Q: Kafka-python producer.send isn't being recieved in a try-except block, but does send with time.sleep(1) I'm testing a script that runs binwalk on a file and then sends a kafka message to let the sending file know that it was completed or if it failed. It looks like this:
if __name__ == "__main__":
    # finds the path of this file
    scriptpath = os.path.dirname(inspect.getfile(inspect.currentframe()))
    print(scriptpath)
    # sets up kafka consumer on the binwalk topic and kafka producer for the bwsignature topic
    consumer = KafkaConsumer('binwalk', bootstrap_servers=['localhost:9092'])
    producer = KafkaProducer(bootstrap_servers = ['localhost:9092'])

    # watches the binwalk kafka topic
    for msg in consumer:
        # load the json
        job = json.loads(msg.value)
        # get the filepath of the .bin
        filepath = job["src"]
        print(0)

        try:
            # runs the script
            binwalkthedog(filepath, scriptpath)
            # send a receipt
            producer.send('bwsignature', b'accepted')
        except:

            producer.send('bwsignature', b'failed')
            pass

    producer.close()
    consumer.close()

If I send in a file that doesn't give any errors in the 'binwalkthedog' function then it works fine, but if I give it a file that doesn't exist it prints a general error message and moves on to the next input, as it should. For some reason, the producer.send('bwsignature', b'failed') doesn't send unless there's something that creates a delay after the binwalkthedog call fails like time.sleep(1) or a for loop that counts to a million.
Obviously I could keep that in place but it's really gross and I'm sure there's a better way to do this.
This is the temp script I'm using to send and recieve a signal from the binwalkthedog module:
job = {
    'src' : '/home/nick/Documents/summer-2021-intern-project/BinwalkModule/bo.bin',
    'id' : 1
}
chomp = json.dumps(job).encode('ascii')
receipt = KafkaConsumer('bwsignature', bootstrap_servers=['localhost:9092'])
producer = KafkaProducer(bootstrap_servers = ['localhost:9092'])
future = producer.send('binwalk', chomp)

try:
    record_metadata = future.get(timeout=10)
except KafkaError:
    print("sucks")
    pass
print(record_metadata.topic)
print(record_metadata.partition)
print(record_metadata.offset)
producer.close()

for msg in receipt:
    print(msg.value)
    break

A: Kafka producers batch many records together to reduce requests made to the server. If you want to force records to send, rather than introducing a blocking sleep call, or calling a get on the future, you should use producer.flush()


text:
Q: how to find out binary number similarity Recently I have appeared in a coding challenge where one of the question is as below
There are N cars, each having some of M features. A car feature list is given as binary string.
for ex: 0000111
0 means feature not supported.
Two cars are similar if their feature description differs by atmost one feature. for ex: 11001, 11000 are similar for every car, find count of similar cars in a list of cars with features
I have tried to solve the problem with XOR operator. But it worked for few test cases
cars = ["100", "110", "010", "011", "100"]

Here for car at 0th index is similar to 1st and 4th. so output should be 2. similar for all the index car need to be found out with which it is similar.
Solution I tried:
def solution(cars):
    ret_list = []
    for i in range(len(cars)):
        count = 0
        for j in range(len(cars)):
            if i != j:
                if (int(cars[i]) ^ int(cars[j])) <= 100:
                    count += 1
        ret_list.append(count)
        print(ret_list)
    return ret_list

output : [2, 3, 2, 1, 2]
But this doesn't fit to when input is like:
cars = ["1000", "0110", "0010", "0101", "1010"]

Can someone please suggest a better solution that works for all kind of binary number

A: Try this:
def isPowerOf2(x):
    return (x & (x - 1)) == 0

def areSimilar(x, y):
    return isPowerOf2(x ^ y)

def solution(cars):
    similarPairCount = 0
    for i in range(len(cars) - 1):
        for j in range(i + 1, len(cars)):
            if areSimilar(int(cars[i], 2), int(cars[j], 2)):
                similarPairCount += 1
    return similarPairCount

A: import numpy as np

# ...

# conversion to int
cars_int = np.array([int(c,2) for c in cars]).reshape(1,-1)

# matrix to compare all against all
compare = (cars_int ^ cars_int.T) # or exclusive

# result of cars with 0 or 1 hamming distance
# (not including comparison of each car with itself)
result = (np.sum(compare & (compare-1) == 0) - cars_int.size) // 2

if you want a list with similarity by car:
# ...
result_per_car = np.sum(compare & (compare-1) == 0, axis=1) - 1


text:
Q: Monte Carlo Tree Search - "most promising" move function I tried to implement tic-tac-toe hello-world MCTS game player but I encountered a problem.
While simulating the game and choosing "the most promising" (exploit/explore) node I only take total wins number into account ("exploit" part) - this causes certain problem, the resulting algorithm is not defensive at all. As a result when choosing between

*

*move that results in (100 draws; 10 loses)

*move that results in (1 wins; 109 loses)

the worse one is chosen (1; 109) because my uct function greedily counts avg wins instead of "value".
Am I identyfing this problem correctly? Should I switch from "avg wins" to some other value metric that takes all results types into account ?
Any advice is welcome, thanks

A: Since tic-tac-toe is a zero-sum game (value of a state for one player is always equal to the negated value for the opponent), your score function should also reflect this.
This means that, when computing average scores, you should use values like the following:

*

*+1 for every win

*0 for every draw

*-1 for every loss

In your example, this would lead to the following average scores:

*

*move that results in (100 draws; 10 loses): avg. score = -10/110 = -0.0909...

*move that results in (1 wins; 109 loses): avg. score = -108/110 = -0.98181...
So the first option would be viewed as the better option


text:
Q: Building separate css for components in CRA app with SASS Working on a new project setup, and trying to get figure out the configuration to get .scss files to build per component. Ideally, only the necessary css files would load per component added to a page, rather than an entire combined .css file for all components. I know this can be done with JSS, but I believe should work with webpack in a CRA app.
My current project setup is:
/src/App.js
/src/components/

*

*index.js => exports all components for easy import to the page (i.e., import {ComponentName} from './components')

/src/components/{component-name}

*

*{component-name.js}

*{component-name.scss}

Currently trying sass@v1.56.1 and sass-loader@13.2.0, but not sure about the proper setup.
Might need to do a modular setup to accomplish this or just stick with JSS?


text:
Q: React onPress execute immediately ( render time) , but once replace with arrow function it does not work export const Focus = ({addSubject})=>{

const [tempValue, setTempValue] = useState(null);

  return(
    <View style={styles.container}>
     <View style={styles.titleContainer}>
    <Text style={styles.title}> What are you going to focus on....?</Text>
     <View style={styles.inputcontainer}>
    <TextInput style ={{flex:1, marginRight:10}}
    onSubmitEditing ={
      ({nativeEvent}) => {
        setTempValue(nativeEvent.text+'0000')
      }
    }
    />
       <RoundedButton title ='+' onPress={
         addSubject(tempValue)
         }/>

       </View>
     </View>
    </View>
  );
}

Just after entering data, once hit the 'return' it submit entered "text+0000"
but once replace with
 <RoundedButton title ='+' onPress={
         ()=>{ addSubject(tempValue)}
         }/>

on press is not working
*** I'm testing this on on Expo web
What is the reason for this behavior and what is the solution to make it work once press the button.

A: Try without braces, then only it will return the addSubject function
<RoundedButton
  title ='+'
  onPress={()=> addSubject(tempValue)}
/>


text:
Q: How to find the depth of a nested hash of hashes? I am trying to write a Perl subroutine to process any given hash (passed by reference) but I would like to make it a generic one so that I can use it anywhere.
Assuming the hash has simple key/value pairs and is not an elaborated record (containing arrays of arrays or arrays of hashes), is there any way to find how deep the hash of hashes runs?
For example
my %stat = (
    1 => { one => "One is  one.",    two => "two is two"},
    2 => { one => "second val wone", two => "Seconv v"}
);

The hash above has first level key 1 which has two keys one and two. So it is a hash with two levels.
My question is whether is there any way to test and find this information that the hash has two levels?

Update from comment
About the "problem that has led me to believe that I need to know the depth that a Perl hash is nested". Here is my situation.

*

*The program is creating a data structure of three levels, and also publishing it in a text file for other scripts which are processing this published data and doing something else.

*The program is also reading and hashing other data structures of five levels, which has data related to the hash in the first point.

*The program is also processing a continuously growing log file and collecting data.

A: Assuming a uniform hash structure:
use strict;
use warnings;

sub depth {
    my ($h) = @_;
    my $d = 0;
    while () {
        return $d if ref($h) ne 'HASH';
        ($h) = values %$h;
        $d++;
    }
}

my %stat = (
    1 => { one => "One is  one.", two => "two is two"},
    2 => { one => "second val wone", two => "Seconv v"}
);

print depth(\%stat), "\n";

Output:
2

A: Traversing hash values and tracking levels could give answer,
use strict;
use warnings;
use v5.16;

{ my $max;
sub hlevel {
    my ($h, $n) = @_;

    $max = 0 if !$n;
    $max = $n if $max < $n;
    __SUB__->($_, $n +1) for grep {ref eq "HASH"} values %$h;

    return $max;
}}

my %h;
$h{a}{b}{c}{d}{e} =1;
$h{a}{b}{c}{d}{e1}{f} =1;
$h{a}{b}{c}{d}{e1}{f1}{g} =1;
print hlevel(\%h, 0);

output
6


text:
Q: mysql Count Distinct and get result using php I have a mysql query like this:
$topicreplycount = mysql_query('SELECT COUNT(DISTINCT post_msg_id) FROM phpbb_attachments WHERE topic_id = '.$row['topic_id'].' AND post_msg_id < '.$row['post_msg_id']);

and hope to get the result using something like this:
$topicreplycount = mysql_result($topicreplycount);

so lets say there are 4 post_msg_ids like this in the table:
2956
2957
2957
2958
and the current $row['post_msg_id'] is 2958, there are 3 post_msg_ids that are less than the one I am comparing it to, and only 2 Distinct post_msg_ids since two of them are the same, I am expecting "2" to be returned
but it doesn't seem to work, am I doing this correctly? I am not getting anything returned in the $topicreplycount variable at all using this method
I am pretty sure usign mysql_result($topicreplycount) must be wrong but don't know what to use instead

A: Try this:
$sql = mysql_query('SELECT COUNT(DISTINCT post_msg_id) AS num_topics FROM phpbb_attachments WHERE topic_id = '.$row['topic_id'].' AND post_msg_id < '.$row['post_msg_id']);
$result = mysql_result($sql);
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['num_topics'];

A: Using mysql_result you need to specify at least the row number so
$topicreplycount = mysql_result($topicreplycount,0);

should work. As there will only ever be one result returned because you used the COUNT() function this will be fine.
However, it is recommended NOT to use the mysql_ family of functions. They are effectively deprecated (not officially but even the PHP docs recommends not to use them). You should switch to mysqli_ or, perhaps better still, PDO.


text:
Q: MySQL Query COUNTing incorrectly Well, I realise that in fact it's more likely to be my logic that's counting wrong ;)
So here's my query:
SELECT
  code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.date,
  code_tags.*,
  tags.*,
  users.firstname AS authorname,
  users.id AS authorid,
  ratingItems.*, FORMAT((ratingItems.totalPoints / ratingItems.totalVotes), 1) AS rating,
  GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup,
  COUNT(comments.codeid) AS commentcount
FROM
  code
  join code_tags on code_tags.code_id = code.id
  join tags on tags.id = code_tags.tag_id
  join users on users.id = code.author
  left join comments on comments.codeid = code.id
  left join ratingItems on uniqueName = code.id
GROUP BY code_id
ORDER BY date DESC
LIMIT 0, 15

Sorry there's quite a bit of 'bloat' in that. The problem I'm having is with commentcount or (COUNT(comments.codeid) AS commentcount) - I want to count the total number of comments a code submission has. Previously, it was working correctly but I restructured my MySQL syntax and now it's stopped working :(
There's only 2 code submissions in the database that have comments. The first of these results that is returned correctly identifies it has more than 0 comments, but reports it as having '2' in commentcount, when in fact it has only 1.
The second submission ALSO only has one comment, but, it tells me that it has 4!
Can someone tell me what's wrong my logic here?
Thanks!
Jack

A: Try eliminating the GROUP BY constraint.  Then see where your duplicate rows are coming from, and fix your original query.  This will fix your COUNTs as well.

A: Try either:
COUNT(DISTINCT comments.codeid) AS commentcount

or
(SELECT COUNT(*) FROM comments WHERE comments.codeid = code.id) AS commentcount

A: Try starting with a simple query, and building up from that.  If I have understood your structure correctly, the following query will return the correct number of comments for each code submission:
SELECT code.*, COUNT(code.id) AS comment_count
FROM code
JOIN comments ON comments.codeid = code.id
GROUP BY(code.id);

There's a few odd looking column names and joins in your example, which may be contributing to the problem … or it might just be an odd naming scheme :-)
For example, you are joining ratingItems to code by comparing code.id with ratingItems.uniqueName.  That might be correct, but it doesn't quite look right.  Perhaps it should be more like:
LEFT JOIN ratingItems ON ratingItems.code_id = code.id

Start with a basic working query, then add the other joins.


text:
Q: Uploading node_modules to Nexus hosted NPM repository We are building our project in offline build server. Thus we have to store and maintain all our project dependencies in local network Nexus.
I have created hosted NPM registry in Nexus following this guide. I skipped the proxy and group part. Now I want to upload (and maintain) all the project NPM packages (node_modules) from my local workstation to this repository. I don't see upload button in the Nexus repository settings. How to properly upload and maintain NPM packages in Nexus NPM registry? Can this be done by the Nexus GUI, or do I have to use command line? Note the nexus is disconnected from the internet.

A: The UI does not handle transitive dependencies.
You can also use the rest API to manage components directly, and upload all your .tgz packages.
POST /v1/components

For instance, to upload the package my-npm-package-0.0.0.tgz to the repository npm-private use the following:
curl -u user:password -X POST "http://localhost:8081/service/rest/v1/components?repository=npm-private" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "npm.asset=@my-npm-package-0.0.0.tgz;type=application/x-compressed"

The complete live API specs can be found at endpoint /#admin/system/api
The official nexus documentation can be found at https://help.sonatype.com/repomanager3/rest-and-integration-api/components-api

A: UI upload for npm packages was added in version 3.7.0.
https://help.sonatype.com/display/NXRM3/Uploading+Components

A: You don't need to upload the node_modules.
You need to create a proxy and a group repository.
Then you can delete the node_modules and package-lock.json in your project and run npm install.
Because your hosted don't have those packages,it will download them from proxy.
Then you can see those packages in the group.
When you run npm install again,it will download form Nexus ,not NPM.
The download speed will be very fast.


text:
Q: i18n not providing translation for french text with accents in C# code We have a .NET core application in french with i18n to translate in english.
There is one unwanted behavior for which we didn't find a solution : for each text containing accents (like "é") in C# code, i18n doesn't provide the translated msgstr and just show the default language msgid.
For example in my .po file :
#: Views\User\Index.cshtml:58
msgid "Compte bloqué"
msgstr "Blocked account"

This will work if it's :

*

*in plain HTML

*in javascript/jquery

This will not work if it's :

*

*in Razor code (ActionLink, etc...)

*in Model/Controller

i18n sees that it has to translate it since we don't see the [[[ ]]] around the text, but it just doesn't provide the chosen translation and doesn't generate an error. We thought it might be an encoding problem, but each file is in utf-8 (with or without BOM, no difference).
The .pot file header :
msgid ""
msgstr ""
"Project-Id-Version: \n"
"POT-Creation-Date: 2022-10-04 15:13+02:00\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: pot (1.0.16)\n"

Here's how we set i18n in Startup.cs :
    services.AddI18NLocalization(_webHostEnvironment, options =>
    {
        var supportedCultures = new[]
        {
            new CultureInfo("fr-FR"),
            new CultureInfo("en-US")
        };

        var defaultCulture = supportedCultures.Single(x => x.Name == "fr-FR");

        options.DefaultRequestCulture = new RequestCulture(defaultCulture);
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
        options.RequestCultureProviders = new List<IRequestCultureProvider>
        {
            new CookieRequestCultureProvider()
        };
    });

The only thing that is working so far is using a variable in code and write the text with the accents in the msgstr of the .pot file. But it's not a viable solution since it's the template, and every msgstr is reset when i18n makes a change to the file.
So of course we tried to make a .po file for fr-FR (default language), but although it's generated just fine, everything is ignored inside, msgid isn't replaced with the chosen msgstr.
Any idea?


text:
Q: Check if file is in use Hi guys I need some help. I'm trying to open a textfile on a servern from multiple clients at the same time so I'm not locking the file when reading from it. Like this:
new StreamReader(File.Open(logFilePath,
                       FileMode.Open,
                       FileAccess.Read,
                       FileShare.ReadWrite))

Now I'm trying to check if this file is used by any of the clients (because I want to write something new to it), but since I'm not locking it when reading from it I don't know how to do this. I can't try to open and catch an exception because it will open.

A: Do you can try this?
Or watch this question already asked here ->Is there a way to check if a file is in use?
protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

A:
I can't try to open and catch an exception because it will open

Why ? It's a valuable option to work in that way.
By the way you can also create a some empty predefined file, say "access.lock", and others, in order to understand if the actual file is locked check on lock file presence:
if(File.Exist("access.lock"))
  //locked
else
  //write something


text:
Q: C Warning when creating an RSA key pair - random: uninitialized urandom read (32 bytes read) I am creating an RSA key pair with the following code (C and OpenSSL library):
void rsa_gen_keys_ca() {
    RSA *keypair = NULL;
    unsigned char *pub_key = NULL;
    BIGNUM *bne = NULL;
    unsigned long e = RSA_F4;
    int success = 0;

    bne = BN_new();
    success = BN_set_word(bne, e);
    if (!success) {
        errx(1, "\nrsa_gen_keys_ca failed at BN_set_word result.");
        goto free_all;
    }

    keypair = RSA_new();
    success = RSA_generate_key_ex(keypair, RSA_KEY_SIZE, bne, NULL);
    if (!success) {
        errx(1, "\nrsa_gen_keys_ca failed at RSA_generate_key_ex result.");
        goto free_all;
    }

    success = i2d_RSAPublicKey(keypair, &pub_key);
    if (success < 0) {
        errx(1, "\nrsa_gen_keys_ca failed at i2d_RSAPublicKey result.");
        goto free_all;
    }
    printf("==========RSA Public Key successfully extracted: %s", pub_key);

free_all:
    RSA_free(keypair);
    BN_free(bne);
}

When I run it, I am receiving the following warning:

random: uninitialized urandom read (32 bytes read)

I think leaving the code with this warning would be a security concern, since in the past I read something regarding the urandom generator.
Can anyone explain this warning and how to avoid it?


text:
Q: Cannot add navigation.php in another php file Display a
Fatal error: Cannot redeclare class MySQLDB in /home/web/public_html/loginfinal/include/database.php on line 13
when I use the below code.
<?php $site_root = $_SERVER['DOCUMENT_ROOT']; ?>
<?
include("include/session.php");
if(!$session->isVerified() && $session->logged_in){
header("Location: email.php");
}
?>

<title>Login page</title>

<?php
include_once($site_root ."/loginfinal/nav_top.php");
?>

<?
//others detail
?>

After read about this problem now I use the code below which dose't show any error also does't show the navigation too. where is my problem please?
<?php $site_root = $_SERVER['DOCUMENT_ROOT']; ?>
<?
include("include/session.php");
if(!$session->isVerified() && $session->logged_in){
header("Location: email.php");
?>

<title>Login page</title>

<?php
if(!class_exists('MySQLDB') == true){
include_once($site_root ."/loginfinal/nav_top.php");}
?>

<?
//others detail
?>

This is my Nnav_top.php
<?
include("include/session.php");
include("db.php");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<META name="TITLE" content="navigation">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv='Content-Type' content='text/html; charset=UFT-8'/>
<title>navigation</title>

<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/bootstrap-theme.min.css">

        <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
            Toggle navigation

        </button>
        BD Showbiz

Home

About Us

Service

 Event Management

Corporate Event

Wedding Event

Others Privet Event

Special Offer

Web Service

Contact Us

        <form role="search" class="navbar-form navbar-left" method="get" action="/search.htm">

                <input type="text" placeholder="Search" id="tfq" class="form-control" name="q">
                <input type="hidden" name="sitesearch" value="" />
                <input type="hidden" name="sitesearch" value="" checked />

        </form>

<?php
if($session->logged_in){
echo '
'.$session->username.'          ';
echo '
';
echo '
Profile
';
echo '
Setting
';
echo '

';
if($session->isAdmin()){
  echo '
Admin Center
';
}
echo '
Logout
';
echo '
';
}else{
echo '
login ';
echo '
';
echo '                      <form style="margin: 0px" accept-charset="UTF-8"   action="process.php" method="post">';

echo '                      </form>';
echo '
';
}
?>

<?php
global $dbh;
//Check image address
$result2 = mysqli_query($dbh,"SELECT u_imgurl FROM blog_users WHERE username='$session- >username'");
if(!$result2) {
die("Database query failed: " . mysqli_error());
}
$u_imgurl = "";
while ($row = mysqli_fetch_array($result2)) {
$u_imgurl = $row["u_imgurl"];
}
if (empty($u_imgurl)) $u_imgurl = "picture.jpg";
    //End Check image address
if($session->logged_in){
echo '

';
}else{
echo '

Sign Up
';
}
?>

My Database.php
<?
/**
 * Database.php
 *
 * The Database class is meant to simplify the task of accessing
 * information from the website's database.
 *
 *
 */
include("constants.php");

class MySQLDB
{
var $connection;         //The MySQL database connection
var $num_active_users;   //Number of active users viewing site
var $num_active_guests;  //Number of active guests viewing site
var $num_members;        //Number of signed-up users
/* Note: call getNumMembers() to access $num_members! */

/* Class constructor */
function MySQLDB(){
  /* Make connection to database */
  $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
  mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());

  /**
   * Only query database to find out number of members
   * when getNumMembers() is called for the first time,
   * until then, default value set.
   */
  $this->num_members = -1;

  if(TRACK_VISITORS){
     /* Calculate number of users at site */
     $this->calcNumActiveUsers();

     /* Calculate number of guests at site */
     $this->calcNumActiveGuests();
  }
}

function confirmUserPass($username, $password){
  /* Add slashes if necessary (for query) */
  if(!get_magic_quotes_gpc()) {
      $username = addslashes($username);
  }

  /* Verify that user is in database */
  $q = "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";
  $result = mysql_query($q, $this->connection);
  if(!$result || (mysql_numrows($result) < 1)){
     return 1; //Indicates username failure
  }

  /* Retrieve password from result, strip slashes */
  $dbarray = mysql_fetch_array($result);
  $dbarray['password'] = stripslashes($dbarray['password']);
  $password = stripslashes($password);

  /* Validate that password is correct */
  if($password == $dbarray['password']){
     return 0; //Success! Username and password confirmed
  }
  else{
     return 2; //Indicates password failure
  }
}

function confirmUserID($username, $userid){
  /* Add slashes if necessary (for query) */
  if(!get_magic_quotes_gpc()) {
      $username = addslashes($username);
  }

  /* Verify that user is in database */
  $q = "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'";
  $result = mysql_query($q, $this->connection);
  if(!$result || (mysql_numrows($result) < 1)){
     return 1; //Indicates username failure
  }

  /* Retrieve userid from result, strip slashes */
  $dbarray = mysql_fetch_array($result);
  $dbarray['userid'] = stripslashes($dbarray['userid']);
  $userid = stripslashes($userid);

  /* Validate that userid is correct */
  if($userid == $dbarray['userid']){
     return 0; //Success! Username and userid confirmed
  }
  else{
     return 2; //Indicates userid invalid
  }
}

function usernameTaken($username){
  if(!get_magic_quotes_gpc()){
     $username = addslashes($username);
  }
  $q = "SELECT username FROM ".TBL_USERS." WHERE username = '$username'";
  $result = mysql_query($q, $this->connection);
  return (mysql_numrows($result) > 0);
}

function usernameBanned($username){
  if(!get_magic_quotes_gpc()){
     $username = addslashes($username);
  }
  $q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'";
  $result = mysql_query($q, $this->connection);
  return (mysql_numrows($result) > 0);
}

function addNewUser($username, $password, $email, $emailvcode){
  $time = time();
  /* If admin sign up, give admin user level */
  if(strcasecmp($username, ADMIN_NAME) == 0){
     $ulevel = ADMIN_LEVEL;
     $verifystatus = 0;
  }else{
     $ulevel = USER_LEVEL;
     $verifystatus = 0;
  }
  $q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password', '0', $ulevel,     '$email', '$verifystatus', '$emailvcode', '$time')";
  return mysql_query($q, $this->connection);
}

function updateUserField($username, $field, $value){
  $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'";
  return mysql_query($q, $this->connection);
}

function getUserInfo($username){
  $q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
  $result = mysql_query($q, $this->connection);
  /* Error occurred, return given name by default */
  if(!$result || (mysql_numrows($result) < 1)){
     return NULL;
  }
  /* Return result array */
  $dbarray = mysql_fetch_array($result);
  return $dbarray;
}

/**
* retrieve email verification code
*/
function emailVerify($vcode){
  $q = "SELECT * FROM ".TBL_USERS." WHERE emailverifier = '$vcode'";
  $result = mysql_query($q, $this->connection);
  /* Verification code exists, verify user and return true */
  if(mysql_num_rows($result) != 0){
  $q = "UPDATE ".TBL_USERS." SET verifystatus = '1' WHERE emailverifier = '$vcode'";
  $result = mysql_query($q, $this->connection);
     return 1;
  }
  /* verification code doesn't exist return false */
  else
  {
    return 0;
  }
}

function getNumMembers(){
  if($this->num_members < 0){
     $q = "SELECT * FROM ".TBL_USERS;
     $result = mysql_query($q, $this->connection);
     $this->num_members = mysql_numrows($result);
  }
  return $this->num_members;
}

function calcNumActiveUsers(){
  /* Calculate number of users at site */
  $q = "SELECT * FROM ".TBL_ACTIVE_USERS;
  $result = mysql_query($q, $this->connection);
  $this->num_active_users = mysql_numrows($result);
}

function calcNumActiveGuests(){
  /* Calculate number of guests at site */
  $q = "SELECT * FROM ".TBL_ACTIVE_GUESTS;
  $result = mysql_query($q, $this->connection);
  $this->num_active_guests = mysql_numrows($result);
}

function addActiveUser($username, $time){
  $q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'";
  mysql_query($q, $this->connection);

  if(!TRACK_VISITORS) return;
  $q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')";
  mysql_query($q, $this->connection);
  $this->calcNumActiveUsers();
}

/* addActiveGuest - Adds guest to active guests table */
function addActiveGuest($ip, $time){
  if(!TRACK_VISITORS) return;
  $q = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')";
  mysql_query($q, $this->connection);
  $this->calcNumActiveGuests();
}

/* These functions are self explanatory, no need for comments */

/* removeActiveUser */
function removeActiveUser($username){
  if(!TRACK_VISITORS) return;
  $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'";
  mysql_query($q, $this->connection);
  $this->calcNumActiveUsers();
}

/* removeActiveGuest */
function removeActiveGuest($ip){
  if(!TRACK_VISITORS) return;
  $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'";
  mysql_query($q, $this->connection);
  $this->calcNumActiveGuests();
}

/* removeInactiveUsers */
function removeInactiveUsers(){
  if(!TRACK_VISITORS) return;
  $timeout = time()-USER_TIMEOUT*60;
  $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout";
  mysql_query($q, $this->connection);
  $this->calcNumActiveUsers();
}

/* removeInactiveGuests */
function removeInactiveGuests(){
  if(!TRACK_VISITORS) return;
  $timeout = time()-GUEST_TIMEOUT*60;
  $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout";
  mysql_query($q, $this->connection);
  $this->calcNumActiveGuests();
}

function query($query){
  return mysql_query($query, $this->connection);
}
};
$database = new MySQLDB;
?>

A: It doesn't show because you're checking if the class is non-existent, which it is, because it's complaining about it being redeclared (re-created).

*

*Change all occurrences of include/require to include_once/require_once.

That will make it so files are only included once within a request, meaning the class isn't re-declared.

A: At the page top add:
if(!class_exists('MySQLDB')== true){
require_once($site_root ."/loginfinal/nav_top.php");}
with $site_root = $_SERVER['DOCUMENT_ROOT'];
So the problem solved and its look like
<?php $site_root = $_SERVER['DOCUMENT_ROOT'];
if(!class_exists('MySQLDB')== true){
require_once($site_root ."/loginfinal/nav_top.php");}
?>

Thank you all


text:
Q: Why am I receiving an error on  ? the error is (Uncaught SyntaxError: Unexpected end of input) Basically, I am trying to create a shipping fulfillment program but i am getting an error that i can't debug myself. Thanks everyone.
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
        <script type="text/javascript">
            var totalPrice = 0;
            var totalVolume = 0;
            var totalItem = 0;
            var numTrucks = 0;
            var productArray = ["LT","ST","DC","LC","PR","SP","SW"]; // 0 1 2 3 4 5 6
            var shippingvolumeArray = ["5.5","3","3.25","2","2.5","0.5","0.25"];
            var unitpriceArray = [1000,600,650,800,375,350,275];
            var productCode = Number(prompt("enter product code:"));
            var Quantity = prompt("enter quantity");

            do {
                var productCode = prompt("enter product code:");
                var Quantity = prompt("enter quantity:");
                for (var i = 0; i<= productArray.length; i++) {
                    if (productCode == productArray[i]) {
                        totalPrice = totalPrice + unitpriceArray[i] * Quantity;
                        totalVolume = totalVolume + shippingvolumeArray[i] + Quantity;
                        totalItem = totalItem + Quantity;
                    }
                }
                document.write(totalPrice);
            }
        </script>
    </body>
</html>

A: Your do loop is not closed, while part is missing there. It should be:
do {
  var productCode = prompt("enter product code:");
  var Quantity = prompt("enter quantity:");
  for (var i = 0; i<= productArray.length; i++) {
    if (productCode == productArray[i]) {
      totalPrice = totalPrice + unitpriceArray[i] * Quantity;
      totalVolume = totalVolume + shippingvolumeArray[i] + Quantity;
      totalItem = totalItem + Quantity;
    }
  }
  document.write(totalPrice);
} while (something);


text:
Q: Why do I get two UberPool products in the APIs? I get two UberPool products in the following APIs:
api.uber.com/v1/estimates/time
api.uber.com/v1/estimates/price
api.uber.com/v1/products

Why do I get two products? How are they different?
Example response:
Url:
api.uber.com/v1/estimates/price

Response:
{
  "prices": [
    {
      "localized_display_name": "uberPOOL",
      "high_estimate": 33,
      "minimum": null,
      "duration": 0,
      "estimate": "₹32.50",
      "distance": 0,
      "display_name": "uberPOOL",
      "product_id": "e0178e76-b13f-4ae6-9f72-6acadbb450c5",
      "low_estimate": 32,
      "surge_multiplier": 1,
      "currency_code": "INR"
    },
    {
      "localized_display_name": "uberPOOL",
      "high_estimate": 51,
      "minimum": null,
      "duration": 0,
      "estimate": "Unavailable",
      "distance": 0,
      "display_name": "uberPOOL",
      "product_id": "f855a84b-a0ec-40d8-a455-fb0d2db58089",
      "low_estimate": 50,
      "surge_multiplier": 1,
      "currency_code": "INR"
    },
    {
      "localized_display_name": "uberGO",
      "high_estimate": 50,
      "minimum": 50,
      "duration": 0,
      "estimate": "₹50",
      "distance": 0,
      "display_name": "uberGO",
      "product_id": "18ba4578-b11b-49a6-a992-a132f540b027",
      "low_estimate": 50,
      "surge_multiplier": 1,
      "currency_code": "INR"
    }
    ....
  ]
}

A: TL;DR Uber sometimes offers many products in a given location, and they're all returned from those two endpoints.
To expound on that... according to the docs, this is normal:

The Products endpoint returns information about the Uber products
  offered at a given location. The response includes the display name
  and other details about each product, and lists the products in the
  proper display order.
Some products, such as uberEATS, are not returned by this endpoint.
  We'll soon be making uberPOOL available in this endpoint.

Particularly: We'll soon be making uberPOOL available in this endpoint. It seems that time has come.
The same goes for the estimates endpoint.

The Price Estimates endpoint returns an estimated price range for each
  product offered at a given location.

How are they different?

Uber offers different types of services in different countries.
UberGo is a cheaper version of UberX that seems to be specific to India.
UberPool is fairly straight forward in that it's a carpooling service offered to those who wish to split the fare with others that are heading in the same destination.
Since services vary by location, it's best to research them individually when constructing a service that's consuming the Uber API.

A: Thank you for the report. This is a known issue and we're working on a fix. In the meantime, you can use either uberPOOL product that is surfaced.


text:
Q: Equivalence involving diagonalization of block matrix Given $T^\top L T = diag(A, B, C)$ being a block diagonalization with

*

*$L$ symmetric

*$A,B$ positive definite (p.d.)

*$T = \left( \begin{array}{ccc}I & 0 & T_2 \\ T_1 & I & T_3 \\ 0 & 0 & I\end{array}\right)$, where $T_2, T_3$ are not quadratic and we don't know whether $T_1$  is regular.

I read in a paper that $L$ is p.d. iff $C$ is p.d. I know that if $L$ is p.d. and $T$ is regular, then also $T^\top L T$ is p.d. and thus every sub matrix of $T^\top L T$, therefore also $C$.

*

*Why does the converse hold?

*Why is $T$ regular?

A: $T$ is a block triangular matrix:
$$
T = \left( \begin{array}{cc|c}I & 0 & T_2 \\ T_1 & I & T_3 \\ \hline0 & 0 & I\end{array}\right).
$$
It is invertible if and only if its two diagonal blocks, $\pmatrix{I & 0\\ T_1 & I}$ and $I$, are invertible. Yet this is trivial. Since $T$ is invertible, $L=(T^{-1})^\top\operatorname{diag}(A,B,C)\,T^{-1}$. If $C$ is p.d., $\operatorname{diag}(A,B,C)$ is also p.d. and by Sylvester's law of inertia, $L$ is p.d..


text:
Q: Free sources to learn Field theory. I want to learn all the theories that are required to learn Differential Algebra. One of them is Field theory. I wonder if there are any free credible sources on the internet about this field where I could learn from scratch? What I found so far are basically notes and they don't seem to give a deep insight into Field theory.

A: As far as I know, differentiel algebra relies heavily on Galois theory. In order to understand this, you need to know group theory and field theory first. A good reference is Abstract Alegbra by Dummit & Foote which also is about Galois theory. As for notes on Galois theory, those of J.S. Milne are really great and freely avalaible on internet.


text:
Q: randomise array html5 java script

    <link rel="stylesheet" type="text/css" href="css/style.css" />

    <title>Street</title>

    <audio id="Mp3Me" autoplay autobuffer controls>
        <source src="au1.mp3">
        <source src="au1.ogg">
    </audio>

    <canvas class="canvas" id="can" width="640" height="350" style=" border:1px solid #6F2E0D; ">
    </canvas>

    <input type="button" value="PLAY"  onclick="play()">
    <audio id="audio" src="door.mp3" ></audio>

The above code works with thanks to stack overflow.
Basically at the moment this code displays images in sequence non randomly, it uses the array to fetch them, and show them. The code then regulates the speed of the image display. There is also a sound player, and a button with a sound.
I managed after some considerable searching to animate a simple sequence of png files. However I have been trying to ad start stop button and a math random function (preferably the music on-click would start everything going).
I want to add a random function to the array,so that it displays images randomly.  however the best I could do was, not to brake the code, or to get is to speed up the animation. Can some one please modify my code to add these functions or please point me to some place that would help.
The randomized array would be really useful.

A: (there was a mistake, updated)
For example,
var array = [1,2,3,4,5]
for(i=0; i<array.length;i++){
    var dist = Math.floor( Math.random() * array.length )
    var swp = array[i]
    array[i] = array[dist]
    array[dist] = swp
}
console.log(array) //=> shuffled

A: Demo: http://jsfiddle.net/techsin/dtz0yj4y/
Code
function shuffle (arr) {
   arr.forEach(function(e,i){
       var rand = ~~(Math.random()*(arr.length-1));
       arr[i] = arr[rand];
       arr[rand] = e;
   });
}

var myArr = [1,2,3,4,5];
shuffle(myArr); //myArr is now shuffled!

Example...


text:
Q: GIT is not installing in OEPE 11.1.1.8.0 How to upgrade Git on eclipse/OEPE on which it is not supported and I don't want to use juno or kepler. kindly help out on the issue
 I have used url  http://download.eclipse.org/egit/updates to install git on eclipse , it is giving error
Cannot complete the install because one or more required items could not be found.
  Software being installed: Eclipse Git Team Provider 3.4.1.201406201815-r (org.eclipse.egit.feature.group 3.4.1.201406201815-r)
  Missing requirement: Git Team Provider UI 3.4.1.201406201815-r (org.eclipse.egit.ui 3.4.1.201406201815-r) requires 'bundle

A: When going to install new software and giving following URIs and mark these as checked
after fetching complete. Git libraries are coming and I am able to install git on eclipse indego
http://download.eclipse.org/releases/indigo/201106220900
http://download.eclipse.org/releases/indigo


text:
Q: Creating a Secure File Hosting Server for PDFs I'm working to develop a website that allows clients to log in and see various PDFs saved on the server.  These PDFs will be unique to the client and should not be accessible by someone who is not logged in.  Getting the files onto the server shouldn't be an issue, I'm just not sure on how to serve them to end users.
I've implemented this kind of thing with data from SQL servers being served instead of files, so I'm not entirely sure what the most effective way to go about this.
The website is on a LAMP and my minimal experience is in PHP (but if a framework or other language would make this easier, I can learn it).
I'm probably in over my head but I usually am, so any input would be great.

A: Put the files outside of the webroot. Then using PHP pass the file though a script. That way no one can link to the file directly and bypass your controls. (Naturally make sure the script that does this only after verifying the user has permission to retrieve that file).
Sample PHP:
<?php
    session_start();
    if (!isset($_SESSION['authenticated'])) {
        exit;
    }
    $file = '/path/to/file/outside/www/secret.pdf';

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
?>

A: The easy way is to give these files long random filenames (say, 20 random characters). Technically they will be accessible by anyone, but it will not be possible to guess the URL, so only authorized people will have access.
Alternatively John Conde already outlined a way to serve a file from a PHP script. It will incur a small performance penalty, but will be as secure as your code is. The only thing I can add is that if you cannot place them outside webroot, then you might be able to use .htaccess to prevent people from accessing the files directly.

A: John posted the primary correct way of doing it, so I'm adding the (probably inferior) alternative:  Serve it from the database.  Just have a BLOB column for the PDF, and read/store the file data from the database.  You'll end up with a quite large table, but it will work.  Serving it requires setting the same header()s as John posted, you just send off the data from the DB instead of from the file.
This has the advantage of not having to ensure you don't have filename collisions, etc.


text:
Q: Anomaly with VBA and Conditional Formatting - Excel Bug? I have an issue in Excel where conditional formatting produces different results if a subset of the characters in the cell have a different colour, depending on whether

*

*the colour was applied with manual editing or using VBA

*if applied with VBA, whether the range of coloured characters includes the first character in the cell

I am using Excel in Office 365 on Windows 10, both fully updated as of today.
In the screenshot below cells A1:A6 have the conditional formatting rule
=NOT(ISBLANK(B1))

In cells A2 and A3 I set first three characters to red by editing manually. In A3 the first three characters remain red when conditional formatting is triggered.
In cell A4 I set the first three characters to red text using the macro
Sub RedFirst()
    ActiveCell.Characters(1, 3).Font.Color = vbRed
End Sub

Instead of getting the same result as A3 when conditional formatting is triggered, the first three characters turn green (the conditional format) instead of remaining red, and the rest of the text remains black instead of being green, although all the text is underlined from the conditional formatting.
In cell A5 I set the second and third characters to red text using the macro
Sub RedNext()
    ActiveCell.Characters(2, 2).Font.Color = vbRed
End Sub

Now, the characters whose colour was set with the macro remain red when conditional formatting is triggered, the same as when I change the text colour manually.
Cell A6 shows the result of conditional formatting without having applied a different colour to any text.
I think A3 and A4 should look the same and changing the text colour manually or using VBA shouldn't make a difference. I have tried different approaches for changing the text colour of the first n characters with VBA but always get the same (odd) result.
Is there a way to set the colour of the first n characters with VBA without getting the odd conditional formatting result? Or is this really how it should work? To me it looks like a program bug that needs to be fixed.


text:
Q: Proper definition of addition and multiplication I recently started to study maths at university and in the analysis course we started, as usual, by looking at the axioms of $\mathbb R$ as a field. I think, I've understood the underlying intuition of these axioms quite well, but one question remained open for me:
How do we define, what we do when we add two numbers, i.e. how to really calculate the result. Is the intuitive addition the only interesting function from $\mathbb R^2$ to $\mathbb R$ which satisfies these axioms? Is this question even relevant?
I thought, I could give it a try, and made the following rules for addition and multiplication (which are more or less accurate):
(1) If $m,n\in\mathbb N_0$, then there exists to sets $E,F$ with cardinality $m$ and $n$ respectively for which $E\cap F=\{\}$. Then:
$$
m+n:=|E\cup F|
$$
Now define the inverses.
(2) Now either define
$$
mn:=|\{(e,f):e\in E,\space f\in F\}|
$$
or
$$
mn:=\underbrace{m+m+...+m}_{n}
$$
Then define the inverses.
From this we can extend the addition to the rationals by:
$$
\frac ab +\frac cd:=\frac{ad+bc}{bd}
$$
And even to the reals with cantors limit construction of $\mathbb R$.
The principle that I don't fully understand, is that we never seem to define our proper addition and multiplication. It seems to be always implicit what we mean by $+$ and $*$. How to explain this?

A: If you introduce $\mathbb R$ axiomatically, there is no urge to define $+$ or $\cdot$ or $42$ in a concrete fashion. You may take any other set than the "true" real numbers and any other operations than the "true" addition and multiplicatioan - as long as your choices still make the axioms of a complete ordered field hold, you can validly claim that the set you have in mind is "the" set of real numbers and that the operations you have in mind are "the" addition and multiplication of real numbers. The good thing is: Whenever you need want to communicate a fact about (your) real numbers to another mathematician, you must express numbers in a ways he/she is bound to understand correctly, such as

*

*$0$ and $1$ for the neutral elements of addition/multiplication,

*$42$ as the real number obtained from $(1+1)\cdot(1+1+1)\cdot(1+(1+1)\cdot(1+1+1))$,

*$\sqrt 2$ as the unique real number $w$ that has the property $w\cdot w=1+1$ and for which there exists real $u$ with $u\cdot u=w$,

and so on.

A: $\mathbb{R}$ is up to isomorphism the only ordered field with the supremum property, so we don't really need to know the definition of $+$ and $*$ to work with the arithmetic of $\mathbb{R}$.
Now, what we do want to know is whether such an objetc exists. To do so, we have to define what a real number is, what $+$, $*$ and $<$ are, to prove that there are inverses and so on.
There are several problems with your definitions:
-You implicitely assume that there are elements in $\mathbb{R}$ with which we can count the number of elements in a finite set: who are they?
-You implicitely assume that there are inverses for the additive law (for natural integers): who are they?
-You seem forget to say how to add whole integers that are not positive
-You implicitely assume there are inverses for the multiplicative law (for natural integers): who are they? (what is $\frac{1}{n}$?)
-etc...
There are many things to do in order to define theses laws, many proofs of existence. Defining the field of real numbers is more complicated and longer than just doing "elementary" real analysis and arithmetic. That is why we often rely on an axiomatic background such as the distributivity of $*$ over $+$ and other rules, and we forget about the rest.
If you are interested in the subject, you can learn about the construction of sets of numbers in mathematics. Discovering this can be quite a great experience.
My advice would be to start with the construction of $\mathbb{Z}$ using $\mathbb{N}$ (easy), then that of $\mathbb{Q}$ using $\mathbb{Z}$ (similar), then that of $\mathbb{R}$ using $\mathbb{Q}$ (more difficult and longer), then that of $\mathbb{N}$ using the axioms of set theory (more difficult and subtler).


text:
Q: Find the value of the limit $b_n = n - \sqrt{n^2 + 2n}$ if $(1/n)\rightarrow 0$. Consider the sequence given by $b_n = n - \sqrt{n^2 + 2n}$. Taking $(1/n)\rightarrow 0$ as given, and using both the Algebraic Limit Theorem, and the fact that if $(x_n)\rightarrow x$ then $(\sqrt{x_n})\rightarrow \sqrt{x}$, show $\lim b_n$ exists and find the value of the limit.
Well, because $(1/n) \rightarrow 0$, the sequence $(n)\rightarrow \infty$. Consider $n=\sqrt{n^2}>\sqrt{n^2 - 2n}$ which implies $n>n-\sqrt{n^2 - 2n}>0 $. So if $(n)\rightarrow \infty$ then so does $(n-\sqrt{n^2 - 2n})\rightarrow \infty$ $\blacksquare$
But after writing I wonder if it is okay for me to assume that $n\in \mathbb{N}$. If $n\notin \mathbb{N}$ then my first statement of $(n)\rightarrow \infty$ is wrong because $n$ could also diverge to $-\infty$.

A: Hint: Multiply numerator and denominator by $$n+\sqrt{n^2+2n}$$

A: Set $x=\dfrac 1n\;(x>0)$. You want the limit, as $x\to 0$, of
$$\frac1x-\sqrt{\frac 1{x^2}+\frac 2x}=\frac{1-\sqrt{1+2x}}{x}=-\frac{\sqrt{1+2x}-\sqrt 1}{x} $$
This is the opposite of the rate of variation, from $0$, of the function $\sqrt{1+2x}$. Can you end the computation?

A: Observe that $n - (n^2 + 2n)^{\frac{1}{2}}=n - n\left( 1 + \frac{2}{n} \right)^{\frac{1}{2}}$.
By the binomial theorem, it follows that
$$
\left( 1 + \frac{2}{n} \right)^{\frac{1}{2}}=1+\frac{1}{n}-\frac{1}{2n^2}+o(n^{-2})
$$
So
$$
n - n\left( 1 + \frac{2}{n} \right)^{\frac{1}{2}}=n - \left(n + 1 - \frac{1}{2n} + o(n^{-1}) \right)=-1+\frac{1}{2n}+o(n^{-1})
$$
Therefore, $\lim n - (n^2 + 2n)^{\frac{1}{2}} = -1$.


text:
Q: Using Facebook PHP SDK 4 but there's no session being stored I've never used the Facebook SDK 4, and I'm had a look at a lot of answers on here to no success.
I'm trying to use the facebook login part of the api, but everytime i re-direct back from facebook there are's no session stored.. here's the code:
<?php
// I am using autoload just to make sure it was including the requested classes, it makes no difference if i include them separately the outcome is the same.

function __autoload($classname) {
    $filename = "../Facebook/". end(explode("\\",$classname)) .".php";
    include_once($filename);
}

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;

// start session
session_start();

// init app with app id and secret -
FacebookSession::setDefaultApplication( '****','****' );

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://dev.mydomain.co.uk/fb/index.php' );

try {
  $session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
  // When Facebook returns an error
} catch(\Exception $ex) {
  // When validation fails or other local issues
}
if ($session) {
  // Logged in
    print('loggedin');
} else {
    print('no session');
    $loginUrl = $helper->getLoginUrl();
    ?>
    <a href="<?=$loginUrl?>">login
    <?php
}

I've replaced the app id and secret, and the redirect uri is correct but ive just replaced the domain here.
It returns back to my login page, just always prints "no session". So it looks like $session = $helper->getSessionFromRedirect(); is not doing what i need it to.
I got this code from the facebook developers site.
Things I've tried:

*

*Including the class files separately instead of autoload

*Moved the whole thing into a seperate directory with out anything else in the index.php file

*Removed my .htaccess file to make sure it's not something interfering with the GET requests.

*I've also tried a few different tutorials i.e http://metah.ch/blog/2014/05/facebook-sdk-4-0-0-for-php-a-working-sample-to-get-started/ using their code exactly (but replacing app_id, app_sec, and the url bits) - but i still return no session

I'm at a bit of a loss, so if someone has experience with this it would be helpful

A: Try this one, I had the same problem as you:
    http://www.codeproject.com/Tips/777252/Integrating-Facebook-Account-into-a-Log-in-Session


text:
Q: Always getting initial value of other local state with React Hooks So I've been trying out React Hooks for a change, but there's something I haven't been able to understand, and it's using multiple states in a functional component and interacting between them. Say I want to get the percentage of the window's scroll position and its height, & then display it like so:
import React, { useState, useLayoutEffect } from 'react'

const Page = () => {
  const [scrollPos, setScrollPos] = useState(window.pageYOffset || document.documentElement.scrollTop)
  const [windowSize, setWindowSize] = useState(window.innerHeight)
  const [percent, setPercent] = useState(0)

  useLayoutEffect(() => {
    const handleScroll = () => {
      const y = window.pageYOffset || document.documentElement.scrollTop
      setScrollPos(y)
      // windowSize is always its initial value, not its latest
      console.log("handleScroll: " + y + " / " + windowSize + " = " + y / windowSize)
      setPercent(y / windowSize)
    }
    window.addEventListener('scroll', handleScroll)

    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  useLayoutEffect(() => {
    const handleResize = () => {
      const height = window.innerHeight
      setWindowSize(height)
      // scrollPos is always its initial value, not its latest
      console.log("handleScroll: " + scrollPos + " / " + height + " = " + scrollPos / height)
      setPercent(scrollPos / windowSize)
    }
    window.addEventListener('resize', handleResize)

    return () => window.removeEventListener('resize', handleResize)
  }, [])

  return (

      {/* Calculates percentage correctly upon scrolling and resizing */}

{scrollPos} / {windowSize} = {scrollPos / windowSize}

      {/* Incorrect once I scroll after resizing and vice versa */}

!= {percent}

  )
}

export default Page

If I run this, the console won't display the latest values of scrollPos and windowSize, but instead the initial ones; while rendering them does show their latest values. And percent gets mixed up with that as it grabs the initial value of one of them upon resizing or scrolling the window.
I think this is one of those things that's caused because of it being asynchronous, but it'd be nice to get a clearer answer on this. How would one be able to work with multiple "local" states, or is it just better to make one single merged state for cases like these?


text:
Q: Exec Format error of a 64-bit executable on a 64-bit machine I'm currently working on an implementation of MD5 just because I'm curious and want to get a better understanding of how hashing works. I have 1 file with all the code in it, called easy_md5.c and I'm compiling it with the following Makefile:
easy_md5: easy_md5.c
    gcc -c easy_md5.c -o easy_md5

clean:
    -rm -f easy_md5.o
    -rm -f easy_md5

I ran chmod +x easy_md5 on the executable to give it permission, and yet I'm getting the following error when I try to run it:
[gabe@void easy_md5]$ ./easy_md5 hello
bash: ./easy_md5: cannot execute binary file: Exec format error

Running file easy_md5 shows the following:
easy_md5: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped

and running arch confirms my machine has x86-64 architecture. Since its a 64-bit executable, there's no reason it should throw a format error when I try to run it on my 64-bit machine. What is going wrong?

A: You didn't create an executable at all.  The -c option tells gcc to compile only, and output a relocatable object file.  You'd normally name that file easy_md5.o and use it when linking, but the -o option forced it to be named easy_md5 which looks like an executable name even though it isn't.
To compile and link in one step, just drop the -c: gcc easy_md5.c -o easy_md5.
There were a couple other hints:

I ran chmod +x easy_md5 on the executable

When you actually create an executable, this isn't necessary.  gcc sets execute permissions on it for you.

Running file easy_md5 shows the following:
easy_md5: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped

This indicates an object file.  An actual executable is reported as something like
a.out: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=7108d6b0e7767b20e8db974561938d3bfcbbe12a, for GNU/Linux 3.2.0, not stripped


text:
Q: What does the function StartJava do? In Mathematica's autocomplete list, the function StartJava appeared.
I searched the mathematica's reference site and found that the function was undocumented. What does it do?

A: Thanks to @J.M., it was discovered the StartJava was a deprecated function, replaced by InstallJava, which is used to launch the java runtime in Mathematica.


text:
Q: Not displaying day of the week using calendar and date instances I have created new SimpleDateFormat object which parses the given string as date object. The date format is as below:
SimpleDateFormat simpledateFormat = new SimpleDateFormat("dd-MM-yyyy");

And I am setting this date to calendar instance as below:
Date date = sampledateFormat.parse("01-08-2013");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

Now I am getting the day of the day of the week from this calendar. It is giving wrong value.
System.out.println(calendar.DAY_OF_WEEK);

The output it is giving is 7 i.e. Saturday but the expected value is 5 i.e. Thursday. Whats the problem?

A: You should print
calendar.get(Calendar.DAY_OF_WEEK);

The Calendar class has DAY_OF_WEEK as integer constant (with value 7) which should be used in conjunction with the Calendar.get(int) method. DAY_OF_WEEK is a calendar field, and all these constant fields are used to get() different values from the calendar instance. Their value is irrelevant.

A: tl;dr
LocalDate.parse(    // Parse the input string by specified formatting pattern to get a date-only `LocalDate` object.
    "01-08-2013" ,
    DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.getDayOfWeek()    // Get a `DayOfWeek` enum object. This is *not* a mere String.
.getValue()        // Ask the `DayOfWeek` object for its number, 1-7 for Monday-Sunday per ISO 8601 standard.

4

java.time
The modern approach uses the java.time  classes that supplanted the troublesome old legacy date-time classes such as SimpleDateFormat and Date and Calendar.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;

Parse the input string.
LocalDate ld = LocalDate.parse( "01-08-2013" , f ) ;

ld.toString(): 2013-08-01

Interrogate for the day-of-week. Get a DayOfWeek enum object, one of seven pre-defined objects, for Monday-Sunday.
DayOfWeek dow = ld.getDayOfWeek() ;

dow.toString(): THURSDAY

You can ask that DayOfWeek object for a localized name and for a number 1-7 for Monday-Sunday per the ISO 8601 standard.
int dowNumber = dow.getValue() ;

4

String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;  // Or Locale.US, Locale.ITALY, etc.

jeudi

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: How to retrieve album images using Facebook php SDK? I am trying to retrieve images from Facebook album using PHP SDK.
$user_profile = $facebook->api('/me');
$user_id = $user_profile['id'];
$albums = $facebook->api('/me/albums');
print_r($albums);
foreach($albums['data'] as $album)
{
    $album_id = $album['id'];
    echo $album_id;
    $photos = $facebook->api('/{$album_id}/photos');

}
foreach($photos['data'] as $photo)
    {
        echo "","
";
    }

But it retrieves an empty array.When I tried to print a certain i, in the first loop,I found that code in that loop is not executed. So what wrong would I be doing?

A: You can try like this, see below
$albums = $facebook->api('/me/photos');

i think It should be like that.


text:
Q: Is there a way to print the amount in XSL 1.0 template with for loop for below scenario? I have requirement or logic where the below tag needs to printed with a difference of 100000 with a for loop logic. Please help in XSL 1.0
Scenario 1
<Amt>
430000
</Amt>

Output required
<Amt>100000</Amt>
<Amt>100000</Amt>
<Amt>100000</Amt>
<Amt>100000</Amt>
<Amt>30000</Amt>

Scenario 2
<Amt>
299999
</Amt>

Output required
<Amt>100000</Amt>
<Amt>100000</Amt>
<Amt>99999</Amt>

Scenario 3
<Amt>
23000
</Amt>

Output required
<Amt>23000</Amt>

A: There is no such thing as a "for loop" in XSLT 1.0. The result you want can be obtained by calling a recursive named template:
<xsl:template name="split-to-lakhs">
    <xsl:param name="amt"/>
    <xsl:choose>
        <xsl:when test="$amt > 100000">
            <Amt>100000</Amt>
            <!-- recursive call -->
            <xsl:call-template name="split-to-lakhs">
                <xsl:with-param name="amt" select="$amt - 100000"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <Amt>
                <xsl:value-of select="$amt"/>
            </Amt>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Demo: https://xsltfiddle.liberty-development.net/nbiE1aD


text:
Q: Call to a member function prepare() on a non-object with PDO  I have a function which uses:
require_once("connect.php");

function get_username($uid){
  $stmt = $pdo->prepare("SELECT username FROM users WHERE uid= ?");

try {
    $stmt->execute(array($uid));
} catch (PDOException $e) {
    echo $e -> getMessage(); exit;
}

      $row = $stmt->fetch();
      return($row['username']);
}

$id = 1;
echo get_username($id);

But it says :
Call to a member function prepare() on a non-object

I'm a bit confused on what this means i have wrong, i'm wondering if its because I am using it in a function ?
EDIT:
My Connect script¬
$dsn = 'mysql:dbname=test_db;host=127.0.0.1';
$user = 'test_user';
$password = 'test_pass';

try {
    $pdo = new PDO($dsn, $user, $password);

} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    exit;
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

error_reporting(E_ALL);
session_start();

A: Yes, it's because you're using it in a function. $pdo is in the global scope, and is not in the scope of the function.
You either need to access the $pdo global by referencing it in the function as a global variable:
function get_username($uid){
  global $pdo;
  $stmt = $pdo->prepare("SELECT username FROM users WHERE uid= ?");

Or pass $pdo in when you call the function
function get_username($uid, $pdo){

...
...
}

get_username( $id, $pdo);