text:
Q: How to white label my website in php I have a website that follows the following structure:

*

*www.example.com/city1

*www.example.com/city2

*...

Programmatically we change the logo which is hard-coded in a specific config file for city 1, city 2,... They are files in a folder structure like /cities/city1 or /cities/city2.
The colors can be changed by the admin of the city itself via the user interface, and it is saved in the database in a local_settings table where there's a column for bg_color.
However, I want to rework my entire system to white label the entire cities layout. But I was wondering how to go about this, I couldn't find much information googling this subject.
Should I:

*

*Keep on creating a config file for each city? And store each of the specific settings in there, where php reads and writes to the file?

*Save everything in the database? How do I structure this properly for scalability?
Extra question: imagine if a city wants its own footer on its sub-site, (which requires completely custom new HTML and CSS code), how do I go about this? Is it good practice to create a specific new footer.html file and put it in its specific /cities/ folder? And load it if it exists, otherwise load the general one?

A: Its been a few years now, but the last PHP system I developed did something like that.  We offered custom domain names, rather than directories, but the principal is the same.
It was a template driven site.  When a page was requested, it'd extract the domain name from the request.  It would look that up in a db table, and obtain the metadata for that site (site id, name, title, company, etc) much like you are doing.  For the templates, if we needed to load abc.template, it'd look first for 123/abc.template (if 123 was the site id), and use that if it existed, otherwise it would use the default abc.template.
The project ran successfully for over a decade and tracked billions of dollars in transactions. So, it worked well!
So I'd say you are on the right track.


text:
Q: How to get woocommerce product collection in template file I want to show Woocommerce products on my custom template page How can i get product collection in that page,Please kindly give some suggestions how do i proceed to complete it
thanks

A: I found like this.
For More : https://docs.woocommerce.com/document/sample-products-loop/
https://www.philowen.co/blog/show-latest-woocommerce-products-in-your-template/
<?php
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12
            );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();
                wc_get_template_part( 'content', 'product' );
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    ?>

Just try it. i hope is useful

A: You didn't provide much detail here, but you could also try to add them as a list:
<?php
$params = array('posts_per_page' => 5, 'post_type' => 'product');
$wc_query = new WP_Query($params);
?>

     <?php if ($wc_query->have_posts()) : ?>
     <?php while ($wc_query->have_posts()) :
                $wc_query->the_post(); ?>

               <a href="<?php the_permalink(); ?>">
               <?php the_title(); ?>

          <?php the_post_thumbnail(); ?>
          <?php the_excerpt(); ?>

     <?php endwhile; ?>
     <?php wp_reset_postdata(); ?>
     <?php else:  ?>

          <?php _e( 'No Products' ); ?>

     <?php endif; ?>

More details would allow us to help you more specifically.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using python regex to find repeated values after a header If I have a string that looks something like:
s = """
...
Random Stuff
...
HEADER
a 1
a 3
# random amount of rows
a 17
RANDOM_NEW_HEADER
a 200
a 300
...
More random stuff
...
"""

Is there a clean way to use regex (in Python)  to find all instances of a \d* after HEADER, but before the pattern is broken by SOMETHING_TOTALLY_DIFFERENT? I thought about something like:
import re
pattern = r'HEADER(?:\na \d*)*\na (\d*)'

print re.findall(pattern, s)

Unfortunately, regex doesn't find overlapping matches. If there's no sensible way to do this with regex, I'm okay with anything faster than writing my own for loop to extract this data.
(TL;DR -- There's a distinct header, followed by a pattern that repeats. I want to catch each instance of that pattern, as long as there isn't a break in the repetition.)
EDIT:
To clarify, I don't necessarily know what SOMETHING_TOTALLY_DIFFERENT will be, only that it won't match a \d+. I want to collect all consecutive instances of \na \d+ that follow HEADER\n.

A: How about a simple loop?
import re

e = re.compile(r'(a\s+\d+)')

header = 'whatever your header field is'
breaker = 'something_different'

breaker_reached = False
header_reached = False

results = []

with open('yourfile.txt') as f:
    for line in f:
        if line == header:
            # skip processing lines unless we reach the header
            header_reached = True
            continue
        if header_reached:
            i = e.match(line)
            if i and not breaker_reached:
               results.append(i.groups()[0])
            else:
               # There was no match, check if we reached the breaker
               if line == breaker:
                   breaker_reached = True

A: Not completly sure where you want the regex to stop please clarify

'((a \d*)\s){1,}'

A: import re

sentinel_begin = 'HEADER'
sentinel_end = 'SOMETHING_TOTALLY_DIFFERENT'
re.findall(r'(a \d*)', s[s.find(sentinel_begin): s.find(sentinel_end)])


text:
Q: Reading only the last 10 lines of a text file "tail" (Jquery/Ajax/javascript or whatever) I've been searching for solutions here for a long time now, and i haven't been able to find any so far
what i need is a way to read the last 10 or so lines of a text file, which continually updates every second
i've found some possible codes in php, but then i wont be able to update the file every second.
how do i get only the last 10 lines of a text file using some sort of javascript?

A: Try using array_slice, which will return a part of an array. In this case you want it to return the last 15 lines of the array,
$filearr = file("filename");
$lastlines = array_slice($filearr,-10);

You can change -10 (-10,-15 any value you want).
Hope it works!

A: Hmmm... maybe so, for large files:
$fileName = '[path_to_file]';
$file = new \SplFileObject($fileName);
$file->seek($file->getSize());

$lines = $file->key() - 1;

$file->setFlags(\SplFileObject::READ_CSV);

$counter = 0;
$records = 100;
$seek = $lines - $records;

$file->seek($seek);

$return = array();
while ($counter++ < $records) {
    try {
        $line = $file->fgets();
        $return[] = $line;
    } catch (\Exception $e) {
    }
}

A: Didn't find the correct answer here, so i started a new question where i'm more specific with what i want
Reading ONLY the last 50 lines of a large text file


text:
Q: VBA - Copy and paste the data from the 4th column I tried to use my other similar VBA code but I don't think I understand what I'm trying to replace for the range. In this code, I am trying to copy the data in the Repeating Items sheet in the fourth column with the cell value of 12, then paste it to the last worksheet.
' Repeating items worksheet
    Worksheets("Repeating Items").Select

    ActiveSheet.ShowAllData

    b = Worksheets("Repeating Items").Cells(Rows.Count, 1).End(xlUp).Row

    ' Filters the data where column 2 equals to 12 to x. ** this is where the error starts
    ActiveSheet.Range(Cells(1, 1), Cells(b, 4)).Autofilter Field:=4, Criteria1:="12", Operator:=xlFilterValues

    ' Selects only the filtered cells and copy
    Range(Cells(2, 1), Cells(b, 4)).SpecialCells(xlCellTypeVisible).Select
    Selection.Copy

    ThisWorkbook.Worksheets(ThisWorkbook.Sheets.Count).Select
    ActiveSheet.Paste Destination:=Cells(Cells(Rows.Count, 1).End(xlUp).Row + 1, 1)

A: Per the Microsoft Documentation, you can just apply the filter to the first row much how you would manually do in excel and it will automatically filter your range. You don't need to quote your number filter FYI (unless the column is Text).
Also, no need to Select anything here. It is just a middle man operator that only slows your code down. Instead, explicitly define your objects (sheets and ranges) and skip right to the action statements (copy/paste).

Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Repeating Items")
Dim ls As Worksheet: Set ls = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Dim lr As Long

lr = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
ws.Range("A1:D1").AutoFilter Field:=4, Criteria1:=12

ws.Range("A2:D" & lr).SpecialCells(xlCellTypeVisible).Copy
ls.Range("A" & ls.Range("A" & ls.Rows.Count).End(xlUp).Row).PasteSpecial xlPasteValues

End Sub


text:
Q: Problem installing neo4j.py I have followed the instructions here and for some reason I am getting the following traceback:
root@ubuntu:~/Downloads/neo4j-python# python setup.py install

Traceback (most recent call last):
  File "setup.py", line 146, in <module>
    main()
  File "setup.py", line 134, in main
    args[attr] = pom[attr]
  File "/home/omer/Downloads/neo4j-python/pom.py", line 58, in __getitem__
    element)
  File "/home/omer/Downloads/neo4j-python/pom.py", line 57, in <lambda>
    return self.pattern.sub(lambda match:self[match.groupdict()['var']],
  File "/home/omer/Downloads/neo4j-python/pom.py", line 54, in __getitem__
    element = self.parent[path]
  File "/home/omer/Downloads/neo4j-python/pom.py", line 91, in __getitem__
    return replacement.get(path, lambda s,x:x)(self, self.__pom[path])
  File "/home/omer/Downloads/neo4j-python/pom.py", line 56, in __getitem__
    raise KeyError(path)
KeyError: 'project.artifactId'

Has anyone encountered this issue? I am running ubuntu 11.04 and python 2.7.1.

A: Found the answer on serverfualt.
See the issue here.


text:
Q: format of do.call statement I am trying to understand how to properly format a combination of lapply, rbind and do.call in a statement and can't get the statement to run properly. I have supplied a simple example function and data that I'm using to try to understand the formatting with. I fully understand that the scenario I've supplied could be ran using a simpler method, the purpose of this is to simply understand the formatting and how to use lapply and rbind on a custom function.
Here's some test data:
facility_id  patient_number  test_result
123          1000            25
123          1000            30
25           1001            12
25           1002            67
25           1010            75
65           1009            8
22           1222            95
22           1223            89

I'm essentially trying to subset the data inside a custom function using a list of facility id values and then want to bind each data table together that results from the custom function.
Here's the code I've used:
facilities_id_list<-c(123, 25)
facility_counts<-function(facilities_id_list){
  facility<-facilities_id_list[[i]]
  subset<-data[facility_id==facility]
}

results <- do.call("rbind", lapply(seq_along(facilities_id_list), function(i) facility_counts)

The result I'm hoping to achieve:
facility_id  patient_number  test_result
123          1000            25
123          1000            30
25           1001            12
25           1002            67
25           1010            75

Why does this not work? Do I need to change the formatting?

A: Instead of using ==, use %in% for direct subsetting
subset(data, facility_id %in% facilities_id_list)

In the OP's code, there are multiple issues - 1) the input argument is facilities_id_list where as in lapply, we are looping over the sequence i., 2) facility_id==facility should be data$facility_id==facility as we are using [ and there is no data binding, 3) We need to specify that we are subsetting with row index as by default without any ,, it is taken as column index in data.frame
 facility_counts<-function(i){
  facility<-facilities_id_list[[i]]
  data[data$facility_id == facility, ]
}
> do.call(rbind, lapply(seq_along(facilities_id_list), facility_counts))
  facility_id patient_number test_result
1         123           1000          25
2         123           1000          30
3          25           1001          12
4          25           1002          67
5          25           1010          75

A: Here's an example of using plain old filter, and then another option of using a custom function with do.call():
library(dplyr)

# data
df <- tibble::tribble(
  ~facility_id, ~patient_number, ~test_result,
  123L,           1000L,          25L,
  123L,           1000L,          30L,
  25L,           1001L,          12L,
  25L,           1002L,          67L,
  25L,           1010L,          75L,
  65L,           1009L,           8L,
  22L,           1222L,          95L,
  22L,           1223L,          89L
)

facilities_id_list<-c(123, 25)

# simplest solution: just using filter
df %>%
  filter(facility_id %in% facilities_id_list)
#> # A tibble: 5 × 3
#>   facility_id patient_number test_result
#>         <int>          <int>       <int>
#> 1         123           1000          25
#> 2         123           1000          30
#> 3          25           1001          12
#> 4          25           1002          67
#> 5          25           1010          75

# using custom function + do.call
custom_filter <- function(data) {
  data %>%
    filter(facility_id %in% facilities_id_list)
}

do.call(custom_filter, list(df))
#> # A tibble: 5 × 3
#>   facility_id patient_number test_result
#>         <int>          <int>       <int>
#> 1         123           1000          25
#> 2         123           1000          30
#> 3          25           1001          12
#> 4          25           1002          67
#> 5          25           1010          75


text:
Q: How can I create a golden master for mvc 4 application I was wondering how to create a golden master approach to start creating some tests for my MVC 4 application.

"Gold master testing refers to capturing the result of a process, and
  then comparing future runs against the saved "gold master" (or known
  good) version to discover unexpected changes." - @brynary

Its a large application with no tests and it will be good to start development with the golden master to ensure the changes we are making to increase the test coverage and hopefully decrease the complexity in the long don't break the application.
I am think about capturing a days worth of real world traffic from the IIS logs and use that to create the golden master however I am not sure the easiest or best way to go about it. There is nothing out of the ordinary on the app lots controllers with post backs etc
I am looking for a way to create a suitable golden master for a MVC 4 application hosted in IIS 7.5.
NOTES
To clarify something in regards to the comments the "golden master" is a test you can run to verify output of the application. It is like journalling your application and being able to run that journal every time you make a change to ensure you have broken anything.

When working with legacy code, it is almost impossible to understand
  it and to write code that will surely exercise all the logical paths
  through the code. For that kind of testing, we would need to
  understand the code, but we do not yet. So we need to take another
  approach.
Instead of trying to figure out what to test, we can test everything,
  a lot of times, so that we end up with a huge amount of output, about
  which we can almost certainly assume that it was produced by
  exercising all parts of our legacy code. It is recommended to run the
  code at least 10,000 (ten thousand) times. We will write a test to run
  it twice as much and save the output.
Patkos Csaba - http://code.tutsplus.com/tutorials/refactoring-legacy-code-part-1-the-golden-master--cms-20331

My question is how do I go about doing this to a MVC application.
Regards

A: Basically you want to compare two large sets of results and control variations, in practice, an integration test. I believe that the real traffic can't exactly give you the control that I think you need it.
Before making any change to the production code, you should do the following:

*

*Create X number of random inputs, always using the same random seed, so you can generate always the same set over and over again. You will probably want a few thousand random inputs.

*Bombard the class or system under test with these random inputs.

*Capture the outputs for each individual random input
When you run it for the first time, record the outputs in a file (or database, etc). From then on, you can start changing your code, run the test and compare the execution output with the original output data you recorded. If they match, keep refactoring, otherwise, revert back your change and you should be back to green.
This doesn't match with your approach. Imagine a scenario in which a user makes a purchase of a certain product, you can not determine the outcome of the transaction, insufficient credit, non-availability of the product, so you cannot trust in your input.
However, what you now need is a way to replicate that data automatically, and the automation of the browser in this case cannot help you much.
You can try a different approach, something like the Lightweight Test Automation Framework or else MvcIntegrationTestFramework which are the most appropriate to your scenario


text:
Q: Specific Range in VBA Excel I have created a pivot table in excel with vba. Now I have to group some different rows.
For Example A1, A6, A19 ...
The information which rows should be grouped are on an own Worksheet where I read from.
When I create an new string which contains for example: groupString = "A1, A5, A90, A103"
and then I use Worksheets("TableTest").Range(groupString).Group I always get an Runtime Error that I cannot group multiple selections.
When I use Worksheets("TableTest").Range("A1, A23").Group it works, but I need the groups which
I read from the other Worksheet. Thanks for helping.
Kind regards

A: Maybe when you use Worksheets("TableTest").Range("A1, A23").Group, A23 falls out of pivot and only A1 is considered.
Range.Group documentation states that range must specify a single cell.
Have you tried grouping cell by cell?
For Each cell in Worksheets("TableTest").Range(groupString).Cells
    cell.Group
Next


text:
Q: Logins through phone app don't count towards enthusiast/fanatic I assumed that logging in through the stack exchange phone app would count towards the Fanatic/Enthusiast badges. Now I actually see my consecutive login days on stackoverflow down to 1 from 91 since I used only the phone app (Android version) for a day. Is this supposed to happen?
Update: The question that I had was answered. However I have just one follow-up question, whether there is any way for me to recover the lost days or is that not possible at all. It makes complete sense that there is no way to distinguish the requests made through API, but still, I cannot anticipate that I would have to ask such a question before I actually find out that my consecutive activity has been lost (meaning consecutive days on the site).

A: It used to be that access through a mobile app would not count towards the badges, see the old answer below.
As of August 2013, mobile app use counts towards the badges, see Last seen not updating when using Android app.

Original answer, December 2012:
Accessing your Stack Exchange data through the API does not count towards your fanatic and enthusiast badge progress.
External applications such as the iPhone app use the API, not direct access to the site. If you use the mobile web interface instead, you are seen to use the site actively and such access is counted towards the badges.
It would be almost impossible to distinguish automated use of the API data from interactive use, so I don't think this will ever change.
As for your update: no, there is no way to recover the days lost.


text:
Q: Simulating power button press to display switch off dialog box I am trying to invoke the switch off dialog box that appears when we press power button. But i want to accomplish this task from an android application or a Junit test case. I will choose the most feasible approach in this case. I have been trying to do this but was not able to succeed. I am trying to use the following five approaches:
First approach:
long eventTime = SystemClock.uptimeMillis(); boolean
                  dispateched = launcherButtonWInst.dispatchKeyEvent(new
                  KeyEvent(eventTime, eventTime, KeyEvent.ACTION_DOWN,
                  KeyEvent.KEYCODE_POWER, 0, 0, 0, 0, 0) );
                  Log.i(LOG_TAG,String.valueOf(dispateched)); boolean
                  dispateched2=launcherButtonWInst.dispatchKeyEvent(new
                  KeyEvent(eventTime+2000, eventTime+2000, KeyEvent.ACTION_UP,
                  KeyEvent.KEYCODE_POWER, 0, 0, 0, 0, 0) );
                  Log.i(LOG_TAG,String.valueOf(dispateched2));

=======================================================
Second apporach:
private void generateKeys() {
        // Obtain the WindowManager system service interface
        IBinder wmbinder = ServiceManager.getService("window");
        Log.d(LOG_TAG, "WindowManager: " + wmbinder);
        IWindowManager wm = IWindowManager.Stub.asInterface(wmbinder);
        keyUpDown(wm, KeyEvent.KEYCODE_POWER);
    }

    private void keyUpDown(IWindowManager wm, int keycode) {
        try {
            Log.d(LOG_TAG, "keyDown: " + keycode);
            wm.injectKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keycode), true);
            Log.d(LOG_TAG, "keyUp: " + keycode);
            wm.injectKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keycode), true);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            Log.e("ERROR!!!!!", e.toString());
            e.printStackTrace();
        }
    }

============================================================
Third approach:
Instrumentation inst = new Instrumentation();
        inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POWER);

======================================================
Fourth approach:
try {
                         long now =SystemClock.uptimeMillis();
                         KeyEvent down = new KeyEvent(now, now,
                         KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POWER, 0);

                         Log.d( LOG_TAG,down.toString() );
                         KeyEvent up = new KeyEvent(now+2000, now+2000,
                         KeyEvent.ACTION_UP, KeyEvent.KEYCODE_POWER, 0);
                         Log.d( LOG_TAG,up.toString() );
                         (IWindowManager.Stub.asInterface(ServiceManager.getService("window"))).injectKeyEvent(down,
                         true);
                         try {
                         Thread.sleep(2000);
                         } catch (InterruptedException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                         }
                         (IWindowManager.Stub.asInterface(ServiceManager.getService("window"))).injectKeyEvent(up,
                         true);
                         } catch (RemoteException e) {
                         Log.d("LOGTAG",
                         "SendKeyEvent exception:"+e.getMessage());

                             }
Fifth approach:
try {
                    Context mContext = getBaseContext();
                    Dialog dialog=new Dialog(mContext);
                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    ShutdownThread.shutdown(mContext, true);

                } catch (Exception e) {
                    Log.e("ERROR!!!", e.toString());
                    e.printStackTrace();
                }

===================================================================
But none of them is working for me. The fifth approach is invoking shutdown() method of ShutdownThread class. But it gives me following error:
07-05 10:18:21.489: W/System.err(709): android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@4104d798 -- permission denied for this window type
07-05 10:18:21.499: W/System.err(709):     at android.view.ViewRootImpl.setView(ViewRootImpl.java:537)
07-05 10:18:21.499: W/System.err(709):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:301)
07-05 10:18:21.499: W/System.err(709):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
07-05 10:18:21.499: W/System.err(709):     at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
07-05 10:18:21.499: W/System.err(709):     at android.app.Dialog.show(Dialog.java:278)
07-05 10:18:21.499: W/System.err(709):     at com.android.internal.app.ShutdownThread.shutdown(ShutdownThread.java:124)
07-05 10:18:21.499: W/System.err(709):     at aexp.keygen.KeyGen$1.onClick(KeyGen.java:47)
07-05 10:18:21.499: W/System.err(709):     at android.view.View.performClick(View.java:3511)
07-05 10:18:21.499: W/System.err(709):     at android.view.View$PerformClick.run(View.java:14105)
07-05 10:18:21.509: W/System.err(709):     at android.os.Handler.handleCallback(Handler.java:605)
07-05 10:18:21.509: W/System.err(709):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-05 10:18:21.509: W/System.err(709):     at android.os.Looper.loop(Looper.java:137)
07-05 10:18:21.509: W/System.err(709):     at android.app.ActivityThread.main(ActivityThread.java:4424)
07-05 10:18:21.509: W/System.err(709):     at java.lang.reflect.Method.invokeNative(Native Method)
07-05 10:18:21.509: W/System.err(709):     at java.lang.reflect.Method.invoke(Method.java:511)
07-05 10:18:21.509: W/System.err(709):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-05 10:18:21.509: W/System.err(709):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-05 10:18:21.509: W/System.err(709):     at dalvik.system.NativeStart.main(Native Method)

Other approaches do not throw any error. I need help to accomplish this task, which ever way it takes even though I have to invoke native methods to accomplish I will do that, but I have to display the switch off UI.
Thanks
Ashwani

A: Other Approach
adb shell input keyevent --longpress KEYCODE_POWER

A: Sixth approach:
$ adb shell input keyevent 26

works!
Seventh approach:
If you want the long press
$ adb shell <<!
> sendevent /dev/input/event5 1 107 1
> sleep 1
> sendevent /dev/input/event5 1 107 0
> exit
> !

You device may use a different input device than /dev/input/event5
Eighth approach
This approach is a bit more clever and uses sendevent or input keyevent depending on API level.
#! /usr/bin/env python

from com.dtmilano.android.adb.adbclient import *

AdbClient(serialno='your-serial-number-here').longPress('POWER')

The advantage here is that this is a generic approach and can be used to send other keys too.
AdbClient is a python implementation of adb and is distributed with AndroidViewClient/culebra.


text:
Q: How Block size varies from Cluster1 to Cluster2, if we use DistCp command? I am processing "DistCp" command to move few critical files form My Cluster1 to Cluster2. These critical files were residing with Blocksize 64MB, before. And now moved to Cluster2 [it got 128MB blocksize).
After the DistCp move, how does the does the critical files performance will increase with new blocksize in Cluster2..performance increase or decreases..???

A: It depends on your files. Hadoop files are supposed to be read sequentially and if your files are big(let's say Gbs or Tbs) it would increase performance if you increase your blocksize, because it would decrease the number of tasks to be performed. Copying with Distcp will not maintain the block properties of your file since block configurations varies from cluster to cluster.


text:
Q: How do I properly run if statements and do while loops with functions? I have 5 programs that run perfectly fine individually, but when I combine them I get error messages and won't build. I have a menu to pick which program to run using if statements. Also a do while loop to repeat the programs. I believe it has something to do with the functions because I haven't had this problem before with simple programs. The program should first ask which program you want to run from the menu. It will run that program, then ask if you want to repeat.
I don't know what to try other than what is now in the program. I did take the do while loop out but still had the issue with the if statements.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main()
{
int choice;
char repeat;
if (repeat == 'm' || 'M'){
cout << "1. Perfect Scores\n"
"2. Larger Than n\n"
"3. Roman Numeral Converter\n"
"4. Monkey Business\n"
"5. Lottery\n"
"6. Exit\n";

cout << "Pick which program you would like to run." << endl;
cin >> choice;
}

else if (choice == 1){  //  -----------Perfect Scores------------
    do{
int countPerfect(int a[])
{
int i=0;
for(int l=0; l<10; l++)
    if(a[1]==100)
        i++;
return i;
}

{
int score[10];
for(int i=0; i<10; i++)
{
    cout << "Enter score " << i+1 << endl;
    cin >> score[i];
    while(score[i]<0 || score[i] > 100)
    {
        cout << "Enter score between 1 and 100." << endl;
        cin >> score[i];
    }
}
int n = countPerfect(score);
cout << "No of perfect scores: " << n << endl;
cout << "To repeat, press Y. For main menu, press M" << endl;
cin >> repeat;
return 0;
}
        }while(repeat == 'Y' || repeat == 'y');
}
//        ------------Larger Than n--------------
   else if (choice == 2){
       do{
void display_greator(int A[], int size, int n)
{
int i;
for(i=0; i< size; i++)
{
    if(A[i]>n)
    {
        cout << A[i] << endl;
    }
}
}

int main(void)
{
int i, size;
cout << "Enter the size of your array:"<< endl;
cin >> size;
int N[size];
cout << "Enter a list of " << size << " numbers:" << endl;
for( i=0; i<size; i++)
{
    cin >> N[i];
}
int num;
cout << "Enter your number n:" << endl;
cin >> num;
display_greator(N, size, num);
cout << "To repeat, press Y. For main menu, press M" << endl;
cin >> repeat;
}
       }while(repeat == 'Y' || repeat == 'y');
}
//  ----------------------Roman Numeral Converter------------------
else if (choice == 3){
    char repeat;
    do{
{
int n;
string romanNumbers[]={"I", "II", "III", "IV", "V", "VI", "VII",
    "VIII", "IX", "X", "XI", "XII",
    "XIII", "VIX", "XV", "XVI", "XVII", "XVIII", "XIX", "XX"};
cout << "Enter a decimal number or enter 0 to quit."  << endl;
cin >> n;
if(n==0)
exit(0);
do
{

    cout << "Enter number between 1 and 20" << endl;
    cout << "Enter number or enter 0 to quit" << endl;
    cin >> n;
} while(n < 0 || n > 20);
{
    cout << "Enter decimal equivalent roman number:" << endl;
    cout << "Enter a number between 1 and 20:" << endl;
    cin >> n;
    if(n==0)
        exit(0);
    cout << "To repeat, press Y. For main menu, press M" << endl;
    cin >> repeat;
}
while(n > 0 || n < 20);
return 0;
}
        }while(repeat == 'Y' || repeat == 'y');
}
//    ---------------Monkey Business--------------------
else if(choice == 4){
   do{
const int DAYS = 7;
double getTotalAmountOfFood(int[][DAYS],int);
double getLeastAmountOfFood(int[][DAYS],int, double);
double getGreatestAmountOfFood(int[][DAYS],int, double);

{

    const int MONKEYS = 3;
    double totalFood, averageFood, leastFood, greatestFood;
    int foodInfo[MONKEYS][DAYS];

    for(int i= 0; i< MONKEYS; i++)
    {
        cout << "Enter the food information of the monkey" <<
        (i + 1) << ":" << endl;
        for(int j = 0; j < DAYS; j++)
        {
            cout << "Day" << (j + 1) << ":" << endl;
            cin >> foodInfo[i][j];
            while(foodInfo[i][j] < 0)
            {
                cout << "Day " << (j+1) << ":" << endl;
                cin >> foodInfo[i][j];

            }
        }
        cout << endl;
    }
    totalFood = getTotalAmountOfFood(foodInfo, MONKEYS);
    leastFood = getLeastAmountOfFood(foodInfo, MONKEYS, totalFood);
    greatestFood = getGreatestAmountOfFood(foodInfo, MONKEYS, 0);
    averageFood = totalFood / DAYS;
    cout << "The average amount of food per day for three monkeys(in pounds):"
    << averageFood << endl;
    cout << "The least amount of food per week for monkeys(in pounds) is:"
    << leastFood << endl;
    cout << "The greatest amount of food per wek for a monkey is(in pounds):"
    << greatestFood << endl;
    cout << "To repeat, press Y. For main menu, press M" << endl;
    cin >> repeat;
    return 0;
}

double getTotalAmountOfFood(int food[][DAYS],int mnks)
{
    double total = 0;

    for(int i = 0; i < mnks; i++)
    {
        for(int j = 0; j < DAYS; j++)
        {
            total += food[i][j];
        }
    }
    return total;
}
double getLeastAmountOfFood(int food[][DAYS], int mnks, double leastAmount)
{
    double least = leastAmount;
    double weekTotal;
    for(int i = 0; i < mnks; i++)
    {
        weekTotal = 0;
        for(int j = 0; j < DAYS; j++)
        {
            weekTotal += food[i][j];
        }
        if(least > weekTotal)
            least = weekTotal;
    }
    return least;
}
double getGreatestAmountOfFood(int food[][DAYS], int mnks, double greatestAmount)
{
    double greatest = greatestAmount;
    double weekTotal;
    for(int i = 0; i < mnks; i++)
    {
        weekTotal = 0;
        for(int j = 0; j < DAYS; j++)
        {
            weekTotal +=food[i][j];
        }
        if(greatest < weekTotal)
            greatest = weekTotal;
    }

    return greatest;
}
       }while(repeat == 'Y' || repeat == 'y');
}
//                    ----------------Lottery--------------------
else if (choice == 5){
    char repeat;
    do{

    srand(time(NULL));
    int winningDigits[5];
    int player[5];
    int num;
    int matchCount = 0;

    for (int i = 0; i < 5; i++)
    {
        winningDigits[i] = rand() % 10;
    }

    cout << "Enter 5 integers in the range of 0 to 9." << endl;
    for(int i = 0; i < 5; i++)
    {
        cout << "Number #" << (i + 1) << ": " << endl;
        cin >> num;

        while (num < 0 || num > 9)
        {
            cout << "Invalid number! It should be in the range of 0 through 9." << endl;
            cout << "Number #" << (i + 1) << ": " << endl;
            cin >> num;
        }
        player[i] = num;
    }
    for (int i = 0; i < 5; i++)
    {
        if (winningDigits[i] == player[i])
        {
            matchCount++;
        }
    }
    cout << "Winning digits: " << endl;
    for (int i = 0; i < 5; i++)
    {
        cout << winningDigits[i] << " " << endl;
    }
    cout << "Player's digits: " << endl;
    for (int i = 0; i < 5; i++)
    {
        cout << player[i] << " " << endl;
    }
    cout << endl << endl << "Number of digits matched: "
<< matchCount << endl;
    cout << "To repeat, press Y. For main menu, press M" << endl;
    cin >> repeat;
    return 0;

        }while(repeat == 'Y' || repeat == 'y');
}
else if (choice == 6)
{cout << "Bye" << endl;}
}

I'm expecting to be able to choose a program to run, repeat it, and     repeat the entire program from main menu.

A: I am not going to point out all errors in your code, they are just too many. You went too fast too far. If you think the complexity of code and the errors it procudes are intimidating you are right. I wrote codes with more lines, but yours is too complicated for me. Go in small steps. Start with something along the line of:
int choose() { return 0; }

void func1() {}
void func2() {}

int main() {
    int choice = 0;
    while ( choice = choose() ) {
        switch(choice) {
            case 1 : func1(); break;
            case 2 : func2(); break;
        }
    }
}

Your main function does not have to be more complex than that.
Write this, not more. Make sure it compiles, then in tiny steps fill the gaps, after each step compile, see if it does what you expect and only then continue to put more.
Some problems in your code (partly stolen from comments):

*

*you cannot have more than one main

*you cannot define functions inside functions

*you cannot start an if statement with else if

*int N[size]; is not standard C++ for a non-compile-time-constant size. Use std::vector instead

*see here why using namespace std is considered bad practice

*if (repeat == 'm' || 'M') is not doing what you expect, it should be if (repeat == 'm' || repeat == 'M'). In yours 'M' is taken as a bool which is always true (because it isnt 0).

*make sure to initialize variables. Using variables that are not initialized causes undefined behaviour.

*please next time reduce your code to a mcve and try to concentrate on a single problem, also include the error in the question

*I cannot help myself than to point that for each single problem there are duplicate questions, which brings me back to: Don't do too many things at once. Fixing 100 errors at once is extremely difficult, fixing 1 error is doable.

*last but not least, pay attention to compiler errors and warnings while you write the code (again: not after you wrote several pages, but after each single line)


text:
Q: Long Query String Being Split I'm using the query string to pass data between two PhoneApplicationPages but the destination page is recieving the data as multiple paameters instead of one big string. This is a problem as I'm passing data as JSON which cannot be desrialized if it's truncated mid flow.
The data I'm passing is:
NavigationService.Navigate("/MainPage.xaml?view=recipes&searchargs={"Author":null,"AuthorFilterType":2,"Categories":["1 Point","100-200 Calorie","1-3 grams Fat","3 Point","Baked Snack","Bakery & Baked Products","Banana","Beer","Boutique Wines","Bread","Breakfast","Breakfast Drinks","Cake","Cakes","Cocktails","Collectible Wines","Cookie","Cookie Dessert","Dairy","Dessert","Desserts","Diabetic","Drinks & Beverages","Fruit","Fruit Dessert","Fruit Drinks","Fruits","Gluten Free","High Fiber","Main Course","Main dish","Pasta","Pork","Raw Foods","Salads","Sandwiches","Shake & Smoothie","Side dish","Snack","Strawberry","Sweet Snack","Under 1 gram Fat","Under 100 Calorie","Vegetarian","Weight Watchers Points","Yogurt"],"Countries":[],"GlobalSearch":"","Ingredients":[],"MaxIngredients":0,"MinIngredients":0,"Name":null,"NameFilterType":2,"Rating":0,"Types":[]}");

But the query string contains this:

Is this a bug?

A: you need to escape the " used by json try this
NavigationService.Navigate("/MainPage.xaml?view=recipes&searchargs={\"Author\":null,\"AuthorFilterType\":2,\"Categories\":[\"1 Point\",\"100-200 Calorie\",\"1-3 grams Fat\",\"3 Point\",\"Baked Snack\",\"Bakery & Baked Products\",\"Banana\",\"Beer\",\"Boutique Wines\",\"Bread\",\"Breakfast\",\"Breakfast Drinks\",\"Cake\",\"Cakes\",\"Cocktails\",\"Collectible Wines\",\"Cookie\",\"Cookie Dessert\",\"Dairy\",\"Dessert\",\"Desserts\",\"Diabetic\",\"Drinks & Beverages\",\"Fruit\",\"Fruit Dessert\",\"Fruit Drinks\",\"Fruits\",\"Gluten Free\",\"High Fiber\",\"Main Course\",\"Main dish\",\"Pasta\",\"Pork\",\"Raw Foods\",\"Salads\",\"Sandwiches\",\"Shake & Smoothie\",\"Side dish\",\"Snack\",\"Strawberry\",\"Sweet Snack\",\"Under 1 gram Fat\",\"Under 100 Calorie\",\"Vegetarian\",\"Weight Watchers Points\",\"Yogurt\"],\"Countries\":[],\"GlobalSearch\":\"\",\"Ingredients\":[],\"MaxIngredients\":0,\"MinIngredients\":0,\"Name\":null,\"NameFilterType\":2,\"Rating\":0,\"Types\":[]}");

A: Thanks @Hermit Dave. For reference, the methods are Uri.EscapeDataString() and Uri.UnescapeDataString().


text:
Q: Android 10 image upload error: kotlin.io.NoSuchFileException: : The source file doesn't exist Hello i am trying to take image from local storage and upload it to the server. But on android 10 and stock android 9 its not working. Its giving me this error:
Fatal Exception: kotlin.io.NoSuchFileException: : The source file doesn't exist.
       at kotlin.io.FilesKt__UtilsKt.copyTo(Utils.kt:183)
       at kotlin.io.FilesKt__UtilsKt.copyTo$default(Utils.kt:181)
       at id.zelory.compressor.UtilKt.copyToCache(Util.kt:82)
       at id.zelory.compressor.Compressor$compress$3.invokeSuspend(Compressor.kt:25)
       at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
       at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
       at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

Heres is my code to take image using intent:
   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
            imageUri = data!!.getData()!!

            updateAdapter(imageUri)

        }

    }

and the crash i am getting is in here:
  fun uploadImagetoS3(presignedUrl: String, imageUri: Uri) {

        var file = File(getRealPathFromURI(activity!!, imageUri)) <- here its crashing

        MainScope().launch {

            file = Compressor.compress(activity!!, file)

            feedbackViewmodel.uploadImageToS3(
                presignedUrl,
                RequestBody.create(MediaType.parse("image/jpeg"), file)
            )

        }

    }

Here is that method getRealPathFromURI :
  private fun getRealPathFromURI(context: Context, contentUri: Uri): String {
        var cursor: Cursor? = null
        return try {
            val proj = arrayOf(MediaStore.Images.Media.DATA)

            cursor = context.contentResolver.query(contentUri, proj, null, null, null)

            val column_index: Int = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)

            cursor!!.moveToFirst()

            cursor.getString(column_index)

        } catch (e: Exception) {

            ""
        } finally {
            if (cursor != null) {
                cursor.close()
            }
        }
    }

WHat am i doing wrong? its working properly till android 9 in most of the devices, but in android 10 and stock android one it is crashing.
I have also already added
android:requestLegacyExternalStorage="true"
in manifest. It was working properly in between last week.
But its still crashing again.
Heres my uploadimage to s3 method:
 fun uploadImageToS3(url: String, requestBody: InputStreamRequestBody) {
        showProgress(true)

        restClient.noAuthClient.create(ApiService::class.java)
            .uploadImage(url, requestBody)
            .enqueue(object : Callback<Void> {

                override fun onResponse(
                    call: Call<Void>, response: Response<Void>
                ) {
                    showProgress(false)

                    if (response.isSuccessful) {

                        uploadImageData.postValue(true)
                    } else {

                        errorData.postValue(response.message())

                        Log.e("xoxo","image upload error onresponse: "+response.toString())

                    }

                }

                override fun onFailure(call: Call<Void>, t: Throwable) {

                    showProgress(false)

                    errorData.postValue(t.message)

                    Log.e("xoxo","image upload error: "+t.toString())

                }
            })

    }

and here it is in the apiservice:
    @PUT
    fun uploadImage(@Url url: String, @Body image: InputStreamRequestBody): Call<Void>

The error from retrofit as logged in code onResponse:
2020-05-10 03:29:37.319 7903-7903/in.example.com E/xoxo: image upload error onresponse: Response{protocol=http/1.1, code=501, message=Not Implemented, url=https://s3.ap-south-1.amazonaws.com/example.com-prod-backend/events/11765_6e6e5680a5009e7bc1932e08?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIARBVMRBYEREFA7JZK%2F20200509%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20200509T215929Z&X-Amz-Expires=300&X-Amz-SignedHeaders=host&X-Amz-Signature=7271b6c8c1b89d4b468abc20dd74f2a4f820dfd158781f905b9f09b580c15e02}

Also here is the okhttp logs in case you want:
2020-05-10 03:37:44.070 7903-8784/in.example.com D/OkHttp: --> PUT https://s3.ap-south-1.amazonaws.com/example.com-prod-backend/events/11765_be7a06c969513557e2830176?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIARBVMRBYEREFA7JZK%2F20200509%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20200509T220736Z&X-Amz-Expires=300&X-Amz-SignedHeaders=host&X-Amz-Signature=3dcaf93b15f0edf4224a4ce6c56bda2d9e9b2aa94144ba12e561f93b942e65a4
2020-05-10 03:37:44.071 7903-8784/in.example.com D/OkHttp: Content-Type: image/jpeg
2020-05-10 03:37:44.122 7903-8784/in.example.com D/OkHttp: --> END PUT (binary -1-byte body omitted)
2020-05-10 03:37:44.145 7903-8784/in.example.com W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
2020-05-10 03:37:44.149 7903-8784/in.example.com I/System.out: e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
2020-05-10 03:37:44.150 7903-8784/in.example.com D/Linux: [Posix_connect Debug]Process in.example.com :443
2020-05-10 03:37:44.213 7903-8784/in.example.com D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2020-05-10 03:37:44.217 7903-8784/in.example.com D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object
2020-05-10 03:37:44.867 7903-8784/in.example.com D/OkHttp: <-- 501 Not Implemented https://s3.ap-south-1.amazonaws.com/bexample.com-prod-backend/events/11765_be7a06c969513557e2830176?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIARBVMRBYEREFA7JZK%2F20200509%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20200509T220736Z&X-Amz-Expires=300&X-Amz-SignedHeaders=host&X-Amz-Signature=3dcaf93b15f0edf4224a4ce6c56bda2d9e9b2aa94144ba12e561f93b942e65a4 (744ms)
2020-05-10 03:37:44.867 7903-8784/in.example.com D/OkHttp: x-amz-request-id: A665CB05729AEB19
2020-05-10 03:37:44.868 7903-8784/in.example.com D/OkHttp: x-amz-id-2: KN3aeeqGgblXcYs7wvF9J7IAdjKSagFHEAy9w4eVkN93IRtO6CoJY6rLGlpavK3Lzb5yl0uOH7o=
2020-05-10 03:37:44.868 7903-8784/in.example.com D/OkHttp: Content-Type: application/xml
2020-05-10 03:37:44.868 7903-8784/in.example.com D/OkHttp: Transfer-Encoding: chunked
2020-05-10 03:37:44.868 7903-8784/in.example.com D/OkHttp: Date: Sat, 09 May 2020 22:07:36 GMT


text:
Q: Windows 10 Icons Suddenly Grew 10 minutes ago I was using google, and I kept getting requests from google saying "Unusual traffic from your computer network"
I didn't know why, but I thought what if it's malware.
I downloaded and am now scanning with Malware Bytes.
Suddenly my Icons (using Windows 10) became jumbo size.
When I check the resolution, it is  1366 x 768.
How to bring icons back to original size?

A: 2 Possibilities:
ResolutionGo into settings > system > display > advanced display settings.From there you can change your screen resolution. Click on the selection, and make sure it is set to the one that says recommended, and press apply.Icon ViewRight click on your desktop and select "View", then select Medium Icons.There's a lot more things that could be causing this, these are only 2 simple possibilities.

A: If you just want to change the icon size on the desktop you can change it by holding CTRL + scrolling the mouse wheel up or down.


text:
Q: Vulkan validation layer CreateDebugUtilsMessengerEXT Allocator is NULL I am trying to follow https://vulkan-tutorial.com/ and a Udemy course on my journey to understand Vulkan.
So far I was able to follow everything but the validation layers are not working and I have no idea why.
Tried the following:

*

*check for typos

*check validation layer present in vulkan configurator

*installed sdk on 2 separate devices

*pushed code around and asked the instructor on Udemy.

So far I have found the following:

*

*Instance creation is successful

*Instance is passed into
static VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger)
The problem I have managed to isolate by breakpoints is that pAllocator is NULL.
Github Repo can be found here: https://github.com/b34s7m0d3/VulkanImplementation
I'm trying to be proper and separate things in different files, is that my issue?

A: You are enabling Debug Report extension, but then you try using Debug Utils messenger instead.


text:
Q: Phusion Passenger status crashing with too long socket name I am trying passenger on Ubuntu 18.04, pretty much generic install and the passenger-status call crashes. Not super clear how to set the path that it uses for local socket communication.
Version : 6.0.12
Date    : 2021-11-17 23:20:19 +0000
Instance: PdoRpeL5 (Apache/2.4.29 (Ubuntu) Phusion_Passenger/6.0.12)

Traceback (most recent call last):
    6: from /usr/sbin/passenger-status:349:in `<main>'
    5: from /usr/sbin/passenger-status:346:in `start'
    4: from /usr/sbin/passenger-status:62:in `command_show_status'
    3: from /usr/sbin/passenger-status:124:in `show_status'
    2: from /usr/lib/ruby/vendor_ruby/phusion_passenger/admin_tools/instance.rb:94:in `http_request'
    1: from /usr/lib/ruby/vendor_ruby/phusion_passenger/admin_tools/instance.rb:94:in `new'
/usr/lib/ruby/vendor_ruby/phusion_passenger/admin_tools/instance.rb:94:in `initialize': too long unix socket path (116bytes given but 108bytes max) (ArgumentError)

Looking at that code, @path is /tmp/systemd-private-af50a27a57d04fec9366f72dd251a3be-apache2.service-Dy9bBV/tmp/passenger.PPuC2RN which makes the socket name /tmp/systemd-private-af50a27a57d04fec9366f72dd251a3be-apache2.service-Dy9bBV/tmp/passenger.PPuC2RN/agents.s/core_api
Seems like a passenger internal issue but I'm looking for a workaround...

A: Have you tried editing your web server service file, nginx.service or apache2.service? I had this problem and solved it by removing the line:
PrivateTmp=true

from /etc/systemd/system/multi-user.target.wants/apache2.service.
Then:
sudo systemctl daemon-reload
sudo systemctl restart apache2

https://github.com/phusion/passenger/issues/2397
"this is because the path generated by the systemd private tmp feature is 80 chars long, which only leaves 27 chars for an application to use, and passenger uses 35 chars in its path to its socket."


text:
Q: JRE error when trying to install Matlab Compiler Runtime Once again, I spent much time trying to get something to work without success.
I want to install MATLAB Compiler Runtime on my Ubuntu 13.04, where there is no MATLAB installed.
Here's what I did:
I downloaded the 64-bit Linux version R2012b(8.0) off of
http://www.mathworks.com/products/compiler/mcr/index.html?s_cid=BB.
Then, I switched into the folder and tried to install via
sudo ./install just to receive the following message:
Error: Cannot locate Java Runtime Environment (JRE).
The directory /home/konni/Downloads/MCR_R2012b_glnxa64_installer/sys/java/jre/glnx86/jre does not exist.
And, it does not exist indeed, but there exists a folder with "glnxa86" instead of "glnx86". I wouldn't just want to rename it, though.
I do have a JRE installed on my machine, btw:
java version "1.7.0_25"
OpenJDK Runtime Environment (IcedTea 2.3.10) (7u25-2.3.10-1ubuntu0.13.04.2)
OpenJDK Server VM (build 23.7-b01, mixed mode)
I have absolutely no clue what to do. The problems I found using google didn't quite help me, either...
Maybe you have an idea?
I'd greatly appreciate any help! :-)

A: If the only problem is finding the JRE, then the command line switch -javadir will get you done:
./install -javadir /usr/lib/jvm/java-7-openjdk-i386/jre/

A: I had the same problem recently when installing a software that required a 7.13 MCR on an Ubuntu 17.10.
In this
https://www.linuxquestions.org/questions/linux-newbie-8/matlab-7-5-compiled-runtime-for-64-bit-linux-installation-no-jre-error-838281/
I found that the 32 bit version installs fine, and it did, but obviously, that didn't solve my problem.
However, I found a way to do it. The trick is that the installer needs the old JRE (1.5) and will not work with JDK 8.
So the first step is to run
./MCRInstaller.bin -is:extract

this will create a directory called istemp... something, for me istemp23732345211606.

ls

jre1.5.0-linux-amd64.bin  JVMNotFound.txt  setup.jar  Verify.jar
It is tempting to run the setup.jar directly, do try, but with Java 8, I only got the following error message:

Could not load wizard specified in /wizard.inf (104)

But perhaps it will work for you. People who get the above mentioned error with wizard.inf should look further, because the installer needs JDK 5 to run.
I chose not to use the bundled version but downloaded the JDK 5 from Oracle. The bundled version might work as well - I did not try.
You can download JDK 5 from here:
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html#jdk-1.5.0_22-oth-JPR
Extract the downloaded archive (chmod +x the bin and run), then copy the files to /usr/lib/jvm/java5
Rename the jdk1.5.0_022 or anything to jdk1.5.0 to make it simple.
Fix attributes:
sudo chmod a+x /usr/bin/java
sudo chmod a+x /usr/bin/javac
sudo chmod a+x /usr/bin/javaws
sudo chown -R root:root /usr/lib/jvm/java5/jdk1.5.0

Then run:
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/java5/jdk1.5.0/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/java5/jdk1.5.0/bin/javac" 1

Now chose the jdk 5 as default
sudo update-alternatives --config java

And selecting the appropriate option.
Check that it worked
java -version

You should see something like this:

java version "1.5.0_22" Java(TM) 2 Runtime Environment, Standard
  Edition (build 1.5.0_22-b03) Java HotSpot(TM) 64-Bit Server VM (build
  1.5.0_22-b03, mixed mode)

Now you can run the setup.jar file in the extracted directory (istemp...)
sudo java -jar setup.jar

I recommend that you chose a contemporary java by running
sudo update-alternatives --config java

again.

A: When running the installer.sh, use the command line option "-is:javahome [path to your java jre folder]".
For instance, I installed below a java 8 jre on an old matlab compiler 2007b as follow:

sudo /opt/installer.sh -console -is:javahome /usr/lib/jvm/java-8-openjdk-amd64/jre/

A: I had same problem. The problem is you are installing 64-bit matlab on 32-bit ubuntu. use 32-bit matlab and install in ubuntu 32-bit. use 64-bit matlab and install in ubuntu 64-bit. Please like the answer if it was helpful.


text:
Q: How can I detect if a file is binary (non-text) in Python? How can I tell if a file is binary (non-text) in Python?
I am searching through a large set of files in Python, and keep getting matches in binary files. This makes the output look incredibly messy.
I know I could use grep -I, but I am doing more with the data than what grep allows for.
In the past, I would have just searched for characters greater than 0x7f, but utf8 and the like, make that impossible on modern systems. Ideally, the solution would be fast.

A: Try this:
def is_binary(filename):
    """Return true if the given filename is binary.
    @raise EnvironmentError: if the file does not exist or cannot be accessed.
    @attention: found @ http://bytes.com/topic/python/answers/21222-determine-file-type-binary-text on 6/08/2010
    @author: Trent Mick <TrentM@ActiveState.com>
    @author: Jorge Orpinel <jorge@orpinel.com>"""
    fin = open(filename, 'rb')
    try:
        CHUNKSIZE = 1024
        while 1:
            chunk = fin.read(CHUNKSIZE)
            if '\0' in chunk: # found null byte
                return True
            if len(chunk) < CHUNKSIZE:
                break # done
    # A-wooo! Mira, python no necesita el "except:". Achis... Que listo es.
    finally:
        fin.close()

    return False

A: If it helps, many many binary types begin with a magic numbers. Here is a list of file signatures.

A: Yet another method based on file(1) behavior:
>>> textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
>>> is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))

Example:
>>> is_binary_string(open('/usr/bin/python', 'rb').read(1024))
True
>>> is_binary_string(open('/usr/bin/dh_python3', 'rb').read(1024))
False

A: Use binaryornot library (GitHub).
It is very simple and based on the code found in this stackoverflow question.
You can actually write this in 2 lines of code, however this package saves you from having to write and thoroughly test those 2 lines of code with all sorts of weird file types, cross-platform.

A: We can use python itself to check if a file is binary, because it fails if we try to open binary file in text mode
def is_binary(file_name):
    try:
        with open(file_name, 'tr') as check_file:  # try open file in text mode
            check_file.read()
            return False
    except:  # if fail then file is non-text (binary)
        return True

A: Here's a suggestion that uses the Unix file command:
import re
import subprocess

def istext(path):
    return (re.search(r':.* text',
                      subprocess.Popen(["file", '-L', path],
                                       stdout=subprocess.PIPE).stdout.read())
            is not None)

Example usage:

>>> istext('/etc/motd')
True
>>> istext('/vmlinuz')
False
>>> open('/tmp/japanese').read()
'\xe3\x81\x93\xe3\x82\x8c\xe3\x81\xaf\xe3\x80\x81\xe3\x81\xbf\xe3\x81\x9a\xe3\x81\x8c\xe3\x82\x81\xe5\xba\xa7\xe3\x81\xae\xe6\x99\x82\xe4\xbb\xa3\xe3\x81\xae\xe5\xb9\x95\xe9\x96\x8b\xe3\x81\x91\xe3\x80\x82\n'
>>> istext('/tmp/japanese') # works on UTF-8
True

It has the downsides of not being portable to Windows (unless you have something like the file command there), and having to spawn an external process for each file, which might not be palatable.

A: You can also use the mimetypes module:
import mimetypes
...
mime = mimetypes.guess_type(file)

It's fairly easy to compile a list of binary mime types. For example Apache distributes with a mime.types file that you could parse into a set of lists, binary and text and then check to see if the mime is in your text or binary list.

A: Usually you have to guess.
You can look at the extensions as one clue, if the files have them.
You can also recognise know binary formats, and ignore those.
Otherwise see what proportion of non-printable ASCII bytes you have and take a guess from that.
You can also try decoding from UTF-8 and see if that produces sensible output.

A: A shorter solution, with a UTF-16 warning:
def is_binary(filename):
    """
    Return true if the given filename appears to be binary.
    File is considered to be binary if it contains a NULL byte.
    FIXME: This approach incorrectly reports UTF-16 as binary.
    """
    with open(filename, 'rb') as f:
        for block in f:
            if b'\0' in block:
                return True
    return False

A: Try using the currently maintained python-magic which is not the same module in @Kami Kisiel's answer. This does support all platforms including Windows however you will need the libmagic binary files. This is explained in the README.
Unlike the mimetypes module, it doesn't use the file's extension and instead inspects the contents of the file.
>>> import magic
>>> magic.from_file("testdata/test.pdf", mime=True)
'application/pdf'
>>> magic.from_file("testdata/test.pdf")
'PDF document, version 1.2'
>>> magic.from_buffer(open("testdata/test.pdf").read(1024))
'PDF document, version 1.2'

A: from binaryornot.check import is_binary
is_binary('filename')

Documentation

A: If you're using python3 with utf-8 it is straight forward, just open the file in text mode and stop processing if you get an UnicodeDecodeError. Python3 will use unicode when handling files in text mode (and bytearray in binary mode) - if your encoding can't decode arbitrary files it's quite likely that you will get UnicodeDecodeError.
Example:
try:
    with open(filename, "r") as f:
        for l in f:
             process_line(l)
except UnicodeDecodeError:
    pass # Fond non-text data

A: If you're not on Windows, you can use Python Magic to determine the filetype. Then you can check if it is a text/ mime type.

A: Here's a function that first checks if the file starts with a BOM and if not looks for a zero byte within the initial 8192 bytes:
import codecs

#: BOMs to indicate that a file is a text file even if it contains zero bytes.
_TEXT_BOMS = (
    codecs.BOM_UTF16_BE,
    codecs.BOM_UTF16_LE,
    codecs.BOM_UTF32_BE,
    codecs.BOM_UTF32_LE,
    codecs.BOM_UTF8,
)

def is_binary_file(source_path):
    with open(source_path, 'rb') as source_file:
        initial_bytes = source_file.read(8192)
    return not any(initial_bytes.startswith(bom) for bom in _TEXT_BOMS) \
           and b'\0' in initial_bytes

Technically the check for the UTF-8 BOM is unnecessary because it should not contain zero bytes for all practical purpose. But as it is a very common encoding it's quicker to check for the BOM in the beginning instead of scanning all the 8192 bytes for 0.

A: Most of the programs consider the file to be binary (which is any file that is not "line-oriented") if it contains a NULL character.
Here is perl's version of pp_fttext() (pp_sys.c) implemented in Python:
import sys
PY3 = sys.version_info[0] == 3

# A function that takes an integer in the 8-bit range and returns
# a single-character byte object in py3 / a single-character string
# in py2.
#
int2byte = (lambda x: bytes((x,))) if PY3 else chr

_text_characters = (
        b''.join(int2byte(i) for i in range(32, 127)) +
        b'\n\r\t\f\b')

def istextfile(fileobj, blocksize=512):
    """ Uses heuristics to guess whether the given file is text or binary,
        by reading a single block of bytes from the file.
        If more than 30% of the chars in the block are non-text, or there
        are NUL ('\x00') bytes in the block, assume this is a binary file.
    """
    block = fileobj.read(blocksize)
    if b'\x00' in block:
        # Files with null bytes are binary
        return False
    elif not block:
        # An empty file is considered a valid text file
        return True

    # Use translate's 'deletechars' argument to efficiently remove all
    # occurrences of _text_characters from the block
    nontext = block.translate(None, _text_characters)
    return float(len(nontext)) / len(block) <= 0.30

Note also that this code was written to run on both Python 2 and Python 3 without changes.

Source: Perl's "guess if file is text or binary" implemented in Python

A: I guess that the best solution is to use the guess_type function. It holds a list with several mimetypes and you can also include your own types.
Here come the script that I did to solve my problem:
from mimetypes import guess_type
from mimetypes import add_type

def __init__(self):
        self.__addMimeTypes()

def __addMimeTypes(self):
        add_type("text/plain",".properties")

def __listDir(self,path):
        try:
            return listdir(path)
        except IOError:
            print ("The directory {0} could not be accessed".format(path))

def getTextFiles(self, path):
        asciiFiles = []
        for files in self.__listDir(path):
            if guess_type(files)[0].split("/")[0] == "text":
                asciiFiles.append(files)
        try:
            return asciiFiles
        except NameError:
            print ("No text files in directory: {0}".format(path))
        finally:
            del asciiFiles

It is inside of a Class, as you can see based on the ustructure of the code. But you can pretty much change the things you want to implement it inside your application.
It`s quite simple to use.
The method getTextFiles returns a list object with all the text files that resides on the directory you pass in path variable.

A: I came here looking for exactly the same thing--a comprehensive solution provided by the standard library to detect binary or text. After reviewing the options people suggested, the nix file command looks to be the best choice (I'm only developing for linux boxen). Some others posted solutions using file but they are unnecessarily complicated in my opinion, so here's what I came up with:
def test_file_isbinary(filename):
    cmd = shlex.split("file -b -e soft '{}'".format(filename))
    if subprocess.check_output(cmd)[:4] in {'ASCI', 'UTF-'}:
        return False
    return True

It should go without saying, but your code that calls this function should make sure you can read a file before testing it, otherwise this will be mistakenly detect the file as binary.

A: on *NIX:
If you have access to the file shell-command, shlex can help make the subprocess module more usable:
from os.path import realpath
from subprocess import check_output
from shlex import split

filepath = realpath('rel/or/abs/path/to/file')
assert 'ascii' in check_output(split('file {}'.format(filepth).lower()))

Or, you could also stick that in a for-loop to get output for all files in the current dir using:
import os
for afile in [x for x in os.listdir('.') if os.path.isfile(x)]:
    assert 'ascii' in check_output(split('file {}'.format(afile).lower()))

or for all subdirs:
for curdir, filelist in zip(os.walk('.')[0], os.walk('.')[2]):
     for afile in filelist:
         assert 'ascii' in check_output(split('file {}'.format(afile).lower()))

A: All of these basic methods were incorporated into a Python library: binaryornot. Install with pip.
From the documentation:
>>> from binaryornot.check import is_binary
>>> is_binary('README.rst')
False

A: are you in unix? if so, then try:
isBinary = os.system("file -b" + name + " | grep text > /dev/null")

The shell return values are inverted (0 is ok, so if it finds "text" then it will return a 0, and in Python that is a False expression).

A: Simpler way is to check if the file consist NULL character (\x00) by using in operator, for instance:
b'\x00' in open("foo.bar", 'rb').read()

See below the complete example:
#!/usr/bin/env python3
import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('file', nargs=1)
    args = parser.parse_args()
    with open(args.file[0], 'rb') as f:
        if b'\x00' in f.read():
            print('The file is binary!')
        else:
            print('The file is not binary!')

Sample usage:
$ ./is_binary.py /etc/hosts
The file is not binary!
$ ./is_binary.py `which which`
The file is binary!


text:
Q: Tesseract.js - Output result line by line instead of reading whole image I am trying to read text with tesseract.js in Node.
To speed up the process, I'd like to have it print out the results line by line. If I understand tesseract correctly, it first reads the image, applies some changes, filters etc to make it more readable, detect the lines and then it starts recognizing the text in those lines.
Is there any way how I could get those lines before it finishes recognizing the whole document or would I need to literally split the image and then pass each line as an image to tesseract?
To try this, I split a test image by hand and ran them through tesseract. This speeds up the process (for my specific use-case) by a lot.
Result: https://gyazo.com/3e50e40bb7b2f07190c4a2377b65c92d
var Tesseract = require('tesseract.js')

var myImage = [
        "1.jpg",
        "2.jpg",
        "3.jpg",
        "4.jpg",
        "5.jpg",
        "6.jpg",
        "7.jpg",
        "8.jpg",
        "9.jpg"
]

rec(0)

function rec(number){
    var thisImage = myImage[number];

    Tesseract.recognize(thisImage, {
        lang: "eng"
    })
       .then(function (result) {
            console.log("[Line: " + number + "] " + result.text.replace(/(\r\n|\n|\r)/gm, ""));
            if(number < 8){
                number++;
                rec(number)
            }
        })
}

In case I would have to split the image beforehand, which NodeJS library should I use to detect lines? ImageMagick?
I only found a python example from somebody trying to detect lines in an image:
Split text lines in scanned document
What would be the right approach for this?


text:
Q: Install JDK 8 on Debian I am trying to install JDK 8 on Debian. I found a lot of similar topics but none of them solved my problem. In most topics the solution was this commands
sudo apt-get install software-properties-common
sudo apt-get install python-software-properties

sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get install openjdk-8-jdk

But I got this error

Reading package lists... Done Building dependency tree        Reading
  state information... Done Some packages could not be installed. This
  may mean that you have requested an impossible situation or if you are
  using the unstable distribution that some required packages have not
  yet been created or been moved out of Incoming. The following
  information may help to resolve the situation:
The following packages have unmet dependencies:  openjdk-8-jdk :
  Depends: openjdk-8-jre (= 8u111-b14-2~bpo8+1) but it is not going to
  be installed
                   Depends: openjdk-8-jdk-headless (= 8u111-b14-2~bpo8+1) but it is not going to be installed E: Unable to
  correct problems, you have held broken packages.

I also checked for updates
sudo update-alternatives --config java

and the output was

There is only one alternative in link group java (providing
  /usr/bin/java): /usr/lib/jvm/java-7-openjdk-i386/jre/bin/java
      Nothing to configure.

A: openjdk-8 is available in my default Jessie/stable install - just need to apt-get install it (openjdk-8-jdk and whatever else you want/need that it recommends or depends on)
Of course, it MAY depend on your /etc/apt/sources.list file including the contrib and non-free repositories
/etc/apt/sources.list should look something like
deb http://ftp.us.debian.org/debian/ jessie main contrib non-free
deb http://security.debian.org/ jessie/updates main contrib non-free
deb http://ftp.us.debian.org/debian/ jessie-updates main contrib non-free
deb http://ftp.us.debian.org/debian/ jessie-backports main contrib non-free

A: Problem not solved here...
# cat /etc/apt/sources.list
#deb hxxp://debian.mirrors.ovh.net/debian/ jessie main contrib non-free
#deb-src hxxp://debian.mirrors.ovh.net/debian/ jessie main contrib non-free

deb hxxp://security.debian.org/ jessie/updates main contrib non-free
deb-src hxxp://security.debian.org/ jessie/updates main contrib non-free

# jessie-updates, previously known as 'volatile'
deb hxxp://debian.mirrors.ovh.net/debian/ jessie-updates main contrib non-free
deb-src hxxp://debian.mirrors.ovh.net/debian/ jessie-updates main contrib non-free

# jessie-backports, previously on backports.debian.org
deb hxxp://debian.mirrors.ovh.net/debian/ jessie-backports main contrib non-free
deb-src hxxp://debian.mirrors.ovh.net/debian/ jessie-backports main contrib non-free

deb hxxp://debian.mirrors.ovh.net/debian/ jessie main contrib non-free
deb-src hxxp://debian.mirrors.ovh.net/debian/ jessie main contrib non-free

# apt-get install openjdk-8-jdk
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 openjdk-8-jdk : Depends: openjdk-8-jre (= 8u121-b13-1~bpo8+1) but it is not going to be installed
                 Depends: openjdk-8-jdk-headless (= 8u121-b13-1~bpo8+1) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

A: The first thing is always see the Debian PTS to have an idea of what options are available to you. For instance, if I go to -
https://tracker.debian.org/pkg/openjdk-8
On the left-hand side you have something called versions - can you see it, it shows -
  stable-bpo: 8u121-b13-1~bpo8+1
     testing: 8u121-b13-3
    unstable: 8u121-b13-4

Now stable-bpo means it is in backports. the backports page describes its function excellently, see https://backports.debian.org/
So you need to add as shared by @Reto as well the backports address to the list of packages that you already have -
deb http://ftp.us.debian.org/debian/ jessie main contrib non-free
deb http://security.debian.org/ jessie/updates main contrib non-free
deb http://ftp.us.debian.org/debian/ jessie-updates main contrib non-free
deb http://ftp.us.debian.org/debian/ jessie-backports main contrib non-free

Now update the index, it should say something like this at the very end -
Reading package lists... Done
Building dependency tree
Reading state information... Done
6 packages can be upgraded. Run 'apt list --upgradable' to see them.

Don't see the number of packages that can be upgraded as that's a function of how many packages I have, how often I update packages etc. If the four lines are similar to above, that means the index updation went without a hitch, no errors.
Once that is done you could simply do -
$ aptitude search openjdk-8

to get a listing of how many different openjdk-8 packages are listed or not. For instance I'm on testing and there are quite a few here. We also have openjdk-9 as well.
Once you get it , just install as you were trying to install before -
$ sudo aptitude install openjdk-8

and let aptitude handle all the dependancy resolution. If you still have issues, let us know here.


text:
Q: How to get time required to deliver message in 802.11b network? Given: 802.11b wireless network , message with fixed size.
Find: how much time would it take to deliver message over Z km distance?

A: You can't find a definite answer, because the throughput will depend on several interference factors which affect all radio signals. At best you'll get an upper bound:

802.11b has a maximum raw data rate of 11 Mbit/s and uses the same CSMA/CA media access method defined in the original standard. Due to the CSMA/CA protocol overhead, in practice the maximum 802.11b throughput that an application can achieve is about 5.9 Mbit/s using TCP and 7.1 Mbit/s using UDP.

Note that the reach also varies with antenna size and frequency band.

Wi-Fi networks have limited range. A typical wireless router using 802.11b or 802.11g with a stock antenna might have a range of 32 m (120 ft) indoors and 95 m (300 ft) outdoors. The IEEE 802.11n however, can exceed that range by more than two times.[30] Range also varies with frequency band. Wi-Fi in the 2.4 GHz frequency block has slightly better range than Wi-Fi in the 5 GHz frequency block. Outdoor ranges - through use of directional antennas - can be improved with antennas located several kilometres or more from their base. In general, the maximum amount of power that a Wi-Fi device can transmit is limited by local regulations, such as FCC Part 15[31] in USA.

For a comprehensive network simulation software, take a look at the ns series, e.g. the latest ns3.
Sources:

*

*http://en.wikipedia.org/wiki/IEEE_802.11b-1999

*http://en.wikipedia.org/wiki/Wi-Fi#Advantages_and_challenges


text:
Q: How to clean git history without pushing to master I have a very basic knowledge of git
Looking to remove files from git history, team has been pushing large .CSV to the repo for months (because the extension was in caps they went through the .gitignore...)
I tried to delete the files with git filter then with the python add-on filter-repo
approach 1
git filter-branch —-force —index-filter \
"git rm —cached —ignore-unmatch -r'\*.CSV'" \
—prune-empty —tag-name-filter cat — —all

approach 2
$ git gc
$ git filter-repo --replace-refs delete-no-add --strip-blobs-bigger-than $ 50M
$ git reflog expire --expire=now --all
$ git gc --aggressive --prune=now

checking with du -sh .git, the size goes from 2GB to 400MB
usual next steps I read was to push origin master -f
but my admin prevents from pushing to master, so I'm at a loss at how to update the remote repo from either approach?
I tried doing the same steps on a branch and making a PR to no avail
-----Edit-----
Thanks for confirming there was no other way than pushing to master, Admin pushed for me -- life is good

A: You are going to need to work with your admin to allow a push to master in this case.  This is something that you are going to want to coordinate with the team anyway.  Removing the file from the repo's history, changes the commits and can lead to some complications with the feature branches.


text:
Q: Good Way to develop a Logger DLL for web app and windows app Let's start by the context !
At my job, I have been asked to add some log functionality to my project, a web app in ASP.NET.
What I thought is that well, I could have do it just for my project, but that's not very useful! So I want to create a DLL that can be used in others projects (webapps or windows apps).
So I planned these functionalities:

*

*XML File for configuration : LogLevel of the file, location of the file, time for keeping it, max size before writing in a new log file. For example I can have a log file where will be written only ERROR and CRITICAL logs and another file where will be written INFO and WARNING LOGS.

*

*Ability to log for a web app or for a win app

But here is the problems, I'm thinking of differents things that can go wrong and I wanted to be sure of what I do before developping it.
First of all, I will have to detect if it's a web application or a windows application. I have find some things that can be helpful like this one
Then I'm thinking about how logs will be written, each time I will write a line of log, I will have to open and close my file. I feel like it's something very greedy in performances. Am I wrong ? Is there any other way to do it ?
It should also be pointed out that there could be a problem when logging from both web applications or a multi-threaded windows applications. Another issue is that the log method could be called twice (2 times) at once, which will then create a problem of simultaneous access for the log file. What is the best way to deal with these issues?
At last, I wonder if you see any other things that can be a problem for this kind of dll ?
Thanks for your help ! :)

A: Its not worth it to reinvent the wheel. You can have a look at log4net library.
Log4net supports writing the logs into TXT, XML, SQL, MSMQ etc. What I would suggest is, writing a bunch of logs is going to block your application execution to certain extent. So instead of doing TXT or SQL logging, I would go for MSMQ logging (Its fire and forget which doesn't blocks your application code). Have a windows service to read the message queue and write the logs in a separate SQL database.

A: You could give a try to ELMAH
https://elmah.github.io/
or
to Serilog : https://serilog.net/
Both, as log4net (maybe less than log4net), are "classics". As previous answer says, there is no gain, except maybe a kind of coding fun, to reinvent the wheel.


text:
Q: How to use RxPY (or RxJS) combine_latest with a group_by observable In ReactiveX I can take the latest value out of each of a number of observables, which each may or may not be emitting at different frequencies, as follows (using RxPY):
from __future__ import print_function

from rx import Observable
import time
import IPython
import random

random.seed(123)

x1 = Observable.interval(random.randint(50, 500))
x2 = Observable.interval(random.randint(50, 500))
x3 = Observable.interval(random.randint(50, 500))

xc = Observable.combine_latest(x1, x2, x3, lambda a1, a2, a3: [a1, a2, a3])

xc.subscribe(lambda s: print(s))

input("Press Enter to end")

However, how would I do the same thing, that is, print the latest value from each of a set of observables, whenever any of the observables emits a value, when said observables were created using a group_by?
from __future__ import print_function

from rx import Observable
import time
import IPython
import random

random.seed(123)

n = 5
xx = Observable.interval(random.randint(50, 500)).group_by(lambda x: x % 5) # create n observables
print(xx)

Thing is this returns an observable group object:
<rx.core.anonymousobservable.AnonymousObservable object at 0xb631bb10>

So for any given n how would I perform the same combine_latest operation on this object?
I understand that in this stylized example the observables will emit at the same rate, but I need the solution to generalize to different emission frequencies as per the explicit example at the top.
Given that the structure of RxPY and RxJS are so similar, I am happy to consider analogous RxJS answers.

A: Edit: If the number of groups is finite and pretty small, this is a cleaner way you can go about this without sacrificing much performance:
groups$.scan(lambda prev, group$: [
               Observable.combineLatest(prev + [group$])\
                         .map(lambda nest: nest[0] + [nest[1]] if len(nest) == 2 else nest)
             ], [])

Here, scan builds an Observable that emits any time any group emits. It does this by nesting the emissions from the list of groups in the previous iteration. Because prev is an observable of arrays, we flatting using map with list concat. The arrays wrapping the scan results accommodate the base case of the first group.

Edit: I realized a little after writing the answer below the line that its behavior, which doesn't emit any items until all streams have emitted one more, is probably not wanted. Off the top of my head, the shortest but certainly not the cleanest solution is to stash the latest values and start each stream with them, like so:
def group_combine(groups$):
  last = []

  def mutate_last(v): # too bad this isn't JS :/
    last = v

  return groups$.scan(lambda streams, next_stream: streams + [next_stream], [])\
                .switch_map(lambda streams: Observable.combine_latest(
                  [stream.start_with(last[i]) if i < len(last) else stream\
                     for i, stream in enumerate(streams)]
                ))\
                .for_each(mutate_last)

Give this a try:
// groups$ = x.group_by(...)
groups$.scan(lambda streams, next_stream: streams + [next_stream], [])\
       .switch_map(lambda streams: Observable.combine_latest(streams))\
       .subscribe(lambda values: ...)

First, we accumulate the group streams into a growing list, then we keep switching to the combine_latest over that list.


text:
Q: How to copy a List to a multidimensional array with a for-loop? I'm working with 3D coordinates. I have them all saved into a List, but to keep working with them, I need to have them into a multidimensional array (float[,]).
My list looks like this:
<Coordinates> hp_List = new List<Coordinates>();

public class Coordinates
{
    public float x { get; set; }
    public float y { get; set; }
    public float z { get; set; }
}

I tried the following code:
int R = hp_List.Count();
float[,] hp_array = new float[R, 3];
for(int i=0; i<R; i++)
{
    for (int j = 0; j < hp_List.Count; j++)
    {
        hp_array[i, 0] = hp_List[j].x;
        hp_array[i, 1] = hp_List[j].y;
        hp_array[i, 2] = hp_List[j].z;
    }
}

and I also tried this other way:
for(int i=0; i<R; i++)
{
    foreach (Coordinates hp_position in hp_List)
    {
        hp_array[i, 0] = hp_position.x;
        hp_array[i, 1] = hp_position.y;
        hp_array[i, 2] = hp_position.z;
    }
}

I expected the following output:
589,5  -75,4  238,4
46,2   173,2  70,9
45,7   173,4  70,9
160,9  75,5   75,4
160    76     75,2
156,1  83,9   73,6

My actual output is
156,1
83,9
73,6
156,1
83,9
73,6
156,1
83,9
73,6
156,1
83,9
73,6
156,1
83,9
73,6
156,1
83,9
73,6

which as you can see is the last element of my list.
I'm not sure where my mistake is.

A: Both loops are iterating through all the elements in the list
for(int i=0; i<R; i++)
{
    for (int j = 0; j < hp_List.Count; j++)
    {
    ////
    }
}

Don't forget that R == hp_List.Count. That is why all the rows in the array contain the last three elements of the list.
Try discarding the inner loop.
for(int i=0; i<R; i++)
{
    hp_array[i, 0] = hp_List[i].x;
    hp_array[i, 1] = hp_List[i].y;
    hp_array[i, 2] = hp_List[i].z;
}

A:         List<Coordinates> hp_List = new List<Coordinates>
        {
            new Coordinates
            {
                 x = 1,
                 y = 2,
                 z = 3
            },
            new Coordinates
            {
                 x = 4,
                 y = 5,
                 z = 6
            }
        };

        int R = hp_List.Count();
        float[,,] hp_array = new float[R, 1, 3];
        for (int i = 0; i < R; i++)
        {
            for (int j = 0; j < 1; j++)
            {
                hp_array[i, j, 0] = hp_List[j].x;
                hp_array[i, j, 1] = hp_List[j].y;
                hp_array[i, j, 2] = hp_List[j].z;
            }
        }
        Console.WriteLine(string.Format("X Y Z"));
        for (int i =  0; i< R; i++)
        {
            Console.WriteLine(string.Format("{0} {1} {2}", hp_array[i, 0, 0], hp_array[i, 0, 1], hp_array[i, 0, 2]));
        }
        Console.Read();

Out Put
X Y Z
1 2 3
4 5 6


text:
Q: Multiple first or create in sidekiq creates multiple records instead of updating it When a user is created, I am trying to add 1 to the count if a record exists, or create a record with count: 1 if not.
I have something like this:
class User < ApplicationRecord
  after_commit :record, on: :create

  def record
    SomeWorker.perform_async(id)
  end
end

After a user is created, SomeWorker will fire in sidekiq, and will call something like:
class SomeWorker
  include Sidekiq::Worker

  def perform(id)
    Record.where(some_conditions).first_or_create()
  end
end

It works like charm when I am not using sidekiq and just call it right after a user is created. However, when I seed data that creates 10 users, I expect to create 1 record with count: 10, but it creates 10 records with count: 1.
Any ideas what is happening and how I can fix it?

A: It's the classic race condition. Please note that "Sidekiq is multithreaded so your Workers must be thread-safe.". All your workers are running in parallel and none of them initially finds a matching record in where and ends up creating the new record with count 1.
I will advice to instead create/find the record beforehand and send it's id for incrementing the count value. Though, I'm not sure why you are using Sidekiq to offload a basic UPDATE operation.
class User < ApplicationRecord
  after_commit :record, on: :create

  def record
    record = Record.create_with(count: 0).find_by(some_conditions)
    SomeWorker.perform_async(record.id)
  end
end

class SomeWorker
  include Sidekiq::Worker

  def perform(id)
    Record.find(id).increment!(:count)
  end
end

Also, please note that increment! is not suitable for concurrency either, but it should work in your case.
a = Record.first #<Record id: 1, count: 1>
b = Record.first #<Record id: 1, count: 1>
a.increment!(:count) #<Record id: 1, count: 2>
b.increment!(:count) #<Record id: 1, count: 2> ## SHOULD BE 3
b.reload #<Record id: 1, count: 3> It's actually three, but object was stale on update.

SQL fires the query below which bumps the value from the last set value.
UPDATE `records` SET `count` = COALESCE(`parent_id`, 0) + 1 WHERE `records`.`id` = 1


text:
Q: Git Edit Config File on Mac I am trying to remove URL's that are in my git global config file and have read to just edit the file in the terminal. How I only see ways on windows to edit it?
git config --global --edit

Pulls up the info but how to edit it on a mac in the terminal?

A: If you see in this link below:-
How to configure default editor for GIT in various Operating Systems.
They have specified various editors like TextEdit in macOS, NotePad++ in Windows, and Sublime for Ubantu.
If the editors are configured in your System's Environment Variables, it will be easier to set it up, for this is the command-line option :- [shell (Bourne, Korn) or zsh or DOS].
Check this with the following commands (mac OS) :-
$ git config --global core.editor "open --wait-apps --new -e"
$ git commit -a


text:
Q: QFile/FILE* : How to properly close the handle? I need to open files with QFile and QString for multilingual without hair pulling. But I also need to manage the data of those files through the std::stream API. As many suggest, I used std::fstream stdFile(fdopen(qtFile.handle(), mode)); to do so.
However I hit a problem when it recurring operations. After a specific amount of file handling, the application crashes.
The following code can reproduce the crash:
int fileOperationCount = 0;
while (true)
{
    QFile qtFile("plop.txt");
    qtFile.open(QIODevice::ReadOnly);
    std::ifstream file = std::ifstream(fdopen(qtFile.handle(), "rb"));

    if (!file.good())
        throw std::exception();
    file.seekg(0, file.beg);
    if (!file.good())
        throw std::exception(); //Will ALWAYS trigger at fileOperationCount = 509

    qtFile.close();

    fileOperationCount++;
}

The 509th will crash after the seekg. It also happens if I were to manipulate hundreds of different files. It will still crash the 509th time I try to read a file, any file.
Any idea what I'm doing wrong ?

A:    int fileOperationCount = 0;
    while (true)
    {
        std::ifstream file ("plop.txt",std::ios::in);

        if (!file.good())
            throw std::exception();
        file.seekg(0, file.beg);
        if (!file.good())
            throw std::exception();

        file.close();
        fileOperationCount++;
    }

this version works if the file exists, if it doesn`t file.good() is false due to eof (I think). If you want to use Qt for translation you can use
            std::ifstream file (QObject::tr("plop.txt"),std::ios::in);

or if the function is inside a QObject use just tr("..") for better context.


text:
Q: Some trivial questions on Tate's conjectures X is a smooth projective variety over a number field k. Write $\bar{X}$ for $X_{\bar{k}}$. Consider the cycle class map on Neron-Severi group of divisors: $cl_l: NS(\bar{X})\hookrightarrow H^2_{et}(\bar{X}, Q_l(1))$. Then Tate's conjecture 1 predicts  $cl_l(NS(\bar{X}))\otimes_Q Q_l=H^2_{et}(\bar{X}, Q_l(1)$ . Edit: should be $cl_l(NS(\bar{X}))\otimes_Q Q_l=H^2_{et}(\bar{X}, Q_l(1)$. (See e.g. Tate, "conjectures on algebraic cycles in l-adic cohomology", Motives, Jannsen et, proceeding of symposia vol55.)
Comment for edit: Consider a product of two modular elliptic curves $E_1$ and $E_2$ over Q. Then it was proved in the following cited paper by Rosen and Silverman that their product satisfies both Tate's conjectures. However, we know the $NS(\bar{E_1}\times \bar{E_2})=2, 3 or 4$. On the other hand, by Kunneth formula $H^2(E_1\times E_2(C), C)=C^6$, so by the comparison theorem the algebraic cycles have no hope of generating the whole space in $H^2_{et}(\bar{E_1}\times \bar{E_2}, Q_l(1))$. One will have to look at $H^2_{et}(\bar{E_1}\times \bar{E_2}, Q_l(1))^{G_Q}$ instead.
Moreover, there is a stronger conjecture let's call it Tate's 2:
consider the Hasse-Weil L function defined by the Galois representation of $G_k:=Gal(\bar{k}, k)$ on $H^2_{et}(\bar{X}, Q_l(1))$. For notational convenience we denote the latter as $V_l(1)$. Conjecture 2 says that: $-ord_{s=2}L_2(\bar{X}, s)=dim_{Q_l}Hom_{Gal(k/Q)}(1, V_l(1))$.
Question 1. (Edit: to keep track my original notation I'll leave question 1 and 2 still separated, but actually after editting I only have one question now.)
If X is a smooth projective variety over a finite field then conjecture 2 follows from conjecture 1, however over a number field I don't know if it still follows. In the article by Rosen and Silverman "on the rank of an elliptic surface" MR1626465, they proved conjecture 2 on rational surfaces over a number field. (Here conjecture 1 is known and I have no problem with that.) However I do not understand their proof.
Here is roughly how their argument goes:
Edit: for the speacial case when $Q_l\otimes cl_l(NS(\bar{X}))=H^2_{et}(\bar{X}, Q_l(1))$ before taking the Galois invariants of the latter,
Then $L_2(\bar(X),V_l(1), s)=L(G_k, NS(\bar{X})\otimes_Z Q, s)$. The latter is a classical (rather than motivic) Artin L function, and the order of poles at s=1 equals the Q-dimension of $G_k$-invariant of Neron-Severi space. My confusion is, if this line of argument would work, then isn't it ture in general that conjecture 1 would imply Edit: in this special case we would get conjecture 2 over a number field?
Question 2:
Note here we are only talking about divisors, i.e. 1-cocyles, so we don't need to worry about the difference between numerical equivelance and homological equivalence. Tate has shown $cl_l(NS(\bar{X}))\otimes Q_l\cong Q_lNS(\bar{X})$. (see prop 2.9, 2.10 from Tate's article in the above cited "motive" book. The following argument is mine, which might contain mistakes:) Therefore $dim_Q NS(\bar{X})=dim_{Q_l}V_l(1)$. Moreover, $dim_{Q_l} V_l(1)=dim_{Q_l}V_l$, by the compasison theorem, $dim_{Q_l}V_l=dim_C H^2_{singular}(\bar{X}(C), C)$. Therefore if I know $dim_Q NS(\bar{X})= H^2_{singular}(\bar{X}(C), C)$, then I would know conjecture 1 is true. (e.g. this happends when $H^1(X(C))=0$. Edit: and say $H^2(X, O_X)=0$.) This seems a very strong result, but I've never seen it anywhere, so my feeling is that there has to be something wrong with this.