text:
Q: Converting Excel to Gsheet and then importrange them without needing Auth I receive files in .xlsx which is updated about daily.  To use the importrange function I need to have the xlsx file converted to gSheet. I've completed the conversion as per drive API
function importXLS(){
  var folderBId = "redacted"; // This is the folder where we will save the gsheet converted files

  fileID = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("DataFile").getValue();

  var xFile = DriveApp.getFileById(fileID);
  var name = xFile.getName();
  if (name.indexOf('.xlsx')>-1){
    var ID = xFile.getId();
    var xBlob = xFile.getBlob();
    var newFile = {
      title : name+'_converted',
      parents: [{id: folderBId}] //  Added
    };
    file = Drive.Files.insert(newFile, xBlob, {
      convert: true
    });
    SpreadsheetApp.getActiveSpreadsheet().getRangeByName("GDatafile").setValue(file.id); // **Notes below**
    // Drive.Files.remove(ID); // Added // If this line is run, the original XLSX file is removed. So please be careful this.
  }

So I save the new gSheet ID in my spreadsheet so I can use importrange to import it. But because it's a new gsheet file for every update, and not an overwritten version of the old one, I need to explicitly give access to the file.  The point here is to automate, and having to click "allow" for every time you access it is not ideal.
Can I somehow (since I have the fileID at my disposal here anyway, and the spreadsheet that will want to access it) allow access right there? Or is there a way that I can set up this 'converting' code to overwrite the old gsheet (so that I only have to allow access once).

A: This worked for me:
function importXLS(){
  var folderBId = "redacted"; // This is the folder where we will save the gsheet converted files

  fileID = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("DataFile").getValue();

  var xFile = DriveApp.getFileById(fileID);
  var name = xFile.getName();

  if (name.indexOf('.xlsx')>-1){
    var ID = xFile.getId();
    var xBlob = xFile.getBlob();
    var newFile = {
      title : name+'_gsheet',
      parents: [{id: folderBId}]
    };
    var GDataFile = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("GDatafile").getValue();

    if (GDataFile == "" ){
      file = Drive.Files.insert(newFile, xBlob, {
        convert: true
      })
      Logger.log("New File Created: " + file.id);
      SpreadsheetApp.getActiveSpreadsheet().getRangeByName("GDatafile").setValue(file.id);
    }
    else{
      file = Drive.Files.update(newFile,GDataFile,xBlob); // <--- this is the update code
      Logger.log("File in theory updated... " + GDataFile);
    }
    // Drive.Files.remove(ID); // Added // If this line is run, the original XLSX file is removed. So please be careful this.
  }

}


text:
Q: VS Code not showing auto-complete suggestions for Eigen I recently downloaded Eigen 3.4.0. I have added it locally to the project I created. However, I am getting the red squiggly lines with the drag-over error - namespace "Eigen" has no member "VectorXd".
I tried adding the path of Eigen to c_cpp_properties.json, settings.json as well as tasks.json to no avail. I was expecting to get the auto-complete suggestions but to no avail.
c_cpp_properties.json
{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**",
                "eigen-3.4.0/**"
            ],
            "defines": [],
            "macFrameworkPath": [
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
            ],
            "compilerPath": "/usr/bin/clang++",
            "cStandard": "c11",
            "cppStandard": "c++17"
        }
    ],
    "version": 4
}

settings.json
{
    "files.associations": {
        "__bit_reference": "cpp",
        "__bits": "cpp",
        "__config": "cpp",
        "__debug": "cpp",
        "__errc": "cpp",
        "__hash_table": "cpp",
        "__locale": "cpp",
        "__mutex_base": "cpp",
        "__node_handle": "cpp",
        "__nullptr": "cpp",
        "__split_buffer": "cpp",
        "__string": "cpp",
        "__threading_support": "cpp",
        "__tree": "cpp",
        "__tuple": "cpp",
        "array": "cpp",
        "atomic": "cpp",
        "bitset": "cpp",
        "cctype": "cpp",
        "chrono": "cpp",
        "clocale": "cpp",
        "cmath": "cpp",
        "compare": "cpp",
        "complex": "cpp",
        "concepts": "cpp",
        "cstdarg": "cpp",
        "cstddef": "cpp",
        "cstdint": "cpp",
        "cstdio": "cpp",
        "cstdlib": "cpp",
        "cstring": "cpp",
        "ctime": "cpp",
        "cwchar": "cpp",
        "cwctype": "cpp",
        "deque": "cpp",
        "exception": "cpp",
        "initializer_list": "cpp",
        "ios": "cpp",
        "iosfwd": "cpp",
        "iostream": "cpp",
        "istream": "cpp",
        "limits": "cpp",
        "list": "cpp",
        "locale": "cpp",
        "map": "cpp",
        "memory": "cpp",
        "mutex": "cpp",
        "new": "cpp",
        "optional": "cpp",
        "ostream": "cpp",
        "queue": "cpp",
        "ratio": "cpp",
        "set": "cpp",
        "sstream": "cpp",
        "stdexcept": "cpp",
        "streambuf": "cpp",
        "string": "cpp",
        "string_view": "cpp",
        "system_error": "cpp",
        "tuple": "cpp",
        "type_traits": "cpp",
        "typeinfo": "cpp",
        "unordered_map": "cpp",
        "variant": "cpp",
        "vector": "cpp",
        "algorithm": "cpp"
    },

    "C_Cpp.default.includePath": [
        "${workspaceFolder}/**",
        "eigen-3.4.0/**"
    ],

    "C_Cpp.intelliSenseEngine": "default",

    "python.terminal.activateEnvironment": false
}

EDIT: The code compiles and runs absolutely fine through the terminal. The problem is purely with getting the auto-suggestions.
EDIT 2: The answer which was suggested does not answer my question. I have already added the path to includePath and <Eigen/Dense> is recognised. However, intelliSense does not give auto-suggestions for Eigen. My problem is specific to Eigen.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert .doc/.docx documents to .odt (Open document text) and vice versa using java. Is there any java library which can be used for converted Microsoft Word files (doc/docx) to Open Document Text format(.odt) formats. Free library would be preferable.

A: I believe everything you need is in this post: http://angelozerr.wordpress.com/2012/12/06/how-to-convert-docxodt-to-pdfhtml-with-java/
For instance:

JODConverter : JODConverter automates conversions between office
  document formats using OpenOffice.org or LibreOffice. Supported
  formats include OpenDocument, PDF, RTF, HTML, Word, Excel, PowerPoint,
  and Flash. It can be used as a Java library, a command line tool, or a
  web application.

A: I don't know about any libraries that do it directly, but it should be relatively easy to exact the bits you're interested from a .docx using poi:
http://poi.apache.org/
and then write them to an ODT format using ODFDOM:
http://incubator.apache.org/odftoolkit/odfdom/index.html
This should be relatively straightforward for simple documents, but if your use case calls for complex doucments containing pictures etc, this might become a LOT harder.
Anyway, hope this helps at least some ;)


text:
Q: export er diagram to sql script in mysql workbench changes LONG to MEDIUMTEXT I have one table in my ER diagram and I am using Export => Forward Engineer Mysql Create Script option to generate SQL Script from this ER diagram in mysql workbench

The output like this
-- -----------------------------------------------------
-- Table `mydb`.`users`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`users` (
  `user_id` MEDIUMTEXT NOT NULL ,
  `username` VARCHAR(45) NULL ,
  `password` VARCHAR(45) NULL ,
  PRIMARY KEY (`user_id`) )
ENGINE = InnoDB;

USE `mydb` ;

In ER diagram the type of user_id is LONG, but it in output script it is MEDIUMTEXT.
I don't understand what's wrong. Please help.


text:
Q: Android exception android.app.IntentReceiverLeaked I am using a BroadcastReceiver to monitor the battery power. I referred this and my code is
public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                        status == BatteryManager.BATTERY_STATUS_FULL;

    int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
}

}
and added this in my manifest
  <receiver android:name=".PowerConnectionReceiver">
  <intent-filter>
    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
  </intent-filter>
</receiver>

It works but in the onReceive, intent doesn't has any value in it. And when I try to start an activity in onReceive, app stops and returns the following error.
android.app.IntentReceiverLeaked: Activity com.example.batterycharging.Activity.MainActivity has leaked IntentReceiver com.example.batterycharging.Activity.MainActivity$1@b7548490 that was originally registered here. Are you missing a call to unregisterReceiver()?
        at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:756)
        at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:551)
        at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:800)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:787)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:781)
        at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:318)
        at com.example.suresh.batterycharging.Activity.MainActivity.onCreate(MainActivity.java:40)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
        at android.app.ActivityThread.access$1500(ActivityThread.java:117)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:130)
        at android.app.ActivityThread.main(ActivityThread.java:3683)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:507)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
        at dalvik.system.NativeStart.main(Native Method)

I don't know how to do this. Can anyone please help me to detect the battery status. Thanks in advance.
Here is the MainActivity.java class
package com.example.batterycharging.Activity;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.example.suresh.batterycharging.R;

public class MainActivity extends ActionBarActivity {

    /*private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        //When Event is published, onReceive method is called
        public void onReceive(Context c, Intent i) {
            //Get Battery %
            int level = i.getIntExtra("level", 0);
            //Find the progressbar creating in main.xml
            ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
            //Set progress level with battery % value
            pb.setProgress(level);
            //Find textview control created in main.xml
            TextView tv = (TextView) findViewById(R.id.textfield);
            //Set TextView with text
            tv.setText("Battery Level: " + Integer.toString(level) + "%");
        }

    };*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        registerReceiver(mBatInfoReceiver, new IntentFilter(
//                Intent.ACTION_BATTERY_CHANGED));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

A: You are registering a BroadcastReceiver at line 40 of MainActivity.
You need to unregisterReceiver(...) in onPause().
You need to either register the BroadcastReceiver in your AndroidManifest.xml file or with registerReceiver(...). You shouldn't need to do both.

A: I am not sure it will solve your issue but try to unregister before destroy.
private final BroadcastReceiver mybroadcast = new PowerConnectionReceiver();
    @Override
    public void onPause() {
        unregisterReceiver(mybroadcast);

    }

can you add these lines in onCreate() method
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = this.registerReceiver(null, ifilter);

and
At Last of your broad cast receiver for testing purpose.
Toast.makeText(context, isCharging+"/"+status+"/"+chargePlug+"/"+acCharge+"/"+usbCharge+"", Toast.LENGTH_LONG).show();

A: You need to unregister the receiver you have registered in the Activity/Fragment.
You should do it in the onStop() or onDestroy() method of your Activity/Fragment.
In an activity call :
unregisterReceiver(RECEIVER_NAME);

In a fragment call :
getActivity().unregisterReceiver(RECEIVER_NAME);

Also, it would be a good practice to check if your receiver is not null for unregistering it.


text:
Q: TinyMce allow HTML Tags i got a problem using html tags in TinyMce.
I've tried different things to get these done.
The TinyMce Docu say's
Use [] to include all elements and all attributes.
But it didn't work.
Here is the code:
tinymce.init({
    selector: ".mytextarea",
    theme: "modern",
    language: "de",
    plugins : 'advlist autolink link images lists charmap print preview jbimages',
    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image jbimages",
    relative_urls: true,
    valid_elements: '+*[*]',
});

I want some bootstrap elements in it (like  and so on)
Thanks a lot my friends =)

A: Due to the fact that tinymce uses its own iframe with own head, html and body html element - you may not use those elements in your content.
Update: Here is my tinymce base config
plugins: 'paste,searchreplace,style',    // and some more ....

dialog_type : "modal",

// Override inline_styles setting to force TinyMCE to produce deprecated contents
inline_styles: false,

// Theme options
theme_advanced_buttons3 : "",
theme_advanced_buttons4 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : false,

relative_urls: false,

gecko_spellcheck: true,

button_tile_map: true,

// disable drag und drop
disable_drag: true,

indentation: "0px",

// No resize handle an the editor itself
resize: false,

//turn on/off the inline resizing controls of tables and images in Firefox/Mozilla
object_resizing: false,
paste_strip_class_attributes : "none",
paste_remove_styles: true,
paste_convert_middot_lists: false,

// Default ab 3.0.1
forced_root_block: 'p',

// All characters will be stored in non-entity form except these XML default entities: & < > "
entity_encoding: "raw",

// This option controls if invalid contents should be corrected before insertion in IE. This option is disabled by default since it might be a bit slow.
fix_nesting: true,

// This option should contain a comma separated list of element names to exclude from the content. Elements in this list will be removed when TinyMCE executes a cleanup.
invalid_elements: "strong,em,div",

// The valid_elements option defines which elements will remain in the edited text when the editor saves.
valid_elements: "@[id|class|title|style],"
+ "a[name|href|target|title|alt],"
+ "#p,-ol,-ul,-li,br,img[src|unselectable],-sub,-sup,-b,-i,-u,"
+ "-span[data-mce-type],hr",

valid_child_elements : "body[p,ol,ul]"
+ ",p[a|span|b|i|u|sup|sub|img|hr|#text]"
+ ",span[a|b|i|u|sup|sub|img|#text]"
+ ",a[span|b|i|u|sup|sub|img|#text]"
+ ",b[span|a|i|u|sup|sub|img|#text]"
+ ",i[span|a|b|u|sup|sub|img|#text]"
+ ",sup[span|a|i|b|u|sub|img|#text]"
+ ",sub[span|a|i|b|u|sup|img|#text]"
+ ",li[span|a|b|i|u|sup|sub|img|ol|ul|#text]"
+ ",ol[li]"
+ ",ul[li]",

formats: {
    bold : {inline : 'b' },
    italic : {inline : 'i' },
    underline: { inline: 'u' }
},


text:
Q: Oracle Sql trigger not working I have a very simple trigger, that prints out the username and date when a new row is inserted into the users table. But after it successfully compiled, the trigger didn't get triggered (there was no output in the dbms window). So, I simplified my code until I got this:
CREATE OR REPLACE TRIGGER logger
AFTER INSERT ON USERS
BEGIN
   DBMS_OUTPUT.PUT_LINE('User added with name:');
END;

If I run the code in the SQL worksheet (from BEGIN to END), I can see the output, but not when I try to use the trigger. Where is the problem?

A: There are two options, one is that the trigger is not firing, the other is that it is, but you're not seeing the output.

*

*Assuming you're working in a console program like sqlplus, make sure to do SET SERVEROUTPUT ON before inserting your row.

*If that doesn't fix it, then make sure the trigger is firing. Try creating a simple table:
CREATE TABLE logtable ( msg VARCHAR2(30 CHAR));
Next, add this to your trigger,
INSERT INTO logtable( msg ) VALUES ( 'trigger fired' );

Then, try your insert again.


text:
Q: ASIC design - combinational logic I had an interview a few days back and this was the question they asked me in one of the rounds:

A mux which gives output a when select line is 1 and b when it is 0. The output is represented as C. This has to be implemented with and and not gates only.

I got it almost but was not sure how the output is received finally in combinational ckt. It is a very simple thing I missed here. I gave the select line to an and gate and input a and the select line and the input b through a not gate to another and gate so I got the output as A and B but how can we have one output alone? either a or b?

A:  C = (A and not(S)) or (B and S)
   = not(not(A and not(S)) and not(B and S))

A: A input 1,
B input 2,
S input select line,
C output,
C = (A & S) | (A & ~S);

Its simple bro!


text:
Q: How to use wildcards in systemd services? I'm trying to remove all files in a specific directory using systemd at reboot.
Here is my /lib/systemd/system/delete-at-boot.service file (root, access 644):
[Unit]
Description=Remove content of test folder at boot

[Service]
ExecStart=/bin/rm /home/user/test/*

[Install]
WantedBy=multi-user.target

When I run /bin/rm /home/user/test/* manually the deletion works fine but when I start the process, I can see my files are not deleted.
● delete-at-boot.service - Remove content of test folder at boot
   Loaded: loaded (/lib/systemd/system/delete-at-boot.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Fri 2019-08-02 18:21:09 UTC; 7s ago
  Process: 5460 ExecStart=/bin/rm /home/user/test/* (code=exited, status=1/FAILURE)
 Main PID: 5460 (code=exited, status=1/FAILURE)

Aug 02 18:21:09 tegra-ubuntu systemd[1]: Started Remove content of test folder at boot.
Aug 02 18:21:09 tegra-ubuntu rm[5460]: /bin/rm: cannot remove '/home/user/test/*': No such file or directory
Aug 02 18:21:09 tegra-ubuntu systemd[1]: delete-at-boot.service: Main process exited, code=exited, status=1/FAILURE
Aug 02 18:21:09 tegra-ubuntu systemd[1]: delete-at-boot.service: Unit entered failed state.
Aug 02 18:21:09 tegra-ubuntu systemd[1]: delete-at-boot.service: Failed with result 'exit-code'.

I believe the problem is related to the "*" But I'm not sure what is the best way to replace it.

A: Wildcards are not supposed to be used like that in a systemd service. change your ExecStart to:
ExecStart=/bin/sh -c '/bin/rm /home/user/test/*'

Now it should perform the action correctly.


text:
Q: Compatible versions of AUCTeX and Ghostscript on Mac When I run preview-at-point (in emacs), I get a minus (do not enter) sign rather than the figure.
I followed the suggestion here and downloaded the development version of AucTeX. The problem remains.
Is there a way at this time to resolve this issue? I am on OSX, have Ghostscript 9.04, and tried AucTeX 11.86 as well as the development version.
Edit
For the sake of those consulting the archives, I have not resolved this issue. Perhaps it's best to just wait for a new release of auctex.

A: You need to use Ghostscript version 8.71 (32bit version) for it to work. It can be downloaded here.


text:
Q: How do I copy a directory in python? I have a code that copy folders and files from a given path that includes  pdf files and word files and folder that includes pdf files also.
what i need is to copy each one to a different destination  mean

*

*the pdf file to  destination a

*the word file to  destination b

*the folder & subdiretories a destination c

the problem is that the destination a will have the pdf files and the subdirectories files that are in the folder. yet the  destination c also will have the folder copied correctly.
so the problem is with the destination a
This is the structure I have in I:
I:
├── file1.doc
├── file1.pdf
├── file2.pdf
└── folder1
    ├── file3.pdf
    └── file4.pdf

Result must be:
├── A
│   ├── file1.pdf
│   └── file2.pdf
├── B
│   └── file1.doc
└── C
    └── folder1
        ├── file3.pdf
        └── file4.pdf

The outcome for now is :
├── A
│   ├── file1.pdf
│   ├── file2.pdf
│   ├── file3.pdf
│   └── file4.pdf
├── B
│   └── file1.doc
└── C
    └── folder1
        ├── file3.pdf
        └── file4.pdf

And this is the code I'm using:
import os
import shutil
from os import path

src = "I:/"
src2 = "I:/test"

dst = "C:/Users/xxxx/Desktop/test/"
dst2 = "C:/Users/xxxxx/Documents/"
dst3 = "C:/Users/xxxxx/Documents/Visual Studio 2017"

def main():
    copy()

def copy():
    i = 0
    j = 0
    for dirpath, dirnames, files in os.walk(src):

        print(f'Found directory: {dirpath}')
        # for file_name in files:
        if len(dirnames)==0 and len(files)==0:
                print("this directory is empty")
        else:
            print(files)

        for name in files:

            full_file_name = os.path.join(dirpath, name)
            #check for pdf extension
            if name.endswith("pdf"):
                i=i+1
                #copy files
                shutil.copy(full_file_name, dst2)
                #check for doc & docx extension
            elif name.endswith("docx") or name.endswith("doc"):
                j=j+1
                #copy files
                shutil.copy(full_file_name, dst3)
                # print(i,"word files done")
        print("{0} pdf files".format(i))
        print("{0} word files".format(j))

    # except Exception as e:
        # print(e)
    if os.path.exists(dst):
        shutil.rmtree(dst)
        print("the deleted folder is :{0}".format(dst))
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))
    else:
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))

if __name__=="__main__":
    main()

A: Here is a simple solution in Python 3.4+ (because of pathlib):
from pathlib import Path

src = Path('I:/')

pdfs = Path('I:/test')
docs = Path('C:/Users/xxxxx/Documents')
dirs = Path('C:/Users/xxxxx/Documents/Visual Studio 2017')

suffixes = {
    'docs': ['.doc', '.docx'],
    'pdfs': ['.pdf']
}

def main():
    for o in src.glob('*'):
        if o.is_dir():
            o.rename(dirs / o.name)

        if o.is_file():
            if o.suffix in suffixes['docs']:
                o.rename(docs / o.name)
            elif o.suffix in suffixes['pdfs']:
                o.rename(pdfs / o.name)

if __name__ == '__main__':
    main()


text:
Q: Bulk insert with SQLAlchemy ORM and return primary keys I am trying to insert a list of dictionaries into a table using bulk_save_objects or bulk_insert_mappings. Is there any way I can get the list of objects with primary key for each entry?
try:
    cycle_object_list = []
    for cycle in cycle_list:
        period = Period()
        for k, v in cycle.items():
            setattr(period, k, v)
        cycle_object_list.append(period)

    db.session.bulk_save_objects(cycle_object_list)
    db.session.commit()
    print(cycle_object_list)
except Exception:
    db.session.rollback()
    raise
finally:
    db.session.close()

I am expecting something like [Period.49, Period.50, Period.51]
But the actual result is [Period.None, Period.None, Period.None]

A: The docs

The objects as given are not added to the session and no additional state is established on them, unless the return_defaults flag is also set, in which case primary key attributes and server-side default values will be populated.

So this might work:
try:
    cycle_object_list = []
    for cycle in cycle_list:
        period = Period()
        for k, v in cycle.items():
            setattr(period, k, v)
        cycle_object_list.append(period)

    db.session.bulk_save_objects(cycle_object_list, return_defaults=True)
    db.session.commit()
    print(cycle_object_list)
except Exception:
    db.session.rollback()
    raise
finally:
    db.session.close()


text:
Q: Go Back To Main Menu Keeps Looping Menus When the program first starts I can select any option from the main menu successfully. However, when I select the go back to main menu option from any of the submenus it'll go back to the main menu but no matter what option I press again afterwards it will continue to loop that menu. Only allowing me to select the go back to main menu option. How do I reset the selection to where it won't continue to loop? I have shortened the code as best as possible so that it can still compile but also demonstrate the error. Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main()
{
    //declare all working variables: mOption, FManOption, COption...etc...
    int MOption = 0;
    int FManOption = 0;
    int FOption = 0;
    int COption = 0;
    int userChoice = 0;

    //declarations for all arrays of struct
    //declare a pointer to an array of struct using malloc() for fisherman, fish, catch

    //process:
    printf("Please select 1 to start the program or 0 to quit: ");
    scanf("%d", &userChoice);
    while(userChoice != 1 && userChoice != 0)
    {
        printf("Invalid selection! Please type a 1 or a 0: ");
        scanf("%d", &userChoice);
    }//end (userChoice != 1 && userChoice != 0)
    if(userChoice != 1)
        printf("Thank you for wasting my time! Have a great day!");
    else
    {

      MOption = mainMenu();

        switch(MOption)
        {
            case 1: FManOption = FishermanMenu();
                    while(FManOption != 3)
                    {
                        switch(FManOption)
                        {
                            case 1: getFisherman();//get a fisherman
                                    //count fisherman
                                    break;
                            case 2: //prompt for a ssn, validate, search
                                    //if found display everything about this fisherman
                                    break;
                            case 3: FManOption = mainMenu();

                                    //reset FManOption
                                    break;
                            default: printf("\nInvalid selection! Please select from one of the menu options\n");
                        }//end switch(FManOption)
                    }//end while(FManOption != 3)
                    break;
        }
    }
}

int mainMenu()
{
    int Option;

    printf("\n-------Welcome to the Fishing Tournament Main Menu!-------\n");
    printf("1 - Fisherman menu\n");
    printf("2 - Fish menu\n");
    printf("3 - Tournament(Catch) menu\n");
    printf("4 - Close Tournament (determine winner)\n");
    printf("5 - Quit Program\n\n");
    printf("Please select a menu option: ");
    scanf("%d", &Option);
    if(Option > 5 || Option < 1)
        do /* check scanf() return value for input errors */
        {
            printf("\nInvalid selection! Please select from one of the menu options\n");
            printf("1 - Fisherman menu\n");
            printf("2 - Fish menu\n");
            printf("3 - Tournament(Catch) menu\n");
            printf("4 - Close Tournament (determine winner)\n");
            printf("5 - Quit Program\n\n");
            printf("Please select a menu option: ");
            scanf("%d", &Option);
        }
        while(Option > 5 || Option < 1);

    return Option; /* finally return the final correct option */
}//end main menu

int FishermanMenu()
{
    int ManOption;
    printf("\n-------Fisherman Menu-------\n");
    printf("1 - Register fisherman\n");
    printf("2 - Search fisherman\n");
    printf("3 - Go back to main menu\n");
    printf("Please select a menu option: ");
    scanf("%d", &ManOption);
    if(ManOption > 5 || ManOption < 1)
        do /* check scanf() return value for input errors */
        {
            printf("\nInvalid selection! Please select from one of the menu options\n");/* handle input error */
            printf("1 - Register fisherman\n");
            printf("2 - Search fisherman\n");
            printf("3 - Go back to main menu\n");
            printf("Please select a menu option: ");
            scanf("%d", &ManOption);
        }
        while(ManOption > 5 || ManOption < 1);
    return ManOption; /* finally return the final correct option */
}//end Fisherman Menu

A: This is relying on a feature called implicit function declarations; this is considered harmful and was removed in C99. One might rearrange the menus to be on top, or prototype the functions before calling them,
int mainMenu(void);
int FishermanMenu(void);

and change the implicit int parameter to a local variable that is returned,
int mainMenu(void) {
    int MOption;
...
}
int FishermanMenu(void) {
    int FManOption;
...
}

EDIT
Instead of figuring out the mess of switches that is only going to get worse to debug, let me suggest a change in application structure. This code could be a state machine without many changes, just return the next state from the function.
enum states {
    START, MAIN, FISHPERSON, REGISTER, SEARCH, FISH, CATCH, CLOSE, END
};

enum states StartMenu(void);
enum states MainMenu(void);
enum states FishermanMenu(void);
/* ... */

typedef enum states (*state_function)(void);
static const state_function states[] = { StartMenu, MainMenu,
    FishermanMenu, /*...*/0, 0, 0, 0, 0, /* END is actually 0 == NULL */0 };

int main(void)
{
    enum states state = START;
    while(states[state]) state = states[state]();
    return 0;
}

Then one returns the state from the menu,
enum states StartMenu(void) {
    int userChoice = 0;
    //process:
    printf("Please select 1 to start the program or 0 to quit: ");
    scanf("%d", &userChoice);
    while(userChoice != 1 && userChoice != 0)
    {
        printf("Invalid selection! Please type a 1 or a 0: ");
        scanf("%d", &userChoice);
    }//end (userChoice != 1 && userChoice != 0)
    if(userChoice != 1) {
        printf("Thank you for wasting my time! Have a great day!");
        return END;
    } else {
        return MAIN;
    }
}

To repeat less, instead of a while() {} consider a do {} while() on menus that display the information up front.

A: I figured it out. My professor was able to help me as he responded to my email later than usual. My problem was I needed to add a while loop for the entire set of menus with MOption = mainMenu(); and assign each menu option to their respective functions. Thank you all who responded I greatly appreciate your time! Here is the updated code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main()
{
    //declare all working variables: mOption, FManOption, COption...etc...
    int MOption = 0;
    int FManOption = 0;
    int FOption = 0;
    int COption = 0;
    int userChoice = 0;

    //declarations for all arrays of struct
    //declare a pointer to an array of struct using malloc() for fisherman, fish, catch

    //process:
    printf("Please select 1 to start the program or 0 to quit: ");
    scanf("%d", &userChoice);
    while(userChoice != 1 && userChoice != 0)
    {
        printf("Invalid selection! Please type a 1 or a 0: ");
        scanf("%d", &userChoice);
    }//end (userChoice != 1 && userChoice != 0)
    if(userChoice != 1)
    {
        printf("Thank you for wasting my time! Have a great day!\n");
        return 0;
    }
        while(MOption != 5)
        {

            MOption = mainMenu();
            switch(MOption)
            {
            case 1: FManOption = FishermanMenu();
                    while(FManOption != 3)
                    {
                        switch(FManOption)
                        {
                            case 1: //get a fisherman
                                    //count fisherman
                                    break;
                            case 2: //prompt for a ssn, validate, search
                                    //if found display everything about this fisherman
                                    break;
                            case 3: FManOption = mainMenu();
                                    //reset FManOption
                                    break;
                            default: printf("\nInvalid selection! Please select from one of the menu options\n");
                        }//end switch(FManOption)
                    }//end while(FManOption != 3)
                    break;
        }
    }
}

int mainMenu(MOption)
{
    printf("\n-------Welcome to the Fishing Tournament Main Menu!-------\n");
    printf("1 - Fisherman menu\n");
    printf("2 - Fish menu\n");
    printf("3 - Tournament(Catch) menu\n");
    printf("4 - Close Tournament (determine winner)\n");
    printf("5 - Quit Program\n\n");
    printf("Please select a menu option: ");
    scanf("%d", &MOption);
    if(MOption > 5 || MOption < 1)
        do /* check scanf() return value for input errors */
        {
            printf("\nInvalid selection! Please select from one of the menu options\n");
            printf("1 - Fisherman menu\n");
            printf("2 - Fish menu\n");
            printf("3 - Tournament(Catch) menu\n");
            printf("4 - Close Tournament (determine winner)\n");
            printf("5 - Quit Program\n\n");
            printf("Please select a menu option: ");
            scanf("%d", &MOption);
        }
        while(MOption > 5 || MOption < 1);

    return MOption; /* finally return the final correct option */
}//end main menu

int FishermanMenu(FManOption)
{
    printf("\n-------Fisherman Menu-------\n");
    printf("1 - Register fisherman\n");
    printf("2 - Search fisherman\n");
    printf("3 - Go back to main menu\n");
    printf("Please select a menu option: ");
    scanf("%d", &FManOption);
    if(FManOption > 5 || FManOption < 1)
        do /* check scanf() return value for input errors */
        {
            printf("\nInvalid selection! Please select from one of the menu options\n");/* handle input error */
            printf("1 - Register fisherman\n");
            printf("2 - Search fisherman\n");
            printf("3 - Go back to main menu\n");
            printf("Please select a menu option: ");
            scanf("%d", &FManOption);
        }
        while(FManOption > 5 || FManOption < 1);
    return FManOption; /* finally return the final correct option */
}//end Fisherman Menu

A: The problem is that you get stuck in this while loop forever:
while (FManOption != 3)
This loop only makes sense when you are inside the "Fisherman" sub-menu, but you should leave this loop and return the program to its previous state after the user selects "Go back to main menu".
Instead of attempting to write your code in such a way that the state of the program (e.g. whether the user is currently in the main menu or a sub-menu) is implied by the control flow of the program, it is often easier to store the program state explicitly in a variable, for example like this:
enum menu_state
{
    MENUSTATE_MAIN,
    MENUSTATE_FISHERMAN,
    MENUSTATE_FISH,
    MENUSTATE_TOURNAMENT_CATCH,
    MENUSTATE_CLOSE_TOURNAMENT
};

int main( void )
{
    [...]
    if (userChoice != 1)
        printf("Thank you for wasting my time! Have a great day!");
    else
    {
        enum menu_state ms = MENUSTATE_MAIN;

        for (;;) //infinite loop, equivalent to while(true)
        {
            switch ( ms )
            {
                case MENUSTATE_MAIN:
                    switch ( mainMenu() )
                    {
                        case 1:
                            printf( "opening fisherman menu\n" );
                            ms = MENUSTATE_FISHERMAN;
                            break;
                        case 2:
                            printf( "opening fish menu\n" );
                            ms = MENUSTATE_FISH;
                            break;
                        case 3:
                            printf( "opening tournament(catch) menu\n" );
                            ms = MENUSTATE_TOURNAMENT_CATCH;
                            break;
                        case 4:
                            printf( "opening close tournament menu\n" );
                            ms = MENUSTATE_CLOSE_TOURNAMENT;
                            break;
                        case 5:
                            //quit program
                            exit( EXIT_SUCCESS );
                        default:
                            fprintf( stderr, "unexpected error\n" );
                            exit( EXIT_FAILURE );
                    }
                    break;
                case MENUSTATE_FISHERMAN:
                    switch ( FishermanMenu() )
                    {
                        case 1:
                            printf( "Register fisherman not yet implemented.\n" );
                            break;
                        case 2:
                            printf( "Search fisherman not yet implemented.\n" );
                            break;
                        case 3:
                            //change program state back to main menu
                            ms = MENUSTATE_MAIN;
                            break;
                        default:
                            fprintf( stderr, "unexpected error\n" );
                            exit( EXIT_FAILURE );
                    }
                    break;
                case MENUSTATE_FISH:
                    printf( "Fish menu not yet implemented, returning to main menu.\n" );
                    ms = MENUSTATE_MAIN;
                    break;
                case MENUSTATE_TOURNAMENT_CATCH:
                    printf( "Tournament(catch) menu not yet implemented, returning to main menu.\n" );
                    ms = MENUSTATE_MAIN;
                    break;
                case MENUSTATE_CLOSE_TOURNAMENT:
                    printf( "Close tournament not yet implemented, returning to main menu.\n" );
                    ms = MENUSTATE_MAIN;
                    break;
                default:
                    fprintf( stderr, "unexpected error\n" );
                    exit( EXIT_FAILURE );
            }
        }
    }
}

It is also worth noting that your functions mainMenu and FishermanMenu contain unnecessary code duplicaton. You can simplify the function mainMenu the following way:
int mainMenu( void )
{
    for (;;) //repeat forever, until input is valid
    {
        int option;
        printf("\n-------Welcome to the Fishing Tournament Main Menu!-------\n");
        printf("1 - Fisherman menu\n");
        printf("2 - Fish menu\n");
        printf("3 - Tournament(Catch) menu\n");
        printf("4 - Close Tournament (determine winner)\n");
        printf("5 - Quit Program\n\n");
        printf("Please select a menu option: ");
        scanf("%d", &option);

        if ( 1 <= option && option <= 5 )
            return option;

        printf("\nInvalid selection! Please select from one of the menu options\n");
    }
}

However, it is important to always check whether the function scanf succeeded before attempting to use the result of scanf. This can be accomplished by checking the return value of scanf. Also, after using scanf, it is important to discard the input from the rest of the line. Otherwise, if the user for example enters "12dfghoh", then all subsequent calls to scanf will fail, because it won't be able to remove dfghoh from the input stream when trying to read a number.
Therefore, here is the code in which I check the return value of scanf and also discard all remaining input in the line:
int mainMenu( void )
{
    for (;;) //repeat forever, until input is valid
    {
        int option, c;

        printf("\n-------Welcome to the Fishing Tournament Main Menu!-------\n");
        printf("1 - Fisherman menu\n");
        printf("2 - Fish menu\n");
        printf("3 - Tournament(Catch) menu\n");
        printf("4 - Close Tournament (determine winner)\n");
        printf("5 - Quit Program\n\n");
        printf("Please select a menu option: ");
        if (
            scanf("%d", &option) == 1 && //make sure scanf succeeded
            1 <= option && option <= 5
        )
        {
            return option;
        }

        printf("\nInvalid selection! Please select from one of the menu options\n");

        //discard remainder of line, which may contain bad input
        //and prevent the next call of scanf to succeed
        do
        {
            c = getchar();
        }
        while ( c != EOF && c != '\n' );
    }
}

On the other hand, for line-based input, it would probably be better to use fgets instead of scanf, because then you don't have to deal with removing bad input from the input stream. See this link for further information:
A beginners' guide away from scanf()
Using the fgets function, the function mainMenu would look like this:
//NOTE: the following header must be added
#include <ctype.h>

int mainMenu( void )
{
    for (;;) //repeat forever, until input is valid
    {
        char buffer[1024], *p;
        long option;

        printf("\n-------Welcome to the Fishing Tournament Main Menu!-------\n");
        printf("1 - Fisherman menu\n");
        printf("2 - Fish menu\n");
        printf("3 - Tournament(Catch) menu\n");
        printf("4 - Close Tournament (determine winner)\n");
        printf("5 - Quit Program\n\n");
        printf("Please select a menu option: ");

        if ( fgets( buffer, sizeof buffer, stdin ) == NULL )
        {
            printf( "unexpected input error!\n" );

            //since this type of error is probably not recoverable,
            //don't try again, but instead exit program
            exit( EXIT_FAILURE );
        }

        option = strtol( buffer, &p, 10 );

        if ( p == buffer )
        {
            printf( "error converting string to number\n" );
            continue;
        }

        //make sure remainder of line contains only whitespace,
        //so that input such as "12dfghoh" gets rejected
        for ( ; *p != '\0'; p++ )
        {
            if ( !isspace( (unsigned char)*p ) )
            {
                printf( "unexpected input encountered!\n" );
                continue;
            }
        }

        //make sure input is in the desired range
        if ( option < 1 || option > 5 )
        {
            printf( "input must be between 1 and 5\n" );
            continue;
        }

        return option;
    }
}

However, you cannot simply replace the function mainMenu in your code with my code above, because mixing scanf and fgets in your code will not work very well. This is because scanf will not read one line at a time from the input stream, but will only extract as much as it needs to read the number and will leave the rest of the line, including the newline character, in the buffer. Therefore, if you use fgets immediately after scanf, fgets will read the remainder of the line that scanf did not extract, which will be often a string containing nothing else than the newline character.
Therefore, if you decide to use fgets (which I recommend), then you should use it everywhere in your program and not mix it with scanf, for example like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>

int mainMenu(void);
int FishermanMenu(void);
int get_int_from_user( const char *prompt );

enum menu_state
{
    MENUSTATE_MAIN,
    MENUSTATE_FISHERMAN,
    MENUSTATE_FISH,
    MENUSTATE_TOURNAMENT_CATCH,
    MENUSTATE_CLOSE_TOURNAMENT
};

int main( void )
{
    int user_choice;

    for (;;) //loop forever until input is valid
    {
        user_choice = get_int_from_user(
            "Please select 1 to start the program or 0 to quit: "
        );

        if ( user_choice == 0 )
        {
            printf("Thank you for wasting my time! Have a great day!");
            exit( EXIT_SUCCESS );
        }

        if ( user_choice == 1 )
        {
            //input is valid, so break infinite loop
            break;
        }

        printf( "Invalid selection!\n" );
    }

    enum menu_state ms = MENUSTATE_MAIN;

    for (;;) //main program loop
    {
        switch ( ms )
        {
            case MENUSTATE_MAIN:
                switch ( mainMenu() )
                {
                    case 1:
                        printf( "opening fisherman menu\n" );
                        ms = MENUSTATE_FISHERMAN;
                        break;
                    case 2:
                        printf( "opening fish menu\n" );
                        ms = MENUSTATE_FISH;
                        break;
                    case 3:
                        printf( "opening tournament(catch) menu\n" );
                        ms = MENUSTATE_TOURNAMENT_CATCH;
                        break;
                    case 4:
                        printf( "opening close tournament menu\n" );
                        ms = MENUSTATE_CLOSE_TOURNAMENT;
                        break;
                    case 5:
                        //quit program
                        exit( EXIT_SUCCESS );
                    default:
                        fprintf( stderr, "unexpected error\n" );
                        exit( EXIT_FAILURE );
                }
                break;
            case MENUSTATE_FISHERMAN:
                switch ( FishermanMenu() )
                {
                    case 1:
                        printf( "Register fisherman not yet implemented.\n" );
                        break;
                    case 2:
                        printf( "Search fisherman not yet implemented.\n" );
                        break;
                    case 3:
                        //change program state back to main menu
                        ms = MENUSTATE_MAIN;
                        break;
                    default:
                        fprintf( stderr, "unexpected error\n" );
                        exit( EXIT_FAILURE );
                    }
                break;
            case MENUSTATE_FISH:
                printf( "Fish menu not yet implemented, returning to main menu.\n" );
                ms = MENUSTATE_MAIN;
                break;
            case MENUSTATE_TOURNAMENT_CATCH:
                printf( "Tournament(catch) menu not yet implemented, returning to main menu.\n" );
                ms = MENUSTATE_MAIN;
                break;
            case MENUSTATE_CLOSE_TOURNAMENT:
                printf( "Close tournament not yet implemented, returning to main menu.\n" );
                ms = MENUSTATE_MAIN;
                break;
            default:
                fprintf( stderr, "unexpected error\n" );
                exit( EXIT_FAILURE );
        }
    }
}

int mainMenu( void )
{
    for (;;) //repeat forever, until input is in desired range
    {
        int option;

        option = get_int_from_user(
            "\n-------Welcome to the Fishing Tournament Main Menu!-------\n"
            "1 - Fisherman menu\n"
            "2 - Fish menu\n"
            "3 - Tournament(Catch) menu\n"
            "4 - Close Tournament (determine winner)\n"
            "5 - Quit Program\n\n"

            "Please select a menu option: "
        );

        //make sure input is in the desired range
        if ( option < 1 || option > 5 )
        {
            printf( "input must be between 1 and 5\n" );
            continue;
        }

        return option;
    }
}

int FishermanMenu()
{
    for (;;) //repeat forever, until input is in desired range
    {
        int option;

        option = get_int_from_user(
            "\n-------Fisherman Menu-------\n"
            "1 - Register fisherman\n"
            "2 - Search fisherman\n"
            "3 - Go back to main menu\n"
            "Please select a menu option: "
        );

        //make sure input is in the desired range
        if ( option < 1 || option > 3 )
        {
            printf( "input must be between 1 and 3\n" );
            continue;
        }

        return option;
    }
}

int get_int_from_user( const char *prompt )
{
    for (;;) //loop forever until user enters a valid number
    {
        char buffer[1024], *p;
        long l;

        puts( prompt );

        if ( fgets( buffer, sizeof buffer, stdin ) == NULL )
        {
            fprintf( stderr, "unrecoverable error reading from input\n" );
            exit( EXIT_FAILURE );
        }

        //make sure that entire line was read in (i.e. that
        //the buffer was not too small)
        if ( strchr( buffer, '\n' ) == NULL )
        {
            int c;

            printf("line input was too long!\n");

            //discard remainder of line
            do
            {
                c = getchar();

                if ( c == EOF)
                {
                    fprintf( stderr, "unrecoverable error reading from input\n" );
                    exit( EXIT_FAILURE );
                }

            } while ( c != '\n' );

            continue;
        }

        errno = 0;
        l = strtol( buffer, &p, 10 );

        if ( p == buffer )
        {
            printf( "error converting string to number\n" );
            continue;
        }

        if ( errno == ERANGE || l < INT_MIN || l > INT_MAX )
        {
            printf( "number out of range error\n" );
            continue;
        }

        //make sure remainder of line contains only whitespace,
        //so that input such as "12dfghoh" gets rejected
        for ( ; *p != '\0'; p++ )
        {
            if ( !isspace( (unsigned char)*p ) )
            {
                printf( "unexpected input encountered!\n" );

                //cannot use `continue` here, because that would go to
                //the next iteration of the innermost loop, but we
                //want to go to the next iteration of the outer loop
                goto next_outer_loop_iteration;
            }
        }

        return l;

next_outer_loop_iteration:
        continue;
    }
}

In the above code, I created a new function get_int_from_user, which performs extensive input validation.
Another problem is that it is not meaningful for the menu handling functions mainMenu and FishermanMenu to simply pass the number that the user entered back to the main function. It would be more meaningful for these functions to interpret and handle the input themselves.
As already suggested in the other answer, you could change the functions mainMenu and FishermanMenu to instead return the new state of the program back to main, as that would be the only information main needs, assuming that the input is interpreted and handled by the functions mainMenu and FishermanMenu.
In that case, the code of your program would instead look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>

int mainMenu(void);
enum menu_state FishermanMenu(void);
enum menu_state get_int_from_user( const char *prompt );

enum menu_state
{
    MENUSTATE_MAIN,
    MENUSTATE_FISHERMAN,
    MENUSTATE_FISH,
    MENUSTATE_TOURNAMENT_CATCH,
    MENUSTATE_CLOSE_TOURNAMENT,
    MENUSTATE_QUIT
};

int main( void )
{
    int user_choice;

    for (;;) //loop forever until input is valid
    {
        user_choice = get_int_from_user(
            "Please select 1 to start the program or 0 to quit: "
        );

        if ( user_choice == 0 )
        {
            printf("Thank you for wasting my time! Have a great day!");
            exit( EXIT_SUCCESS );
        }

        if ( user_choice == 1 )
        {
            //input is valid, so break infinite loop
            break;
        }

        printf( "Invalid selection!\n" );
    }

    enum menu_state ms = MENUSTATE_MAIN;

    for (;;) //main program loop
    {
        switch ( ms )
        {
            case MENUSTATE_MAIN:
                ms = mainMenu();
                break;
            case MENUSTATE_FISHERMAN:
                ms = FishermanMenu();
                break;
            case MENUSTATE_FISH:
                printf( "Fish menu not yet implemented, returning to main menu.\n" );
                ms = MENUSTATE_MAIN;
                break;
            case MENUSTATE_TOURNAMENT_CATCH:
                printf( "Tournament(catch) menu not yet implemented, returning to main menu.\n" );
                ms = MENUSTATE_MAIN;
                break;
            case MENUSTATE_CLOSE_TOURNAMENT:
                printf( "Close tournament not yet implemented, returning to main menu.\n" );
                ms = MENUSTATE_MAIN;
                break;
            case MENUSTATE_QUIT:
                return;
            default:
                fprintf( stderr, "unexpected error\n" );
                exit( EXIT_FAILURE );
        }
    }
}

enum menu_state mainMenu( void )
{
    for (;;) //repeat forever, until input is in desired range
    {
        int option;

        option = get_int_from_user(
            "\n-------Welcome to the Fishing Tournament Main Menu!-------\n"
            "1 - Fisherman menu\n"
            "2 - Fish menu\n"
            "3 - Tournament(Catch) menu\n"
            "4 - Close Tournament (determine winner)\n"
            "5 - Quit Program\n\n"

            "Please select a menu option: "
        );

        switch (option)
        {
            case 1:
                printf( "opening fisherman menu\n" );
                return MENUSTATE_FISHERMAN;
            case 2:
                printf( "opening fish menu\n" );
                return MENUSTATE_FISH;
            case 3:
                printf( "opening tournament(catch) menu\n" );
                return MENUSTATE_TOURNAMENT_CATCH;
            case 4:
                printf( "opening close tournament menu\n" );
                return MENUSTATE_CLOSE_TOURNAMENT;
            case 5:
                printf( "quitting program\n" );
                return MENUSTATE_QUIT;
            default:
                printf( "input must be between 1 and 5\n" );
                continue;
        }
    }
}

enum menu_state FishermanMenu()
{
    for (;;) //repeat forever, until input is in desired range
    {
        int option;

        option = get_int_from_user(
            "\n-------Fisherman Menu-------\n"
            "1 - Register fisherman\n"
            "2 - Search fisherman\n"
            "3 - Go back to main menu\n"
            "Please select a menu option: "
        );

        switch ( option )
        {
            case 1:
                printf( "Register fisherman not yet implemented.\n" );
                return MENUSTATE_FISHERMAN;
            case 2:
                printf( "Search fisherman not yet implemented.\n" );
                return MENUSTATE_FISHERMAN;
            case 3:
                //change program state back to main menu
                return MENUSTATE_MAIN;
                break;
            default:
                printf("input must be between 1 and 3\n");
                continue;
        }
    }
}

int get_int_from_user( const char *prompt )
{
    for (;;) //loop forever until user enters a valid number
    {
        char buffer[1024], *p;
        long l;

        puts( prompt );

        if ( fgets( buffer, sizeof buffer, stdin ) == NULL )
        {
            fprintf( stderr, "unrecoverable error reading from input\n" );
            exit( EXIT_FAILURE );
        }

        //make sure that entire line was read in (i.e. that
        //the buffer was not too small)
        if ( strchr( buffer, '\n' ) == NULL )
        {
            int c;

            printf("line input was too long!\n");

            //discard remainder of line
            do
            {
                c = getchar();

                if ( c == EOF)
                {
                    fprintf( stderr, "unrecoverable error reading from input\n" );
                    exit( EXIT_FAILURE );
                }

            } while ( c != '\n' );

            continue;
        }

        errno = 0;
        l = strtol( buffer, &p, 10 );

        if ( p == buffer )
        {
            printf( "error converting string to number\n" );
            continue;
        }

        if ( errno == ERANGE || l < INT_MIN || l > INT_MAX )
        {
            printf( "number out of range error\n" );
            continue;
        }

        //make sure remainder of line contains only whitespace,
        //so that input such as "12dfghoh" gets rejected
        for ( ; *p != '\0'; p++ )
        {
            if ( !isspace( (unsigned char)*p ) )
            {
                printf( "unexpected input encountered!\n" );

                //cannot use `continue` here, because that would go to
                //the next iteration of the innermost loop, but we
                //want to go to the next iteration of the outer loop
                goto next_outer_loop_iteration;
            }
        }

        return l;

next_outer_loop_iteration:
        continue;
    }
}

On second thought, I'm not sure if my previous advice was correct. Because you seem to have a strict menu hierarchy, it may be simpler in your case not to store the state of the program in a separate variable, but to instead let the menu state be implied by the control flow of the program. In that case, your program would look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>

void MainMenu( void );
void FishermanMenu( void );
void FishMenu( void );
void TournamentCatchMenu( void );
void CloseTournamentMenu( void );

int get_int_from_user( const char *prompt );

int main(void)
{
    int user_choice;

    for (;;) //loop forever until input is valid
    {
        user_choice = get_int_from_user(
            "Please select 1 to start the program or 0 to quit: "
        );

        if (user_choice == 0)
        {
            printf("Thank you for wasting my time! Have a great day!");
            exit(EXIT_SUCCESS);
        }

        if (user_choice == 1)
        {
            //input is valid, so break infinite loop
            break;
        }

        printf("Invalid selection!\n");
    }

    MainMenu();
}

void MainMenu(void)
{
    for (;;) //repeat forever, until input is in desired range
    {
        int option;

        option = get_int_from_user(
            "\n-------Welcome to the Fishing Tournament Main Menu!-------\n"
            "1 - Fisherman menu\n"
            "2 - Fish menu\n"
            "3 - Tournament(Catch) menu\n"
            "4 - Close Tournament (determine winner)\n"
            "5 - Quit Program\n\n"

            "Please select a menu option: "
        );

        switch (option)
        {
            case 1:
                FishermanMenu();
                break;
            case 2:
                FishMenu();
                break;
            case 3:
                TournamentCatchMenu();
                break;
            case 4:
                CloseTournamentMenu();
                break;
            case 5:
                return;
            default:
                printf( "input must be between 1 and 5\n" );
                continue;
        }
    }
}

void FishermanMenu()
{
    for (;;) //repeat forever, until input is in desired range
    {
        int option;

        option = get_int_from_user(
            "\n-------Fisherman Menu-------\n"
            "1 - Register fisherman\n"
            "2 - Search fisherman\n"
            "3 - Go back to main menu\n"
            "Please select a menu option: "
        );

        switch (option)
        {
            case 1:
                printf( "Register fisherman not yet implemented.\n" );
                break;
            case 2:
                printf( "Search fisherman not yet implemented.\n" );
                break;
            case 3:
                printf( "Returning to main menu.\n" );
                return;
            default:
                printf( "input must be between 1 and 5\n" );
                continue;
        }
    }
}

void FishMenu()
{
    printf( "Fish Menu not yet implemented, please select another menu item.\n" );
}

void TournamentCatchMenu()
{
    printf( "Tournament(Catch) Menu not yet implemented, please select another menu item.\n" );
}

void CloseTournamentMenu()
{
    printf( "Close Tournament Menu not yet implemented, please select another menu item.\n" );
}

int get_int_from_user( const char *prompt )
{
    for (;;) //loop forever until user enters a valid number
    {
        char buffer[1024], *p;
        long l;

        puts( prompt );

        if ( fgets( buffer, sizeof buffer, stdin ) == NULL )
        {
            fprintf( stderr, "unrecoverable error reading from input\n" );
            exit( EXIT_FAILURE );
        }

        //make sure that entire line was read in (i.e. that
        //the buffer was not too small)
        if ( strchr( buffer, '\n' ) == NULL )
        {
            int c;

            printf("line input was too long!\n");

            //discard remainder of line
            do
            {
                c = getchar();

                if ( c == EOF)
                {
                    fprintf( stderr, "unrecoverable error reading from input\n" );
                    exit( EXIT_FAILURE );
                }

            } while ( c != '\n' );

            continue;
        }

        errno = 0;
        l = strtol( buffer, &p, 10 );

        if ( p == buffer )
        {
            printf( "error converting string to number\n" );
            continue;
        }

        if ( errno == ERANGE || l < INT_MIN || l > INT_MAX )
        {
            printf( "number out of range error\n" );
            continue;
        }

        //make sure remainder of line contains only whitespace,
        //so that input such as "12dfghoh" gets rejected
        for ( ; *p != '\0'; p++ )
        {
            if ( !isspace( (unsigned char)*p ) )
            {
                printf( "unexpected input encountered!\n" );

                //cannot use `continue` here, because that would go to
                //the next iteration of the innermost loop, but we
                //want to go to the next iteration of the outer loop
                goto next_outer_loop_iteration;
            }
        }

        return l;

next_outer_loop_iteration:
        continue;
    }
}

However, even if this solution is simpler and cleaner, it is not as flexible as the previous solution. If you later decide to loosen the strictness of the menu hierarchy (for example by allowing to directly jump from one menu to another menu in a completely different place in the menu hierarchy), then things would get messy very quickly.


text:
Q: WebExtensions and Firefox Android: How to get a BrowserApp object The MDN page for the BrowserApp object says that it is an alternative way to access some properties that you otherwise could not get to on Android. But the way they show how to actually get one of these objects uses the deprecated 'old-style' API that does not work in my extension.
I need a way for my background script to get a hold of one of these BrowserApp objects, how do I do this? I know that if I use a bootstrap script, the browser will give me one, but I need it in my background script.
I can't use the above var { Cu } = require("chrome") method because "chrome" is not loaded yet by the time my script runs.
(as an aside, does anyone know if the browser.downloads.download(...) api works on Android? The MDN says it will but the MDN says a lot of things, and at this point I'm wary of blindly trusting the docs)

A: You cannot access BrowserApp by design from webextensions.  Your best bet is probably asking about the individual things you want to get at via BrowserApp.


text:
Q: Outer merge between pandas and imputing NA with preceeding row I have two dataframes containing the same columns:
df1 = pd.DataFrame({'a': [1,2,3,4,5],
                    'b': [2,3,4,5,6]})

df2 = pd.DataFrame({'a': [1,3,4],
                    'b': [2,4,5]})

I want df2 to have the same number of rows as df1. Any values of a not present in df1 should be copied over, and corresponding values of b should be taken from the row before.
In other words, I want df2 to look like this:
df2 = pd.DataFrame({'a': [1,2,3,4,5],
                    'b': [2,2,4,5,5]})

EDIT: I'm looking for an answer that is independent of the number of columns

A: Use DataFrame.merge by only a column from df1 and for replace missing values is added forward filling them:
df = df1[['a']].merge(df2, how='left', on='a').ffill()
print (df)
   a    b
0  1  2.0
1  2  2.0
2  3  4.0
3  4  5.0
4  5  5.0

Or use merge_asof:
df = pd.merge_asof(df1[['a']], df2, on='a')
print (df)
   a  b
0  1  2
1  2  2
2  3  4
3  4  5
4  5  5


text:
Q: FindControl issue I created a row (header row) in a gridview with a dropdownlist among other input controls. I also put a button on that row (fltbttn-see below). I created an addhandler for the button called fltbttn_Click. I want gain access to my dropdownlist (ddlscantype) using findcontrol but how can I get to the header row where the filter controls exist?
   Dim fltbttn As New ImageButton
   fltbttn.ImageUrl = "\images\bttnFilter.gif"
   AddHandler fltbttn.Click, AddressOf fltbttn_Click
   Dim cell As New TableCell
   Dim row As New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal)
   Dim ddlscantype As New DropDownList
    AddHandler ddlscantype.SelectedIndexChanged, AddressOf ddlscantype_Changed
    ddlscantype.DataSource = SqlDataSource2
    ddlscantype.DataValueField = "value"
    ddlscantype.DataTextField = "name"
    ddlscantype.DataBind()
   row.Cells.Add(cell)
   cell.Controls.Add(ddlscantype)

MARKUP
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate >
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
            AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF"
            BorderStyle="None" BorderWidth="1px" CellPadding="3"
            DataSourceID="SqlDataSource1" Font-Names="Estrangelo Edessa" Font-Size="Small"
            ShowFooter="True"
            Caption = '

Receiving Error Log

' >
            <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
            <Columns>
                <asp:BoundField DataField="scan" HeaderText="Scan" SortExpression="scan" />
                <asp:BoundField DataField="ScanType" HeaderText="ScanType" ReadOnly="True"
                    SortExpression="ScanType" />
                <asp:BoundField DataField="Vendor" HeaderText="ht" ReadOnly="True"
                    SortExpression="ht" />
                <asp:BoundField DataField="Name" HeaderText="ht2" ReadOnly="True"
                    SortExpression="ht2" />
            </Columns>
            //footer style and pager style blah blah blah goes here.
            </ContentTemplate>
    </asp:UpdatePanel>
    <ajaxToolkit:UpdatePanelAnimationExtender ID="upae" BehaviorID ="animation" runat="server" TargetControlID = "UpdatePanel1" >
         <Animations >
            <OnUpdating>
                <Parallel duration="0">


text:
Q: How to use lambda expression in android I'm having this error when trying to use lambda expressions.
Error:

Error:(122, 42) error: lambda expressions are not supported in -source 1.7
  (use -source 8 or higher to enable lambda expressions)

How can I solve it notice that my android studio is 3.0

A: android {
compileSdkVersion 29
buildToolsVersion "29.0.2"

defaultConfig {
    applicationId "com.sanjay.sanjay"
    minSdkVersion 15
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

}

add like this in you app.gradle file in android studio

A: Add the below code to your app level gradle:
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

A: Its because maybe you are using Java 7 and Actually, Retrolambda is a library which we can use with Java 8 lambda expressions.
So How To SetUp :-
Add this following to your project's main build.gradle
 classpath 'me.tatarka:gradle-retrolambda:3.2.3'

then add this to your application module's build.gradle
apply plugin: 'me.tatarka.retrolambda'

then we need to add these lines to your application module's build.gradle
android {
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

and done, you can use it like below :-

eg.) Clicking a button with Retrolambda.

  // RETROLAMBDA WAY
        clickMeBtn.setOnClickListener(view ->
                Toast.makeText(MainActivity.this,
             "This is the way to click a button to make a toast with RetroLambda !", Toast.LENGTH_LONG).show());

Anonymous class new View.OnClickListener() can be replaced with lambda .

A: Add the following block into your app level gradle file inside
android {} attribute
compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

like
 android {
...
compileOptions {
            sourceCompatibility = '1.8'
            targetCompatibility = '1.8'
        }
}

A:
Use the following code and click the sync button and then your errors will be fixed

android {
  defaultConfig {
    // Required when setting minSdkVersion to 20 or lower
    multiDexEnabled true
  }

  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
    // Sets Java compatibility to Java 8
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
}


text:
Q: Question about AdMob impression-level ad revenue implementation in React Native I am currently building an app in React-Native and have come to the point of adding ads. I am very interested in the impression-level ad revenue feature that AdMob provides. Though, I am not sure how to implement such a feature into React Native. I currently use a bare Expo project.
The two ways of easily implementing AdMob is through Firebase, and through react-native-google-mobile-ads.
Question is, can any of these methods use the impression-level ad revenue feature, or is there another better way of achieving this?
I appreciate any help!


text:
Q: Repeat same value on next 15 rows multiple times each time a condition is satisfied I'm new to VBA but I absolutely need it for my work.
I have a file with multiple columns. I have one column, 4th one, that marks when I'm going from one group to another. It has the number 1 written once at the begining of each group. For my 1st column, I would like to write the letter "P" for 15 consecutive rows each time I encounter the number 1 on the 4th column. I wrote a piece of code but I don't know how to make it do it for 15 rows each time.
Thank you for your help.
Sub InsertP()

Dim i As Double

For i = 1 To 400000

If Cells(i, 4) = 1 Then

Cells(i, 1) = "P"

End Sub


text:
Q: Remove objects connected to right and bottom borders I'm trying to remove white objects connected to right and bottom borders. I tried imclearborder but don't know how to exclude objects connected to top and left borders.

A: You can use imclearborder, but you should pad the left and top edges of the image first so that they are not touching the border (and therefore, are not cleared).
Code:
I = imread('gQKc8.png');         %// your image

J = zeros(size(I)+1,'uint8');    %// initialize a padded matrix
J = J(:,:,1:3);                  %// (we didn't need to pad the third-dimension)
J(2:end,2:end,:) = I;            %// assign I to the lower-right of J

C = imclearborder(J,4);          %// now run imclearborder, using connectedness option 4
C = C(2:end,2:end,:);            %// remove the padding

Connectedness option 4 in imclearborder just tells the function to only check the four two-d neighboring pixels. See imclearborder documentation for more info.
Plotting the result:
%// for comparison:
B=imclearborder(I,4);             %// imclearborder on the original
subplot(221); imshow(I);
subplot(222); imshow(B);
subplot(223); imshow(J);
subplot(224); imshow(C);

from left to right, top to bottom:

*

*original image

*using imclearborder directly on original

*padded image

*desired result, using imclearborder on padded image

Note: as @beaker commented, since the two little white blobs on the right are not connected to the border, they are not cleared. If you also want to remove them you'll need to define more precisely what decides whether or not a blob should be cleared.


text:
Q: Pandas manipulation with GroupBy I have a very large table of data containing play_id, position and frame columns.

*

*play_id - refers to a particular play

*position - either A or B (with 3 total players (rows) for each given play - any combination of As and Bs)

*frame - time frame (e.g. imagine freeze-frame every 1 second)
The following shows example data (simplified for clarity):

play_id
position
frame

1
A
1

1
A
1

1
B
1

1
A
2

1
A
2

1
B
2

2
A
1

2
B
1

2
B
1

2
A
2

2
B
2

2
B
2

I want to count the number of players in each position for each play_id (they are consistent across frames for a given play_id) and append a number to each to make them unique.
This would result in the following:

play_id
position
frame

1
A_1
1

1
A_2
1

1
B_1
1

1
A_1
2

1
A_2
2

1
B_1
2

2
A_1
1

2
B_1
1

2
B_2
1

2
A_1
2

2
B_1
2

2
B_2
2

In reality I have 7 different positions, 25 frames and around 500,000 play_ids (along with many more columns).
How can I achieve this in an efficient manner? I assume groupby should be used, but I can't figure out how.

A: You could groupby.cumcount, to group by all columns and add a count for the positions:
df['position'] = df.position.str.cat(df.groupby(['play_id','frame','position']).position
                                       .cumcount().add(1).astype(str),
                                     sep='_')

print(df)

    play_id position  frame
0         1      A_1      1
1         1      A_2      1
2         1      B_1      1
3         1      A_1      2
4         1      A_2      2
5         1      B_1      2
6         2      A_1      1
7         2      B_1      1
8         2      B_2      1
9         2      A_1      2
10        2      B_1      2
11        2      B_2      2


text:
Q: Google Maps in JSP Document Could anybody direct me to an example of JSP code displaying a google map? I've got some javascript that works but ideally I would like to feature a map in my pre existing JSP pages.
Many Thanks

A: Just put it in a HTML file. Once you got it to work, then rename .html to .jsp whenever you want to replace some static content by backend-controlled dynamic content with help of EL (those ${} things).
Do you now see the point of JSP?


text:
Q: Trying to clone or pull Git from GitHub but no error I tried to clone or pull repository from GitHub but nothing happened and also no error :(
git clone https://github.com/test/test.git test

Cloning into 'test'...
after this message nothing else. Any idea where I can check the error log? because same command is working on different server but not on Amazon EC2 instance.

A: Is it a firewall issue? The Git protocol listens on port 9418.
http://git-scm.com/book/en/Git-on-the-Server-The-Protocols#The-Git-Protocol


text:
Q: Get the email of my friends using Graph API Is there any possible way from which i can access my friends email using php-sdk? Assuming that I am logged in is it possible to see the same info through a php script .What i want to do is send a gmail invite to all my friends on facebook using graph.facebook.com/$id/
it asks for a access token please help me with it .

A: *

*While login, set the permissions for email also, and you would be able to access the email
$facebook->api('/FRIEND_ID?fields=email')

*for access token , use -
$facebook->getAccessToken()


text:
Q: Bluetoothctl can't find default device but hciconfig / hcitool can see my device I was using BlueZ-5.49 at Linux with HCI-UART controller (Nordic Zephyr project).
I already use btattach to connect with my adapter and can do scan through hcitool.
$ hciconfig -a
@ RAW Open: hciconfig (privileged) version 2.22             {0x0003} 240.238053
hci0:   Type: Primary  Bus: UART
        BD Address: 00:00:00:00:00:00  ACL MTU: 27:7  SCO MTU: 0:0
        UP RUNNING
        RX bytes:476 acl:0 sco:0 events:34 errors:0
        TX bytes:248 acl:0 sco:0 commands:34 errors:0
        Features: 0x00 0x00 0x00 0x00 0x60 0x00 0x00 0x00
        Packet type: DM1 DH1 HV1
        Link policy:
        Link mode: SLAVE ACCEPT

I would like to use bluetoothctl to connect my peripherals
but I cannot find my adapter
$bluetoothctl
[bluetooth]#                         Agent registered
[bluetooth]# list
[bluetooth]# scan on
No default controller available

It seems that the bluetoothctl does not recognize this adapter.
I think my issue is similar to the below question. However, I don't quite understand what was the solution is.
bluetoothctl can't detect device but hcitool can?
I hope someone could give me some hint to check what's missing on my system right now.
Thank for your help.

A: BD Address: 00:00:00:00:00:00 - that's not a good sign. Looks like a driver issue.
I have the same problem with what appears to be a counterfeit CSR dongle. rmmod btusb && modprobe btusb helped reset the BD Address to a real one, however bluetoothctl still doesn't see it:

hci0:   Type: Primary  Bus: USB
    BD Address: 00:1A:XX:XX:XX:11  ACL MTU: 679:9  SCO MTU: 48:16
    UP RUNNING
    RX bytes:1140 acl:0 sco:0 events:58 errors:0
    TX bytes:702 acl:0 sco:0 commands:59 errors:1
    Features: 0xff 0xff 0xcd 0xfa 0xdb 0xbf 0x7b 0x87
    Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
    Link policy: RSWITCH HOLD SNIFF PARK
    Link mode: SLAVE ACCEPT
    Name: ''
    Class: 0x000000
    Service Classes: Unspecified
    Device Class: Miscellaneous,
    HCI Version: 4.0 (0x6)  Revision: 0x810
    LMP Version: 4.0 (0x6)  Subversion: 0x810
    Manufacturer: Cambridge Silicon Radio (10)

I had to recompile my kernel to do some changes in the btusb.c otherwise it would not even bring up the interface.
Here's my USB device information from dmesg:
idVendor=0a12, idProduct=0001, bcdDevice=88.91


text:
Q: Substituting lines of a text file into bash commands I want to run a bash command once for each line of a text file.
If I do:
while read l; do
  echo $l;
done < myfile.txt

I get each line echoed.
But when I use my actual command:
while read l; do
  curl -X POST http://somedomain -H "Content-Type: application/json" -d $l
done < myfile.txt

I get errors. I think it may have something to do with escaping characters in the text file, but nothing I have tried works. What is the proper way to run a curl expression once for each line of a text file?

A: To use quotes.
foocmd ... "$l"


text:
Q: Проверка get-запроса Всем привет. У меня есть гет-запросы вида:
getdata?contact&term=text
getdata?company&term=text

Как мне теперь проверить именно гет-запрос, где contact или company?
$_GET['company'] вернул пустое значение. Ссылка должна быть именно с &term=text.
Код в таком виде:
  if(isset($_GET['company']) && isset($_GET['term']))
     {

     }

A: if (Input::has('company') && Input::has('term'))
{

}

UPD: Нужно ведь сразу указывать, что фреймворк.
http://laravel.com/docs/4.2/requests


text:
Q: Dynamically changing the size of JFrame when exposed to different screen resolutions So for a school project I made a grade book in java. When creating the gui I used hardcoded values in the setBounds() methods. Now this worked when I had a 1024×768 screen resolution it looked alright, but when I got a new laptop and it had a 4k screen it looked super small when I ran the program.
So my question would be is there a way to dynamically change the size of the Jframe and all of the associated objects on the frame so it matches the resolution of the screen?
I know that you can get the screen resolution from this
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

double width = screenSize.getWidth();

double height = screenSize.getHeight();

but I do not know what would be the best way to do this.

A: Taking your approach as example and taking this answer and this tutorial as base, here you have the clues:
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;

public class Q1 extends JFrame {
    public static void main(String[] args) {
        Q1 frame = new Q1();

        frame.setSize(300, 300);
        frame.setMinimumSize(new Dimension(300, 300));
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public Q1() {
        this.addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                // This is only called when the user releases the mouse button.
                System.out.println("componentResized");
            }
        });
    }

    @Override
    public void validate() {
        resize();
        super.validate();

    };

    private void resize() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        double width = screenSize.getWidth();

        double height = screenSize.getHeight();

        System.out.println(width + "," + height);
    }
}

This will print the size of the screen when your resize the frame, so you just need to add an if/else in the resize method to make frame bigger
OUTPUT
1366.0,768.0
1366.0,768.0
componentResized
1366.0,768.0
1366.0,768.0
componentResized
1366.0,768.0
1366.0,768.0
componentResized

A:
A layout manager is an object that implements the LayoutManager
  interface* and determines the size and position of the components
  within a container. Although components can provide size and alignment
  hints, a container's layout manager has the final say on the size and
  position of the components within the container.

See the example I found using layout managers.Hope you get some idea.THe original author is here   Set a layout manager like BorderLayout and then define more specifically, where your panel should go: like
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);

puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.See below example for full usage:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestLayoutManagers {

    private JPanel northFlowLayoutPanel;
    private JPanel southBorderLayoutPanel;
    private JPanel centerGridBagLayoutPanel;
    private JPanel westBoxLayoutPanel;
    private JPanel eastGridLayoutPanel;

    private final JButton northButton = new JButton("North Button");
    private final JButton southButton = new JButton("South Button");
    private final JButton centerButton = new JButton("Center Button");
    private final JButton eastButton = new JButton("East Button");
    private final JButton westButton = new JButton("West Button");

    public TestLayoutManagers() {
        northFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        southBorderLayoutPanel = new JPanel(new BorderLayout());
        centerGridBagLayoutPanel = new JPanel(new GridBagLayout());
        eastGridLayoutPanel = new JPanel(new GridLayout(1, 1));
        Box box = Box.createHorizontalBox();
        westBoxLayoutPanel = new JPanel();

        northFlowLayoutPanel.add(northButton);
        northFlowLayoutPanel.setBorder(BorderFactory.createTitledBorder("Flow Layout"));

        southBorderLayoutPanel.add(southButton);
        southBorderLayoutPanel.setBorder(BorderFactory.createTitledBorder("Border Layout"));

        centerGridBagLayoutPanel.add(centerButton);
        centerGridBagLayoutPanel.setBorder(BorderFactory.createTitledBorder("GridBag Layout"));

        eastGridLayoutPanel.add(eastButton);
        eastGridLayoutPanel.setBorder(BorderFactory.createTitledBorder("Grid Layout"));

        box.add(westButton);
        westBoxLayoutPanel.add(box);
        westBoxLayoutPanel.setBorder(BorderFactory.createTitledBorder("Box Layout"));

        JFrame frame = new JFrame("Test Layout Managers");
        frame.setLayout(new BorderLayout());      // This is the deafault layout
        frame.add(northFlowLayoutPanel, BorderLayout.PAGE_START);
        frame.add(southBorderLayoutPanel, BorderLayout.PAGE_END);
        frame.add(centerGridBagLayoutPanel, BorderLayout.CENTER);
        frame.add(eastGridLayoutPanel, BorderLayout.LINE_END);
        frame.add(westBoxLayoutPanel, BorderLayout.LINE_START);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

}

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestLayoutManagers testLayoutManagers
                        = new TestLayoutManagers();
            }
        });
    }
}


text:
Q: H-polar decomposition Can anyone help me understand how this paper: http://www.cs.vu.nl/~ran/polarnormal.pdf
figured out $(14)$ from Example 12 (on page 14)?
The problem is essentially asking for a polar decomposition of
$X=\left[\begin{matrix} 0 & 0 & 1 & 0 & 0\\ 0 & 0 & 0 & r & z \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0\end{matrix}\right]$
where $r>0$ and $z=\pm 1$.
However, I do not understand where the $H$ matrix is coming from, and how they came up with it! Same goes for $U$ and $A$ matrices.
And yes, I read the paper, but I still don't understand!


text:
Q: Simple integral with a logarithmic function: $\int\frac{\ln x}{\sqrt{1-x}}\,\mathrm dx$ Consider this indefinite integral and solve it with the simplest way.
$$\int\frac{\ln x}{\sqrt{1-x}}\,\mathrm dx$$
How  can we  solve it?

A: You can make the substitution $u = 1 - x$ and then apply integration by parts.
Edit:
Using the given substitution, we get (neglecting the negative sign, which you can add in in your work)
$$\int \frac{\ln(1 - u)}{\sqrt{u}}\,\mathrm{d}u = 2\sqrt{u}\ln(1 - u) + 2 \int\frac{\sqrt{u}}{1 - u}\,\mathrm{d}u$$
The last integral can be easily evaluated by putting $u = v^2$.

A: Follow the steps
i) Using integration by parts with $u=\ln(x)$ gives

$$ -2\,\sqrt {1-x}\ln  \left( x \right) -\int \!-2\,{\frac {\sqrt {1-x}}{
x}}{dx}.$$

ii) applying the change of variables $1-x=u^2$ yields

$$ -2\,\sqrt {1-x}\ln  \left( x \right) +4\,\int \!{\frac {{u}^{2}}{{u}^{
2}-1}}{du}
. $$

iii) To evaluate the last integral use the partial fraction technique

$$ \frac{u^2}{u^2-1}=1-\frac{1}{2(1+u)}+ \frac{1}{2(u-1)}. $$

A: Beter make the substitution $z=\sqrt{1-x}$. Then $x=1-z^2$ $dx=-2zdz$
$$\int \frac{\ln (1-z^2)}{z}(-2z dz)=-2\int\ln(1-z^2)dz$$
Now $U=\ln (1-z^2), dU=-\frac{2z}{1-z^2}$,  $dV=dz, V=z$ and an integration by parts gives
$$\int \ln(1-z^2)dz=z\ln (1-z^2)+2\int  \frac{z^2}{1-z^2}dz$$
$$=z\ln (1-z^2)-2\int  \frac{z^2-1+1}{z^2-1}dz$$
$$=z\ln (1-z^2)-2\int dz-2\int \frac{1}{z^2-1}dz=etc.$$

A: Let's take as known the integral
$$\int \ln x\,dx = x\ln x-x+C$$
Start with the substitution $x=1-u^2$, so that $\sqrt{1-x}=u$ and $dx=-2udu$.  We have
$$\int{\ln x\over\sqrt{1-x}}\,dx=-2\int\ln(1-u^2)\,du=-2\int\ln(1-u)\,du-2\int\ln(1+u)\,du$$
Each of the last two integrals can be handled as a straightforward substitution from the known integral of the logarithm function.
Note:  Short of simply differentiating $x\ln x-x$ and verifying you get $\ln x$, I can't offhand think of any way to integrate $\ln x$ without at some point using integration by parts.


text:
Q: Live Scroll Issues (JS) Im working on a website right now and have run into an issue.  Im pretty new to all of this so im sure its a simply fix.  basically, i would like to use javascript to have an onlick event in which clicking a link in the header will result in a live animated scroll down to a point on the page.  The issue?  no live scroll, it just jumps.  heres a snippet of the code.  thanks!

    <title>Dupont Studios</title>
    <link href= 'style.css' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Oxygen:300' rel='stylesheet' type='text/css'>

what

how

why

where

who

example of a jump point:

another attempt at the js which doesnt work
 $("a.nav-item").click(function() {
        $("html, body").animate({
        scrollTop: $($(this).attr("href")).offset().top + "px"}, {duration: 500, easing: "swing"
        });
        return false;
        });

A: It didn't work out because you tried my answer from This Question but you have a different setup.
So this will work:
$("li.nav-item").click(function() {
        $("html, body").animate({
            scrollTop: $($(this).children().attr("href")).offset().top + "px"}, {duration: 500, easing: "swing"
        });
        return false;
    });

The point is that the element you are looking for #tag is inside an A element inside the LI element. Ypu can see a Fiddle here
EDITED
There are quite a few errors in your document, that's why is not working. When in trouble open FF or Chrome Dev Tools (Console...) so that you can see what's wrong. There is an error within  the code "waypoint" and can't load it. I commented it for now. The following works like a charm:

    <title>Dupont Studios</title>
    <link href= 'style.css' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Oxygen:300' rel='stylesheet' type='text/css'>

what

how

why

where

who

            What

            How

            Why


text:
Q: How to create image from numpy float32 array? I have a numpy.ndarray array which contains values of float32. The images should be dimensions 226×226. I tried to use PIL.Image to create the image but I got an error. I read that PIL.Image.fromarray require an object and mode, and for float I need to call fromarray with 'F' as I tried.
This is what I tried to do:
from PIL import Image
img = Image.fromarray(slice56, mode='F')
#type(slice56) = <type 'numpy.ndarray'>
#slice56 = array([ 0.,  0.,  0., ...,  0.,  0.,  0.], dtype=float32)

and I get this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1860, in fromarray
    return frombuffer(mode, size, obj, "raw", mode, 0, 1)
  File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1805, in frombuffer
    return apply(fromstring, (mode, size, data, decoder_name, args))
  File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1743, in fromstring
    im = new(mode, size)
  File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1710, in new
    return Image()._new(core.fill(mode, size, color))
TypeError: argument 2 must be sequence of length 2, not 1

Can anyone suggest an idea how to do it? Or how to solve this error?

A: I would agree with DavidG's answer being a quick solution to plot an image from a numpy array. However, if you have a very good reason for sticking with PIL.Image, the closest approach to what you've already done would be something like this:
from PIL import Image
import numpy as np

slice56 = np.random.random((226, 226))

# convert values to 0 - 255 int8 format
formatted = (slice56 * 255 / np.max(slice56)).astype('uint8')
img = Image.fromarray(formatted)
img.show()

It will then produce something like below given random numbers:

A: scipy.misc is my favorite way of doing it. It's cleaner and it is done in just one line.
Look how nice it is:
import scipy.misc
img = scipy.misc.toimage(slice56, mode='L')

Please check here for the official docs.

A: Thanks to John Titus Jungao the problem solved. The array was 1D so I did the following:
from PIL import Image
import numpy as np

slice56 = slice56.reshape((226,226))
formatted = (slice56 * 255 / np.max(slice56)).astype('uint8')
img = Image.fromarray(formatted)
img.save('slice56.png')

and that's it.


text:
Q: Is it hard to find the root compare to showing its existence? Fundamental theorem of Algebra : It says that a polynomial over complex numbers of degree $d$ has at least one root complex root.
My Question : Is it hard to find the root compare to showing its existence ?

A: It depends on what you mean by find.  I expect that you know the formula for roots of a quadratic (degree 2) polynomial.  You probably learned it before you learned the complex numbers; it applies in the complex case as well but with the difference that you can always perform the square root.
There is also a formula for the cubic (degree 3) case but it is much more complicated and not so well known.  Cubic function at Wikipedia.  An interesting feature of this is that complex numbers may occur in the calculations even if the result is real.
There is an even more complicated formula for the quartic (degree 4) case: Quartic function at Wikipedia.
You might expect the trend to continue but it does not. There is no general solution in radicals (normal arithmetic and roots).  Not just not known but provably not possible.  Quintic formula at Wikipedia.
So, in a sense, yes it is hard to find the roots of an arbitrary polynomial (real or complex).
On the other hand, numerical methods will easily calculate the roots of any polynomial to any desired accuracy.  So, it is easy.


text:
Q: Vuejs + Laravel скачать файл (axios) Столкнулся со следующей проблемой:
Пытаюсь скачать файл размером 150mb на стеке Laravel + Vue с использованием axios:
На фронте: axios который по клику обращается к методу на бэке в котором return Storage::disk('ftp')->download($filename);
Само скачивание проходит на ура, но есть загвоздка:
1. Пользователь нажимает на ссылку, после этого достучавшись до ftp файл записывается в память, т.к. он весит 150mb все это дело происходит относительно долго. Пользователь не понимает что происходит, т.к. никаких очевидных действий не происходит для него.
2. Как только файл полностью записан в память, выскакивает окно с предложением сохранить файл на ПК.
Что я хочу:
1. Пользователь нажимает на ссылку, после этого сразу выскакивает окно с предложением сохранить файл на пк (без записи его в буфер), и после выбора директории, файл начинает скачиваться в браузере (внизу появляется файл с круглым прогресс баром, как например в Chrome).
Есть также другое приложение на Laravel, там на фронте не используется Vue, соответственно по нажатию на ссылку, файл начинает скачиваться, так как я хочу (с прогресс баром и т.п.).
Перепробовал кучу вариантов, но видимо из-за недостатка знаний решить проблему не получается, сижу уже второй день, если кто-то поможет идеей буду очень благодарен. Laravel 5.7, php 7.1.3.

A: Использование axios тут избыточно.
Просто ставь html-ссылку, не обязательно с target="_blank", на метод, который делает return Storage::disk('ftp')->download($filename); . Laravel помещает в хедеры информацию, что это скачивание файла, а браузер это понимает и не изменяет текущую страницу с vue-приложением.