text:
Q: Can threading.local() be used for a request in a Flask application? I have a Flask Service and I want to log a correlationID for all log messages. I found this blog post which makes use of threading.local().
My Flask service uses gunicorn and gevent:
gunicorn --worker-class=gevent \
         --worker-connections=1000 \
         --bind 0.0.0.0:5000 myapp.app:app
         --workers=4 --timeout 120 --keep-alive 120

Can threading.local() be used for a request?
I guess ...

*

*each worker is a different process and

*each connection is a different thread and

*each request is on exactly one thread, if I don't explicitly start another thread?

But when I start another thread, I would need to pass the correlationId explicitly, right?
(In case it matters: I use Python 3.7)

A: If you are asking if you can use threading locals to pass request objects around, that is what flask does internally already.
# context locals
_request_ctx_stack = LocalStack()
_app_ctx_stack = LocalStack()
current_app = LocalProxy(_find_app)
request = LocalProxy(partial(_lookup_req_object, 'request')) # Here
session = LocalProxy(partial(_lookup_req_object, 'session'))
g = LocalProxy(partial(_lookup_app_object, 'g'))

If you are asking if you can pass your own object around from the thread locals, you can do that as well since that's basically what flask does.
But apparently flask recommends werkzeug.local
https://werkzeug.palletsprojects.com/en/0.15.x/local/


text:
Q: "dagger-android" library, how to inject a property of a Dialog class? I followed the example which claims that is the better "new way". (https://proandroiddev.com/exploring-the-new-dagger-android-module-9eb6075f1a46) The full sample source code is here (https://github.com/jshvarts/DaggerAndroidKotlinSampleApp). It uses this to inject properties to an Activity like this,
class MainActivity:AppCompatActivity()
{
    @Inject
    lateinit var something:Something

    override fun onCreate(..)
    {
      AndroidInjection.inject(this)
      ...

And a module
@Module
abstract class ActivitiesModule
{
    @ContributesAndroidInjector
    abstract fun bindMainActivity():MainActivity

It works well, but what about a custom Dialog class?  I create the Dialog with some custom arguments (which are only known at run-time with user's inputs) like the following. I may modify the constructor of MyDialog to take something, and let the activity eventually pass something to the MyDialog's constructor.
But it would be ugly, because the activity does not directly create MyDialog. MainActivity has a custom control, and that custom control shows MyDialog when a button is clicked on it. So, to use the constructor method, I must pass something from MainActivity to the custom control, and then let the custom control create MyDialog with something.
class MyDialog:Dialog
{
      @Inject
      lateinit var something:Something

      constructor(context:Context?, arg1, args2, args3):super(context)
      {
          //Cannot call AndroidInjection.inject, because
          //it does not take a Dialog.
          AndroidInjection.inject(this); //<--Does NOT work.

If only I could tell Dagger to inject the fields of MyDialog at its constructor... What is the solution for this?

A: AndroidInjection only works on the classes like activities and fragments, not dialogs. If you want to inject your dialog, use a dialog fragment instead. Or, since you can actually just call the constructor, use constructor injection and not Dagger.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to access local variable via a function call through ssh This the code I,m trying to execute:
#!/bin/bash

set -e -a

err_report() {
    echo "Error on line $1"
}

trap 'err_report $LINENO' ERR

IFS=$'\n'

value=($(cat builds.txt))

prevBuild=${value[0]}
prevBuildDir=$prevBuild
currentBuild=${value[1]}
currentBuildDir=$currentBuild

splitPrevBuild=(${prevBuild//./$'\n'})
splitcurrentBuild=(${currentBuild//./$'\n'})

prevBuildSR=${splitPrevBuild[2]}
prevBuildHF=${splitPrevBuild[3]}
prevBuildNum=${splitPrevBuild[4]}
currentBuildSR=${splitcurrentBuild[2]}
currentBuildHF=${splitcurrentBuild[3]}
currentBuildNum=${splitcurrentBuild[4]}

function change {
    cd ~/InstallationFiles/${currentBuildSR}/${currentBuildDir}/${currentBuild}extracted
}

change
pwd
ssh -T atao52@kvs-in-hsglap17.in.kronos.com <<-EOF
$(typeset -f)
change
pwd
echo hi
exit
EOF

How to access the variables as currently, it says
cd: /home/atao52/InstallationFiles///extracted: No such file or directory


text:
Q: Local vs non-local boundary conditions In the context of PDEs how exactly are local and non-local boundary conditions defined? Can you give some examples?
For instance, are Nuemann and Dirichlet local boundary conditions?


text:
Q: WPF Microsoft Charting Line Chart with Error Bars Does anyone know how I can add Error bars like these:
http://www.officetooltips.com/images/tips/83_3/1.png
with the Microsoft WPF charting toolkit? Can you give me a simple code example please?
I've found some info here, but can't seem to utilize the info:
http://msdn.microsoft.com/en-us/library/dd456729.aspx
Hope someone can help
Many thanks in advance.


text:
Q: What are the int and multiplication signs doing here? Can anyone explain what the purpose of the ints are in Rectangle center and Rectangle obstacle? I already understand that an int is a positive or negative whole number. Also why don't I need any ints in Rectangle left and Rectangle right if they are needed in center and obstacle? I'm still new to this so if anyone thinks I should include more code just let me know.
Rectangle left = new Rectangle(0,0,WIDTH/9,HEIGHT);
Rectangle right = new Rectangle((WIDTH/9)*8,0,WIDTH/9,HEIGHT);

Rectangle center = new Rectangle((int)((WIDTH/9)* 2.5),(int)((HEIGHT/9)*2.5),(int)
((WIDTH/9)*5),(HEIGHT/9)*4);
Rectangle obstacle = new Rectangle(WIDTH/2,(int)((HEIGHT/9)*7),
WIDTH/10,HEIGHT/9);

A: Java is a strongly typed language, which means every variable has a data type. However, via polymorphism you can use the information from one data type and handle it as a different one. Examples of this in Java are interfaces & subclasses. You can do this conversion either by implicit or explicit casting. That is what is shown here.
When you use a primitive data type or object name in parentheses before another variable, it casts to another compatible type.
As long as the internal data is compatible, you can convert the type to something else. For example, if the Object in question here was a String:
if(s instanceof String) {
String t = (String)s;
}


text:
Q: Http request in nodejs with form data and query string How can I send both query string parameters and form data parameters in nodejs. I tried the following code. but it's not working. it is just hanging and no response is comming.
var url_req = require("request");
    url_req({
        pool: separateReqPool,
        url: "https://somthing.com/v1/message/userF",
        method: 'POST',
        qs: {
            action: "send-message",
            c: "somecode_c",
            cache: new Date().getTime(),
            sid: "somecode_sid"
        },
        form: {
            convId: "userF~userT~esp",
            message: ".",
            sendAs: "userF",
            txnId: "userF~" + new Date().getTime() + "~number",
        },
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'Cookie': 'some cookies',
            'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:33.0) Gecko/20100101 Firefox/33.0',
            'Accept-Language': "en-US,en;q=0.5",
            'Connection': "keep-alive",
            'Pragma': "no-cache",
            'Cache-Control': "no-cache",
            'Referer': "https://something.com/xframe.html?bc",
            'Accept': ' text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Content-Length': 100,
            'Host': "something.com"
        }
    }, function (error, response, body) {
        if (error)
            console.log(error);
        else
            console.log(body);
    });


text:
Q: Setting up a Git remote with a truncated history I am in the midst of doing some non-standard, probably doomed, experiments on a git repository. The goal is to create a remote repository with a truncated history which can still share commits with an internal repository which has a full history.
I've had some success using a graft to connect the public history with the private history - when I push from my internal repository, only the post-graft contents are included.
So my main question is: what is the simplest way of taking a commit, eliminating its parent and writing a graft in place of the parent?
A more general question: is what I'm trying to do going to cause me pain in the long run, do you know if there's a better way?

A: Scott Chacon talks about something similar to what you're describing in a recent Pro Git post (updated location). He uses git rebase --onto to separate the history into two parts, later showing how to use git replace to restore the history later, should you want to do so. I've never done this myself, but it's explained in great detail in his post. Lots of diagrams too.


text:
Q: How to change width of datacells dynamically in flutter DataTable? I have found in this link a way to place data from JSON dynamically to DataTable() widget:
Dynamically display JSON data in data table layout in flutter
In that post he has ColumnWidths in the json but he doesn't show how he changes width of the individual datacell columns.
I have used that example for myself as well and I wonder how I can use the column widths from json as well to change width of individual data cells?
This is the json I am using:
[
  {
    "table-data": [
      {
        "table-label-data": "SL.´Customer´Balance Qty´Amount´Oldest / Recent ",
        "table-row-list": [
          {
            "table-row-data": "1. ´ABD ´14 / 14.60´11,090´313 / 313"
          },
          {
            "table-row-data": "1. ´ABD ´14 / 14.60´11,090´313 / 313"
          }
        ],
        "table-cell-widths": "40´168´96´96´108"
      }
    ]
  }
]

This is the model I am using:
import 'dart:ui';

class TableModel {
  TableModel(this.labelData, this.rowData);
  List<String> labelData;
  List<List<String>> rowData;

  factory TableModel.fromJson(Map<String, dynamic> json) {
    return TableModel(
      json['table-data'][0]["table-label-data"].split('´').toList(),
      buildRowData(json),
    );
  }
}

List<List<String>> buildRowData(Map<String, dynamic> json) {
  List<List<String>> rowDataCollection = [];
  json['table-data'][0]["table-row-list"].forEach((rows) {
    rowDataCollection.add(rows['table-row-data'].split('´').toList());
  });

  return rowDataCollection;
}

For the view as you can see i use a variable width inside SizedBox widget to change width, but it is now changing all widths but i want to change individual data cell widths based on json.
This is the view:
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:test_project/controllers/getters/get_test.dart';

import '../models/table_model.dart';
import '../models/test_model.dart';

class AppView2 extends StatefulWidget {
  const AppView2({
    Key? key,
  }) : super(key: key);

  @override
  _AppViewState createState() => _AppViewState();
}

class _AppViewState extends State<AppView2> {
  Future<void> generateList() async {
    String responseBody =
        await rootBundle.loadString("assets/tableJsonData.json");
    var list = await json.decode(responseBody).cast<Map<String, dynamic>>();
    return await list
        .map<TableModel>((json) => TableModel.fromJson(json))
        .toList();
  }

  @override
  void initState() {
    generateList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
            appBar: AppBar(
              title: Text('DataTable'),
            ),
            body: FutureBuilder(
              future: generateList(),
              builder: (context, AsyncSnapshot snapShot) {
                if (snapShot.data == null ||
                    snapShot.connectionState == ConnectionState.waiting ||
                    snapShot.hasError ||
                    snapShot.data.length == 0) {
                  return Container(
                    child: Center(child: CircularProgressIndicator()),
                  );
                } else {
                  return ListView.builder(
                      shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                      itemCount: snapShot.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        final TableModel table = snapShot.data[index];
                        return SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: DataTable(
                            columns: table.labelData.map<DataColumn>((e) {
                              var columnName = e;

                              return DataColumn(
                                  label: Text(
                                columnName,
                              ));
                            }).toList(),
                            rows: table.rowData.map<DataRow>((e) {
                              return DataRow(
                                  cells: e.map<DataCell>((e) {
                                var dataCell = e;
                                dynamic width;

                                return DataCell(SizedBox(
                                  width: width,
                                  child: Text(
                                    dataCell,
                                  ),
                                ));
                              }).toList());
                            }).toList(),
                          ),
                        );
                      });
                }
              },
            )));
  }
}


text:
Q: detect ACTION_MOVE on imageView using selector I created xml file and use selector to make a button change its background.
it works perfectly ; on touch it changes background and when  finger exit view it returns to normal state ; what i want is that when the finger go back to the view it has to change its background again with the same color.
I did it by Code Java this is the code But i want to do same thing by using just xml file:
imgButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            cmp++;
            txt2.setText(" " + cmp);
            //when touch image :
            if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                imgButton.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
            }
            // finger draging...
            if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
                //... and finger exit image do this
                if (event.getX() < 0 || event.getX() > v.getWidth() || event.getY() < 0 || event.getY() > v.getHeight()) {
                    imgButton.getDrawable().setColorFilter(0x00000001, PorterDuff.Mode.SRC_ATOP);
                }
                if (event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight()) {
                    // ... and finger in the image do this
                    imgButton.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
                }
            }
            return true;
        }
    });

Selector :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <color android:color="#00FF00"/>
    </item>
    <item android:="true">
        <color android:color="#000000"/>
    </item>
</selector>

Layout

<ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:src="@drawable/str"
        android:maxWidth="@dimen/abc_button_padding_horizontal_material"
        android:contentDescription="@string/imgstart"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="82dp"
        android:background="@drawable/hhhh"
        android:clickable="true"
        />


text:
Q: view bag message not working properly on button click success using asp.net mvc? When i click on save button then success alert message is displayed, but i require only save function successful then only success alert message should be displayed.
In my code i written success alert message in button on click so it is not working properly. how to call id="bn-success" in view bag message on success.
<input type="submit" name="actionType" id="bn-success" value="Save" class="btn btn-rounded btn-inline btn-success" />

Controller:
[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Domain(Domain domain)
        {
            try
            {
                int refID = Convert.ToInt32(Session["RefID"]);
                if (ModelState.IsValid && refID > 0)
                {
                    userType type = new userType();
                    int id = type.AddDomain(domain, refID);
                    if (id != 0)
                    {
                        ViewBag.Message = "Domain added successfully";
                    }
                }
                return View();
            }
            catch
            {
                return View();
            }

        }

Alert message:
 $('#bn-success').on('click', function() {
        $.notify({
            icon: 'font-icon font-icon-check-circle',
            title: 'Heads up!',
            message: @ViewBag.Message
        },{
            type: 'success'
        });
    });

A: '@ViewBag.Message'
$('#bn-success').on('click', function() {
    $.notify({
        icon: 'font-icon font-icon-check-circle',
        title: 'Heads up!',
        message: '@ViewBag.Message'
    },{
        type: 'success'
    });
});


text:
Q: Validation failed: Cast to Array failed for value I am trying to use Typegoose with GrqphQL, MongoDB and Nest.js. I wanted to create a mutation which will create a post. I created model, service and resolver for simple Post. When I am trying to run my mutation to create a Post I am getting this error:

PostModel validation failed: sections: Cast to Array failed for value:
[
  [Object: null prototype] {
    title: 'section 1',
    body: [ 'section test lalal' ],
    code: [ "console.log('hello world!)" ],
    image: [ 'kanow.svg' ]
  }
]

at path "sections"

I do not know why I am getting this error I tried to use: ref, itemsRefs (for class and string value. You can read more about this here: typegoose arrayProp).  After I create new PostModel and I console.log every property I can see that sections is an empty array, but it shouldn't, because inside postInput I can find this JSON:
[Object: null prototype] {
  title: 'refactored post',
  image: 'rest.jpg',
  tags: [ 'ref, ref' ],
  sections: [
    [Object: null prototype] {
      title: 'section 1',
      body: [Array],
      code: [Array],
      image: [Array]
    }
  ]
}

I think this json looks good so it shouldn't be a source of this error.
I want to know what I am doing wrong and why it is not working. Below I attached some code. If you need anything else let me know in comments.
GraphQL mutation:
mutation {
  createPost(postInput: {
    image: "rest.jpg",
    title: "refactored post"
    tags: ["ref, ref"]
    sections: [{
      title: "section 1"
      body: ["section test lalal"]
      code: ["console.log('hello world!)"]
      image: ["kanow.svg"]
    }]
  }) {
    _id
    title
    tags
    sections {
      title
      body
      code
      image
    }
  }
}

post.service.ts:
@Injectable()
export class PostsService {
    constructor(@InjectModel(PostModel) private readonly postModel: ReturnModelType<typeof PostModel>) {
    }

    async create(postInput: CreatePostInput): Promise<DocumentType<PostModel>> {
        const createdPost: DocumentType<PostModel> = new this.postModel(postInput);
        return await createdPost.save();
    }
 ...
}

post.model.ts:
@ObjectType()
export class PostModel {
    @Field(() => ID)
    readonly _id: ObjectId;

    @Field()
    @prop({required: true})
    title: string;

    @Field()
    @prop({nullable: true})
    image: string;

    @Field(() => [String])
    @arrayProp({items: String})
    tags: string[];

    @Field(() => [SectionModel])
    @arrayProp({ref: 'SectionModel'})
    sections: Ref<SectionModel>[];
}

section.model.ts:
@ObjectType()
export class SectionModel {
  @Field()
  @prop({ required: true })
  title: string;

  @Field(() => [String])
  @arrayProp({ items: String })
  body: string[];

  @Field(() => [String])
  @arrayProp({ items: String })
  code: string[];

  @Field(() => [String])
  @arrayProp({ items: String })
  image: string[];
}

create-post.input.ts:
@InputType()
export class CreatePostInput {
  @Field()
  readonly title!: string;

  @Field()
  readonly image!: string;

  @Field(() => [String])
  readonly tags!: string[];

  @Field(() => [CreateSectionInput])
  readonly sections!: CreateSectionInput[];
}

UPDATE 1
I discovered that if I pass an empty array inside sections body then there is no problem to create a post. I attach example query below:
mutation {
  createPost(postInput: {
    image: "newly created.jpg",
    title: "newly created"
    tags: ["newly created, ref"]
    sections: []
  }) {
    _id
    image
    title
    tags
    sections {
      title
      body
      code
      image
    }
  }
}

A: I figured out that I should not use Ref<> for declaring nested documents. To do it you have to use items and provide correct typgoose model class. In the documentation you can read that items are only for primitive types but in the end of items documentation description you can read that you can use it also for typegoose classes (for example SectionModel.ts). Below I attached an example which is solving my problem.
post.model.ts:
@ObjectType()
export class PostModel {
  @Field(() => ID)
  readonly _id: ObjectId;

  @Field()
  @prop({required: true})
  title: string;

  @Field()
  @prop({nullable: true})
  image: string;

  @Field(() => [String])
  @arrayProp({items: String})
  tags: string[];

  @Field(() => [SectionModel])
  @arrayProp({items: SectionModel})
  sections: SectionModel[];
}

section.model.ts:
@ObjectType()
export class SectionModel {
  @Field(() => ID)
  readonly _id: ObjectId;

  @Field()
  @prop({ required: true })
  title: string;

  @Field(() => [String])
  @arrayProp({ items: String })
  body: string[];

  @Field(() => [String])
  @arrayProp({ items: String })
  code: string[];

  @Field(() => [String])
  @arrayProp({ items: String })
  image: string[];
}


text:
Q: Add a string in a  using jquery and conditions What do I want : When the user focus out the field, i would like to add a string in the  depending of an other . The  are in a table and the problem is that i have to build the string depending of the size of the table.
It would be really nice if you give some documentations to help me because im a bit lost..
HTML :

        Type

        Nom

      <select name="typ_element_1" id="typ_element_1"
      class="obligatoryAssemblage typ_element">
         <option value="" selected="selected"></option>
         <option value="EDITION">EDITION</option>
         <option value="ENCART">ENCART</option>
         <option value="INCARTO">INCARTO</option>
         <option value="INCPLUS">INCPLUS</option>
         <option value="OPP">OPP</option>
         <option value="SUPPLEMENTS" disabled="">SUPPLEMENTS</option>
     </select>

      <input type="text" name="nom_element_1" id="nom_element_1" value=""
      size="35" length="35" maxlength="35" class="obligatoryAssemblage
      nomAssemblage">

The Table : result in my computer
The jQuery/JS :
$(".nomAssemblage").focusout(function(){
  addApresFixNomElement();
});

function addSuffixNomElement(){
   // Parametres
   var rowCount = $('#tableAssemblage tr').length;
   var typElem = $(".typ_element").val();
   var nomAss = $(".nomAssemblage").val();
   var Suffix;
   var id;
   // Switch
   switch (typElem)
   {
    case 'EDITION':
        for(id=1; id<rowCount; id++){
            Suffix = "[EDI ->" + id + "]";
            $(".nomAssemblage").append(Suffix);
        }

        break;

    case 'ENCART':
        break;

    case 'INCARTO':
        break;

    case 'INCPLUS':
        break;

    case 'OPP':
        break;

    case 'SUPPLEMENTS':
        break;
}

}
The result i want : This is what i want exaclty

A: You could use
$("#nom_element_" + id).val($("#nom_element_" + id).val() + " " + Suffix);

as $().append() is to append elements (have also improved the logic as well):

$(".nomAssemblage").focusout(function() {
  addSuffixNomElement();
});

function addSuffixNomElement() {
  // Parametres
  var rowCount = $('#tableAssemblage tbody tr').length;
  var typElem = $(".typ_element").val();
  var nomAss = $(".nomAssemblage").val();
  var Suffix = "";
  var id = 1;
  // Switch
  switch (typElem) {
    case 'EDITION':
      Suffix = "[EDI ->" + id + "]";
      break;

    case 'ENCART':
      Suffix = "[ENC ->" + id + "]";
      break;

    case 'INCARTO':
      //Suffix = "[INCA ->" + id + "]";
      break;

    case 'INCPLUS':
      //Suffix = "[INCP ->" + id + "]";
      break;

    case 'OPP':
      //Suffix = "[OPP ->" + id + "]";
      break;

    case 'SUPPLEMENTS':
      //Suffix = "[SUP ->" + id + "]";
      break;
  }
  for (id = 1; id < rowCount; id++) {
    $("#nom_element_" + id).val($("#nom_element_" + id).val().replace(/\[.*?\]/, '') + " " + Suffix);
  }
}

        Type

        Nom

        <select name="typ_element_1" id="typ_element_1" class="obligatoryAssemblage typ_element">
          <option value="" selected="selected"></option>
          <option value="EDITION">EDITION</option>
          <option value="ENCART">ENCART</option>
          <option value="INCARTO">INCARTO</option>
          <option value="INCPLUS">INCPLUS</option>
          <option value="OPP">OPP</option>
          <option value="SUPPLEMENTS" disabled="">SUPPLEMENTS</option>
        </select>

        <input type="text" name="nom_element_1" id="nom_element_1" value="" size="35" length="35" maxlength="35" class="obligatoryAssemblage nomAssemblage">


text:
Q: Ignore non-number values in a list and find the sum recursive method I need to create a recursive method in LISP that takes the numbers in a list and finds the sum. Anything in the list that is not a number is skipped (For example, if the list contains "Cheese 12 Dog 8 Shoe 5", the output would be 25).
Right now my code finds the sum, but throws an error if there is anything in the list that is not a number. What can be changed to fix that?
(defun adder (lis)
   (cond
    ((null lis) 0)
    (t (eval (cons '+ lis)) )
  )
)

A: This would do:
(defun adder (lis)
  (if (null lis)
    0
    (let ((c (car lis)))
      (if (numberp c)
        (+ c (adder (cdr lis)))
        (adder (cdr lis))))))

Your version is not recursive (you don't call adder inside of adder), maybe you meant something like this (which is non-recursive)?
(defun adder (lis)
  (apply '+ (remove-if-not 'numberp lis)))

A: Using apply on lists that can be long is a bit dangerous.  If the list is longer than call-arguments-limit, then (apply '+ list) won't work.  Now, call-arguments-limit is typically pretty big in modern Lisps, but it's allowed to be as small as 50. For more information about this, see:

*

*Common lisp: How many argument can a function take? (this answer uses (reduce '+ …))

*In Lisp, how many inputs can the + function actually have?
I think your best bet would be to use reduce '+ list with a key function that takes each number to itself and each non-number to 0.  (This key function is what abiessu mentioned in a comment.)
(reduce '+ list :key (lambda (x) (if (numberp x) x 0)))

CL-USER> (let ((list '(cheese 12 dog 8 shoe 5)))
           (reduce '+ list :key (lambda (x) (if (numberp x) x 0))))
25
CL-USER> (let ((list '()))
           (reduce '+ list :key (lambda (x) (if (numberp x) x 0))))
0

Instead of using a more complex key function, you could also use (remove-if-not 'numberp list) to get rid of the non-numbers (or (remove-if (complement 'numberp) list)):
CL-USER> (let ((list '(cheese 12 dog 8 shoe 5)))
           (reduce '+ (remove-if-not 'numberp list)))
25
CL-USER> (let ((list '()))
           (reduce '+ (remove-if-not 'numberp list)))
0


text:
Q: Dataflow BigTable read rows by prefix defined at runtime I'm using Google Dataflow to read rows from BigTable based on row prefix and need to change the prefix between pipeline runs. I unsuccessfully tried to parameterize the scan configuration as there's apparently no way how to pass a ValueProvider to the scan configuration that would carry the runtime parameter.
Here's a code snippet of the scan config with static prefix provided:
   // Scan config definition
    private static CloudBigtableScanConfiguration getCloudBigtableScanConfiguration(CatalogPipelineOptions options) {
        Scan scan = new Scan()
            .setCacheBlocks(false)
            .setFilter(
                // FIXME: How to provide the prefix at runtime/when executing the dataflow template?
                new PrefixFilter("prefix-changed-at-runtime-".getBytes())
            );

        return new CloudBigtableScanConfiguration.Builder()
            .withProjectId(options.getBigtableProjectId())
            .withInstanceId(options.getBigtableInstanceId())
            .withTableId(options.getBigtableTableId())
            .withScan(scan)
            .build();
    }

   // Use of the scan config
    pipeline.apply("Read from BigTable", Read.from(
        CloudBigtableIO.read(getCloudBigtableScanConfiguration(options)))
    );

Is there a way how to pass a runtime parameter to the scan configuration and not rely on a single value defined during the pipeline build?


text:
Q: INSERT/DELETE entire row vs UPDATE BOOL field? My normalized DB has a table where a 1-N relationship exists for attributes related to the user. One of these attributes involves storing a yes/no binary status. This attribute is relatively frequently updated (TRUE to FALSE then back to TRUE) but also frequently retrieved.
Table
user_id (FK user table) | value_id (regular int) | yes_no (bool)

User has multiple variations of value_id but these are always retrieved as an entire set i.e. SELECT * FROM table WHERE user_id=ID
I'm thinking a bulk SELECT like that would benefit from lesser rows to return if all the FALSE rows are deleted from the table instead of being updated.
However, I understand that updating a single field would definitely also be less taxing than multiple INSERT/DELETE.
Thoughts appreciated!

A: Delete/insert will require from MySQL to rebuild indexes and update statistics (you have FKs == indexes).
If you have many records in the table and changing data often, this would be expensive.


text:
Q: wrong output with large test case in union find I wrote a simple union find implementation using quick find method. Here is my code
#include <iostream>

using namespace std;

class QuickFind
{
    int* id;
    int size;
    public:
    QuickFind(int n)
    {
        id = new int[n];
        size = n;
        for(int i = 0; i < size; i++) id[i] = i;
    }
    bool is_connected(int p, int q)
    {
        return id[p] == id[q];
    }
    void do_union(int p, int q)
    {
        int tempP = p;
        int tempQ = q;

        for(int i = 0; i < size; i++)
        {
            if(id[i] == tempP) id[i] = tempQ;
        }
    }
};
int main()
{
    QuickFind obj(10000);
    obj.do_union(5,6);
    obj.do_union(6,8);

    cout<<obj.is_connected(5,6)<<endl;

    for(int i = 0; i < 1000; i++)cout<<obj.is_connected(i,i+1)<<endl;
    return 0;
}

I also wrote a for loop in main. This prints correct answers when I loop it say 50 or 100 times. But it is giving me all 0s when i loop it like 1000 or more times. I'm using codeblocks ide.
Also when i compiled the same code in codechef's online compiler i get correct output. Can anyone tell me about this anomaly?


text:
Q: Sending email without hard-coding username and password Is there any way of sending an email from C# without manually coding my user name and password using Gmail SMTP?
I know that there is some software that can see the source code, and I don't really like them seeing my Gmail password.

A: You shouldn't be using your user name and password in an application that someone else is running.
Modify the application so that it prompts the user for their e-mail credentials and use those.
This will have to be stored in a configuration file and can still be read by someone else unless you store the hashedencrypted password.

A: First option: store username and password in config
using System.Net.Mail;

var fromEmail = ConfigurationSettings.AppSettings[ "mail" ];
var fromPassword = ConfigurationSettings.AppSettings[ "pass" ];

var fromAddress = new MailAddress(fromEmail, "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
           {
               Host = "smtp.gmail.com",
               Port = 587,
               EnableSsl = true,
               DeliveryMethod = SmtpDeliveryMethod.Network,
               UseDefaultCredentials = false,
               Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
           };
using (var message = new MailMessage(fromAddress, toAddress)
                     {
                         Subject = subject,
                         Body = body
                     })
{
    smtp.Send(message);
}

in app.config:
  <appSettings>
    <add key="mail" value="somemail@gmail.com" />
    <add key="pass" value="password" />
  </appSettings>

Also you can make secure config file by encrypting it.
Second option: read username and password from user

A: Make a HTTP POST to your web server, which will send the email on behalf of the application. You probably need some way to authenticate that the POST really comes from your application, so you will need to hardcode a key to the application, but since you're in control of the server part, you can block keys that are found to be misused.
Alternatively, create a secondary throwaway Gmail account, which you use to send email to your primary account, which will forward it to the intended recipient.
All these seems silly to me though, ultimately the best solution depends on what you're intending to do with the sending of the emails.

A: If you are running in ASP.NET, then you can encrypt sections of the web.config file using the aspnet_regiis.exe tool.
If you are running a regular application with an app.config file, then you can encrypt the whole file, or just parts of the file, as described by Jon Galloway in his blog entry "Encrypting Passwords in a .NET app.config File".
Once you have this in the configuration file, you can use the SecureString class to get your username/password options from the configuration file and keep them encrypted in memory until the absolute last moment they are needed/used.

A: Store the username and password in a configuration file...
Using Settings in C#

A: Externalize environment-specific configuration--especially sensitive configuration like credentials--in a configuration file.

A: The ASP.NET IIS Registration-Tool can do that for you. You just have to type a single line. Check http://odetocode.com/blogs/scott/archive/2006/01/08/encrypting-custom-configuration-sections.aspx.

A: I did a little research since my comment so I feel better about answering now.
You can use a configuration file which can be setup using these Instructions
You can then pass in the information for whatever variables you want. This will store them outside of your program, although they are still written in plain text.
An example of a config file looks similar to this.
<?xml version ="1.0"?>
    </configuration>
            </appSettings>
               <add key="password" value="Jdas7#8SL" />
            </appSettings>
    </configuration>

As for getting that info into your program here is a link that shoudl serve as a decent example.
C# using config settings
If you are worried about security and do not want this written anywhere then you need to make it so that you personally enter it every time. Or you could translate the password using some formula as mentioned in my comment. But as concluded there you are still in a pickle.
Good luck.


text:
Q: Where to find in IBM Websphere 7.0 admin console to configure http_access.log to show response time We are using IBM Websphere 7.0 Server. I need to configure to see response time in the http_access.log. I navigated through most of the admin console options, but I am not sure where to find it.

A: PM68250 added the custom log formats to WAS 7.0.0.25 and later:
http://www-01.ibm.com/support/docview.wss?uid=swg1PM68250

To enable this new functionality please add the "accessLogFormat"
  custom property to the HTTP Channel, the panel on the administrative
  console can be found here:
          Application Servers > {Server Name} > Web Container Transport Chains > {Chain Name} > {HTTP Channel Name} > Custom Properties
Also, please ensure the "Use chain-specific logging" option is enabled on the HTTP Channel where the previously mentioned property is
  enabled.


text:
Q: Obtain real Remote ADDR to peer I use development Heroku account, and wrote simple web application. When I try to obtain RemoteAddr from the HTTP Request, I get IP: 10.151.38.13:47253, which is private address, and not my IP address shown from www.whatismyipaddress.com for example. I understand that there is some proxy, relaying web traffic, but is it possible to get the real IP address.
Thank you.

A: No. The IP address will change and can't be guaranteed.  Use a domain name.  If you really need a static IP address, check out the proximo add-on.

A: I know this question is super old, but since it's near the top of the search result list I want to point anyone else who lands here to the correct answer.
See this StackOverflow post for a detailed discussion on the topic.
In short: yes, IPs can be spoofed, relayed, etc., and you should never really trust the end user.  Setting that aside, the X-Forwarded-For server variable will provide the best guess of the caller's IP address.  The first (left-most) address in the list should be the actual caller's IP, while the last (right-most) address in the list will be whatever IP actually connected to Heroku to make the request.  See the post I linked above for more details.
Note that using the REMOTE_ADDR server variable will give you the IP of the Heroku router that connected to your dyno.  This might be useful, but isn't what this question is looking for.


text:
Q: Protect worksheets in loop The following code is to lock cells that meet the criteria in each worksheet of the workbook. The code works fine on single worksheet, but when I want to apply to the entire workbook, the error messgage "unable to set the locked property to the range class".
The workbook loop procedure is also correct, can someone tell me what is causing the error?
Much appreciated! Code as below and I'm sorry I don't know how to display the correct format here:
Sub selectnumbers()
    Dim ws_count As Integer
    Dim n As Integer
    ws_count = ActiveWorkbook.Worksheets.Count
    For n = 2 To ws_count

        Dim rng As Range
        Dim cell As Range
        Dim i As Range
        Set rng = Nothing

        For Each cell In ActiveSheet.UsedRange
          If IsNumeric(cell) = False Or cell.Interior.Pattern = xlLightUp Or cell = "" Then
           If rng Is Nothing Then
            Set rng = cell
              Else
              Set rng = Application.union(rng, cell)
            End If
          End If
        End If
        Next cell

        If Not rng Is Nothing Then
        rng.Select
        End If

        Selection.Locked = True

        ActiveSheet.Protect Password:="ADARS", DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True

    Next n

End Sub

A: There seemed to be an extra End If just before the close of the nested For Each cell In .UsedRange.
I believe your primary problem was relying on the ActiveSheet property. The For n = 2 To ws_count wasn't really passing control over to the next worksheet. Focus and control was remaining with the ActiveSheet.
Sub selectnumbers()
    Dim ws_count As Long, n As Long
    Dim rng As Range, cell As Range, i As Range

    ws_count = ActiveWorkbook.Worksheets.Count
    For n = 2 To ws_count
        With Worksheets(n)

            Set rng = Nothing

            For Each cell In .UsedRange
                If Not IsNumeric(cell) Or cell.Interior.Pattern = xlLightUp Or cell = "" Then
                    If rng Is Nothing Then
                        Set rng = cell
                    Else
                        Set rng = Application.Union(rng, cell)
                    End If
                End If
            Next cell

            If Not rng Is Nothing Then
                rng.Locked = True
            End If

            .Protect Password:="ADARS", DrawingObjects:=True, Contents:=True, Scenarios:=True, _
                AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True

        End With
    Next n

End Sub

I've used a With ... End With statement to pass control along to the next worksheet.

A: The cell by cell testing looked slow to me, so I've tried a version below using SpecialCells and Find to speed it up.
Sub selectnumbers()
    Dim ws_count As Long, n As Long
    Dim rng As Range
    Dim rng1 As Range
    Dim rng2 As Range
    Dim strAddress As String

    ws_count = ActiveWorkbook.Worksheets.Count
    For n = 2 To ws_count
        With Worksheets(n)

            Set rng = Nothing
            .UsedRange

            On Error Resume Next
            Set rng = .UsedRange.SpecialCells(xlBlanks)
            If Not rng Is Nothing Then
                Set rng = Union(rng, .UsedRange.SpecialCells(xlCellTypeFormulas, 22))
            Else
              Set rng = .UsedRange.SpecialCells(xlCellTypeFormulas, 22)
            End If
            On Error GoTo 0

            With Application.FindFormat
                    .Clear
                    .Interior.Pattern = xlLightUp
            End With

            Set rng1 = .UsedRange.Find(vbNullString, , xlFormulas, xlPart, xlByRows, xlNext, , True)
            If Not rng1 Is Nothing Then
                strAddress = rng1.Address
                Set rng2 = rng1
                Do
                    Set rng1 = .UsedRange.Find(vbNullString, rng1, xlFormulas, xlPart, xlByRows, xlNext, , True)
                    Set rng2 = Union(rng2, rng1)
                Loop Until rng1.Address = strAddress
            Set rng = Union(rng, rng2)
            End If

            If Not rng Is Nothing Then rng.Locked = True

            .Protect Password:="ADARS", DrawingObjects:=True, Contents:=True, Scenarios:=True, _
                AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
        End With
    Next n

End Sub


text:
Q: Python - Selenium - select an element from a dropdown menu I need to select an element from a dropdown menu.
For example:

       Date Range
       <select class="selectpicker" id="rangeFilter" data-none-selected-text="Range" name="range">
              <option value="">View by</option>
              <option value="6month">6 months</option>
              <option value="1year">1 Year</option>
              <option value="2year">2 Year</option>
              <option value="all">All time</option>
         </select>

but i have always some kind of error.
My code is so easy:
driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
time.sleep(15)
select = Select(driver.find_element_by_id('rangeFilter'))
select.select_by_visible_text('All time')

but it don´t work. It appears a message about "element not visible: Element is not currently visible and may not be manipulated"
Traceback (most recent call last):
File "scraping.py", line 23, in <module>
select.select_by_visible_text('All time')
File "D:\Python27\lib\site-packages\selenium\webdriver\support\select.py", line 120, in select_by_visible_text
...
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated

any idea? i was trying with some fixes from another stackoverflow questions but i didn´t find the way...

A: The dropdown you are trying to select from is actually not the element with rangeFilter id. Its in the sibling
.
Since you can't use Select class on any tag either than <select> you need to first click on the dropdown to make it open the options and then click on the option
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.implicitly_wait(5)
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")

drop_down = driver.find_element_by_css_selector('[data-id="rangeFilter"]')
ActionChains(driver).move_to_element(drop_down).perform()
drop_down.click()

option = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//span[contains(., "All time")]')))
option.click()

A: The drop down that you tries to interact is not visible to the user unless we scroll up and that's why the error. Try to scroll up and then interact with the drop down. The below code might give you some idea.
element=find_element_by_xpath("xpath of the element you are trying to access")

element.location_once_scrolled_into_view

Hope this helps. Thanks.

A: You can replace implicit waits by explicit wait which waits until the element is rendered in DOM.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome("D:\Python27\selenium\webdriver\chrome\chromedriver.exe")
driver.maximize_window()
driver.get("https://ispspeedindex.netflix.com/country/norway/")
try:
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "rangeFilter"))
    )
    select = Select(driver.find_element_by_id('rangeFilter'))
    select.select_by_visible_text('All time')
finally:
    driver.quit()


text:
Q: Why horizontal scroll bar not working on listview qml? I have used almost all solutions on Stackoverflow to make it work. But none of them worked?
What changes can be done so that horizontal scroll bar work?
I used the qt docs also but still not working. Please give some examples. I just need horizontal scroll in listview. Or other view also.
main.qml
Rectangle {

    id: frame

    width: 300
    height: 300
    anchors.top: meaning.bottom

     ListView {

        width: 300
        height: 300
        anchors.centerIn: parent
        id: myList
        model: myModel
        highlight: highlightBar
        clip: true

        snapMode: ListView.SnapToItem

        headerPositioning: ListView.OverlayHeader

        header: Rectangle {
            id: headerItem
            width: myList.width
            height: 30
            z: 2

            color: "gray"

            Text {
                text: "Simple Text List"
                color: "white"
            }
        }

        delegate: Item {
            id: delegateItem
            width: 400
            height: 20
            Text {
                text: name
            }

            MouseArea {
                id: mArea
                anchors.fill: parent
                onClicked: {
                    myList.currentIndex = index
                }
            }
        }
    }

    Component {
        id: highlightBar
        Rectangle {
            width: parent.width
            height: 20
            color: "#FFFF88"
        }
    }

    ListModel {
        id: myModel
    }

        ScrollBar {
        id: vbar
        hoverEnabled: true
        active: hovered || pressed
        orientation: Qt.Vertical
        size: frame.height / content.height
        anchors.top: parent.top
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

    ScrollBar {
        id: hbar
        hoverEnabled: true
        active: hovered || pressed
        orientation: Qt.Horizontal
        size: frame.width / content.width
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }
}

Please make change to this so horizontal scroll work.
Thanks.

A: QML ListView is a Flickable subclass.
To show scrollbars in a Flickable you need to provide contentWidth and/or contentHeight and the desired flickableDirection.
Here is an example of a ListView that scrolls both ways:
import QtQuick
import QtQuick.Controls
import QtQuick.Window

Window {
  visible: true
  width: 640
  height: 480
  title: qsTr("Hello World")

  ListView {
    anchors.fill: parent
    ScrollBar.vertical: ScrollBar {}
    ScrollBar.horizontal: ScrollBar {}
    flickableDirection: Flickable.HorizontalAndVerticalFlick
    contentWidth: 1000
    model: ["lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "ut", "enim", "ad", "minim", "veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "ut", "aliquip", "ex", "ea", "commodo", "consequat", "duis", "aute", "irure", "dolor", "in", "reprehenderit", "in", "voluptate", "velit", "esse", "cillum", "dolore", "eu", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident", "sunt", "in", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum"]
    delegate: Label {
      width: ListView.view.width
      horizontalAlignment: Text.AlignHCenter
      text: modelData
    }
  }
}


text:
Q: What is the fastest way to convert an imageURL from Firebase into a UIImage? In my iOS app I need to take an imageURL string and convert it into a UIImage.
I wrote the below function to handle this:
 func getImage(urlString: String) -> UIImage {
    let url = URL(string: urlString)!
    do {
        let data = try Data(contentsOf: url)
        let image = UIImage(data: data)!
        return image
    } catch {
        print(error, " This was the error in p2")
    }
    return UIImage(named: "media")!
}

The issue is that this takes too long. I believe it's a solid second or longer for this to complete.
I need that time to be significantly shorter.
Question: Is there a faster way to get the UIImage based on an imageURL from Firebase? (maybe a cocoa-pod? or better way to write the code?)
Additional questions:

*

*Would this be any faster if the image in Firebase were of lower quality?

*Would it be a viable solution to lower the quality of the image right before being passed into this function?

A: A lot the prominent iOS apps (and web and mobile and general) that do a lot of downloading of images take advantage of progressive jpeg. This way your user will see at least something while the image loads and over time the image will get progressively better. As a lot of commenters have mentioned, you're not in control of Firebase like you would be if you had your own backend server delivering the pictures that you could do performance optimizations. Therefore one of the best things you can do is implement progressive jpeg in your app.
The first link is a library that will allow you to use progressive jpeg in your iOS app. The second link is a detailed approach used at FaceBook on faster loading of images.
https://www.airpair.com/ios/posts/loading-images-ios-faster-with-progressive-jpegs
https://code.fb.com/ios/faster-photos-in-facebook-for-ios/


text:
Q: becomeFirstResponder returns true and keyboard is dismissed In the following code I am trying to transfer control from UITextField to the next via a next button.
I am doing this by calling becomeFirstResponder on the next UITextField.
If I don't type anything in the first and current UITextField the next button works as expected. The keyboard stays up and the focus is transferred.
If I do type something, and only if the field is empty. The method becomeFirstResponder for the next field is called and returns true, yet the keyboard is dismissed and focus is not transferred.
public func numberPad(numberPad: APNumberPad, functionButtonAction:UIButton, textInput: UIResponder) {

    var current:UITextField?

    for field in editCells {

        if (current != nil) {

            field.valueTextField.becomeFirstResponder()

            return;
        }

        if (field.valueTextField == activeField) {
            current = field.valueTextField
        }

    }

    textInput.resignFirstResponder()

}

This function is called when the NEXT or DONE button is pressed on the keyboard. Which is a custom number keypad. APNumberPad specifically.
https://github.com/podkovyrin/APNumberPad
It is my delegate function.
Anyone know any reason becomeFirstResponder would return true and not work, only in some cases, but work in others?
And yes this is the main UI thread. Adding a call to resignFirstResponder on the current field, then a delay and calling becomeFirstResponder works. This causes the keypad to flicker, no matter how small the delay though.
Edit... I am now doing this... and am living with the keyboard flicker for now:
Delay is a helper function for GCD
public func numberPad(numberPad: APNumberPad, functionButtonAction:UIButton, textInput: UIResponder) {

    var current:UITextField?

    for field in editCells {

        if (current != nil) {

            current?.resignFirstResponder()
            delay (0) {
                field.valueTextField.becomeFirstResponder()
            }

            return;
        }

        if (field.valueTextField == activeField) {
            current = field.valueTextField
        }

    }

    textInput.resignFirstResponder()

}

A: I don't know if it helps you, or not. I wrote a simple UITextField extension that contains a returnView variable which decides what the textfield should do on return key press:

*

*turn to next text field (if the returnView is an UITextField)

*simulate button touch (if the returnView is a UIButton)

*or hide keyboard

class NextTextField: UITextField, UITextFieldDelegate {

    @IBOutlet weak var returnView: UIView? {
        didSet {
            if returnView is UITextField {
                returnKeyType = UIReturnKeyType.Next
            }
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        delegate = self
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {

        if let nextTextField = self.returnView as? UITextField {
            nextTextField.becomeFirstResponder()
        } else if let nextButton = self.returnView as? UIButton {
            nextButton.sendActionsForControlEvents(.TouchUpInside)
        } else {
            self.resignFirstResponder()
        }

        return true
    }

}


text:
Q: Grails: Getting the Data Source in a normal groovy class How can I get access to the data source from within a normal groovy class?  Injection doesn't work like it does with services.
The reason for this is that I need to do some manual database calls (ie: SQL statements using the groovy.sql.Sql class) from the groovy class since I'm working with a legacy database.

A: Simple solution to do manual database calls:
def grailsApplication

def getSeqVal () {

    SessionFactory sessionFactory = grailsApplication.mainContext.sessionFactory

    def sql = "--INSERT QUERY HERE--"
    def query = sessionFactory.currentSession.createSQLQuery(sql);
    def result = query.list()
    return result[0]

}

A: dataSource is a bean which gets auto injected in services when used. All beans are auto wired in grails artifacts (controllers, services etc) by default. In your case you are using a POGO and I suppose it would be inside src/groovy.
You can inject the dataSource bean explicitly to POGO class by making it a bean by itself
//resources.groovy
beans = {
    myPogo(MyPogo){
        dataSource = ref('dataSource')
    }
}

//MyPogo.groovy
MyPogo {
    def dataSource
    ....
}

This is an expensive operation. If you already are accessing applicationContext or grailsApplication in POGO then you need not create a bean as mentioned above.
dataSource bean can be directly fetched from the context as:
//ctx being ApplicationContext
def dataSource = ctx.getBean('dataSource')

//or if grailsApplication is available
def dataSource = grailsApplication.mainContext.getBean('dataSource')

If you are invoking the POGO class methods from a grails artifact then use below approach than all of the above approaches. For example:
//service class
class MyService {
   def dataSource //autowired

   def serviceMethod(){
       MyPogo pogo = new MyPogo()
       pogo.dataSource = dataSource //set dataSource in POGO
   }
}


text:
Q: Logging HDFS file while read HDFS file using Spark readStream I have written a small program that will continuesly read the incoming new files from a HDFS directory and will stream it to Kafka Topic.
While continuesly reading the HDFS file, I want to log these file into my logfile, but I am not finding any way to do it. And I also want to log the file once it is completely fed into Kafka topic. And while writting the data into Kafka topic I want to pass file name as header to kafka topic.
Below is the sample code I am using for read the file from HDFS and pushing it to Kafka Topic.
    StructType sch =  DataTypes.createStructType(new StructField[] {
            DataTypes.createStructField("id", DataTypes.StringType, true),
            DataTypes.createStructField("cat", DataTypes.StringType, true)
    });

    Dataset<Row> jsonlines = spark.readStream().schema(sch).json("/data/json/") ;

    StreamingQuery query = jsonlines.selectExpr("to_json(struct(*)) AS value")
            .writeStream()
            .format("kafka")
            .option("kafka.bootstrap.servers", "localhost:9092")
            .option("checkpointLocation", "/checkpoint/topic2/")
            .option("batch.size", 10)
            .option("topic", "topic2").start();

    query.awaitTermination();

Can you please help, will really appretiate.


text:
Q: Question about performance of the code that uses async await to read several bulk data from Redis and write them to SQL Server in parallel I wrote the code that reads bulks of data from Redis and writes those bulks to SQL Server using async await in C#.
I have written the following code in my TeamController class using async/await to make reading from REDIS in parallel with writing to SQL Server:
[Route("api/[controller]")]
[ApiController]
public class TeamController : ControllerBase
{
    private ICacheManager cacheManager;
    private IDBManager dbManager;
    private IDomainDataConverter _domainDataConverter;

    public TeamController(ICacheManager cacheManager,
                          IDBManager dbManager,
                          IDomainDataConverter domainDataConverter)
    {
        this.cacheManager = cacheManager;
        this.dbManager = dbManager;
        this._domainDataConverter = domainDataConverter;
    }

    [HttpPost, Route("SaveDataParallel")]
    public async Task<IActionResult> SaveDataParallel(int parallelDegree, int totalCount)
    {
        int chunkeSize = totalCount / parallelDegree;
        int remainder = totalCount - chunkeSize * parallelDegree;

        System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
        st.Start();

        try
        {
            var tasks = new List<Task>();

            for (int i = 0; i < parallelDegree; i++)
            {
                tasks.Add(SaveChunkAsync(i, chunkeSize, parallelDegree, remainder));
            }

            await Task.WhenAll(tasks);

            st.Stop();
        }
        catch
        {
        }

        return Ok(st.ElapsedMilliseconds);
    }

    [HttpPost, Route("SaveDataSimple")]
    public IActionResult SaveDataWithSimple(int parallelDegree,  int totalCount)
    {
        int chunkeSize = totalCount / parallelDegree;
        int remainder = totalCount - chunkeSize * parallelDegree;

        System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
        st.Start();

        try
        {
            for (int i = 0; i < parallelDegree; i++)
            {
                SaveChunk(i, chunkeSize, parallelDegree, remainder);
            }

            st.Stop();
        }
        catch (Exception ex)
        {
        }

        return Ok(st.ElapsedMilliseconds);
    }

    private async Task SaveChunkAsync(int i, int pageSize, int parallelDegree, int remainder)
    {
        var data = cacheManager.ReadDataAsync<TeamDto>(i * pageSize, (i == parallelDegree - 1 ? remainder : 0) + pageSize);
        var arr = _domainDataConverter.Convert<Team, TeamDto>(data.Result);
        await dbManager.BulkInsertAsync(arr);
    }

    private void SaveChunk(int i, int pageSize, int parallelDegree, int remainder)
    {
        var data = cacheManager.ReadData<TeamDto>(i * pageSize, (i == parallelDegree - 1 ? remainder : 0) + pageSize);
        var arr = _domainDataConverter.Convert<Team, TeamDto>(data);
        dbManager.BulkInsert(arr);
    }
}

I'm comparing the performance of the two methods: SaveDataParallel and SaveDataWithSimple. Unfortunately I don't seem to see a significant difference between the two method calls in terms of  performance.
If
n  = total number of read and writes
td = time required to save chunk of data to SQL,
tr = time required to read chunk of data from Redis,
tparallel = total time for SaveDataParallel,
tsimple = total time for SaveDataWithSimple,

I expect tparallel to be as follows:
tparallel = (max(td, tr) * n) / 2 + tr

and tsimple as follows:
tsimple = (max(td, tr)) * n

but the result is different and the two tsimple and tparallel values don't appear to have a significant difference.
Does anybody have any idea why? Am I expecting the right thing? Or there is something wrong with the code?
I would appreciate any ideas or guidance.

A: The first part of async methods is executed synchronously. And await sometimes can complete synchronously if the called method returned a completed task (see "Hot path" optimization section https://devblogs.microsoft.com/premier-developer/dissecting-the-async-methods-in-c/).
So e.g. it might be that cacheManager.ReadDataAsync did its job quickly and returned a completed task instead of going really asynchronously. Then _domainDataConverter.Convert will also run synchronously. And the for (int i = 0; i < parallelDegree; i++) loop will take all the time of ReadDataAsync + Convert. Yes, BulkInsertAsync will run in parallel, but you could do better if you made the Convert also running in parallel.
Something like:
private async Task SaveChunkAsync(int i, int pageSize,
    int parallelDegree, int remainder)
{
    var data = await cacheManager.ReadDataAsync<TeamDto>(i * pageSize,
        (i == parallelDegree - 1 ? remainder : 0) + pageSize);
    var arr = await _domainDataConverter.ConvertAsync<Team, TeamDto>(data);
    await dbManager.BulkInsertAsync(arr);
}

Also you are dividing all the data at once into parts according to the number of parallel threads. I suggest dividing it into smaller parts of fixed (maybe configurable) length and then process them either with Parallel.ForEach, in which case I would use SaveCunk or maybe Parallel.ForEachAsync with SaveChunkAsync, although I haven't tried this. See https://www.hanselman.com/blog/parallelforeachasync-in-net-6 for more details.
What to choose depends on whether you have some work for CPU and want to fully use it or if you are mostly waiting for something. In the former case multithreading approach might give you the required control to load all the CPU cores. In the latter case asynchronous approach might be better.
Then you can play with different values of batch size and number of parallel workers to find the optimal combination. When I was doing parallel bulk insert I used Parallel.ForEach and went with 4 threads. Increasing this limit didn't give any noticeable benefits.
Testing different implementations
You can run the following program to see the possible timelines of SaveChunk method depending on the implementation details. I prepared simulations of ReadData, Convert and BulkInsert so that they take 40ms, 200ms and 40ms correspondingly, to simulate tr=24, td=4 situation. And the parallelDegree=10. The first variant is synchronous and takes about 2800ms, the second one is partially async and takes about 2440ms, and the third one is async and takes about 560ms.
using System.Diagnostics;

namespace SaveChunks
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            int parallelDegree = 10;

            Console.WriteLine("Simple:");
            var target = new DataSaver();
            target.SaveDataSimple(parallelDegree);

            Console.WriteLine("Partially Async:");
            await target.SaveDataPartiallyAsync(parallelDegree);

            Console.WriteLine("Async:");
            await target.SaveDataAsync(parallelDegree);
        }
    }

    internal class DataSaver
    {
        private Stopwatch _timer = new Stopwatch();

        public void SaveDataSimple(int parallelDegree)
        {
            _timer.Restart();

            for (int i = 0; i < parallelDegree; i++)
                SaveChunk(i);

            _timer.Stop();
        }

        public async Task SaveDataPartiallyAsync(int parallelDegree)
        {
            _timer.Restart();

            var tasks = new List<Task>();

            for (int i = 0; i < parallelDegree; i++)
                tasks.Add(SaveChunkPartiallyAsync(i));

            await Task.WhenAll(tasks);

            _timer.Stop();
        }

        public async Task SaveDataAsync(int parallelDegree)
        {
            _timer.Restart();

            var tasks = new List<Task>();

            for (int i = 0; i < parallelDegree; i++)
                tasks.Add(SaveChunkAsync(i));

            await Task.WhenAll(tasks);

            _timer.Stop();
        }

        private void SaveChunk(int i)
        {
            var data = ReadData(i);
            var converted = Convert(i, data);
            BulkInsert(i, converted);
        }

        private async Task SaveChunkPartiallyAsync(int i)
        {
            var data = await ReadDataPartiallyAsync(i);
            var converted = Convert(i, data);
            await BulkInsertAsync(i, converted);
        }

        private async Task SaveChunkAsync(int i)
        {
            var data = await ReadDataAsync(i);
            var converted = await ConvertAsync(i, data);
            await BulkInsertAsync(i, converted);
        }

        // Synchronous implementation

        private int ReadData(int i)
        {
            Log(i, "ReadData start");
            Pause(40);
            Log(i, "ReadData end");
            return 0;
        }

        private int Convert(int i, int data)
        {
            Log(i, "Convert start");
            Pause(200);
            Log(i, "Convert end");
            return 0;
        }

        private void BulkInsert(int i, int data)
        {
            Log(i, "BulkInsert start");
            Pause(40);
            Log(i, "BulkInsert end");
        }

        // Partially-asynchronous implementation

        private Task<int> ReadDataPartiallyAsync(int i)
        {
            return Task.FromResult(ReadData(i));
        }

        private Task<int> ConvertAsync(int i, int data)
        {
            return Task.Run(() => Convert(i, data));
        }

        private Task BulkInsertAsync(int i, int data)
        {
            return Task.Run(() => BulkInsert(i, data));
        }

        // Asyncronous implementation

        private Task<int> ReadDataAsync(int i)
        {
            return Task.Run(() => ReadData(i));
        }

        // Helper methods

        private void Pause(int ms)
        {
            var start = _timer.ElapsedMilliseconds;
            var sum = 0;
            while (_timer.ElapsedMilliseconds - start < ms)
                sum += sum * sum;
        }

        private void Log(int i, string message)
        {
            char c = message[0];
            Console.WriteLine($"{_timer.ElapsedMilliseconds,5} {new string(' ', i * 2)}{c}");
        }

        private void Log2(int i, string message)
        {
            Console.WriteLine($"{_timer.ElapsedMilliseconds}\t{i}\t{message}");
        }
    }
}

The log shows the timeline of all 3 variants. As you can see in the second variant we are not running more than 2 tasks in parallel. But in the third one we are much more parallel.
Simple:
    1 R
   43 R
   43 C
  243 C
  243 B
  283 B
  283   R
  323   R
  323   C
  523   C
  523   B
  563   B
  563     R
  603     R
  603     C
  803     C
  803     B
  843     B
  843       R
  883       R
  883       C
 1083       C
 1083       B
 1123       B
 1123         R
 1163         R
 1163         C
 1363         C
 1363         B
 1403         B
 1403           R
 1443           R
 1443           C
 1643           C
 1643           B
 1683           B
 1683             R
 1723             R
 1723             C
 1923             C
 1923             B
 1963             B
 1963               R
 2003               R
 2003               C
 2203               C
 2203               B
 2243               B
 2243                 R
 2283                 R
 2283                 C
 2483                 C
 2483                 B
 2523                 B
 2523                   R
 2563                   R
 2563                   C
 2763                   C
 2763                   B
 2803                   B
Partially Async:
    0 R
   40 R
   40 C
  240 C
  244   R
  244 B
  284 B
  284   R
  284   C
  484   C
  484     R
  484   B
  524   B
  524     R
  524     C
  724     C
  724       R
  724     B
  764       R
  764       C
  764     B
  964       C
  964         R
  964       B
 1004         R
 1004         C
 1004       B
 1204         C
 1204           R
 1204         B
 1244           R
 1244           C
 1244         B
 1444           C
 1444             R
 1444           B
 1484             R
 1484             C
 1484           B
 1684             C
 1684             B
 1684               R
 1724               R
 1724               C
 1724             B
 1924               C
 1924                 R
 1924               B
 1964                 R
 1964                 C
 1964               B
 2164                 C
 2164                   R
 2164                 B
 2204                   R
 2204                   C
 2204                 B
 2404                   C
 2404                   B
 2444                   B
Async:
    1 R
    2   R
    2       R
    2         R
    2           R
    3     R
   27             R
   34                   R
   41 R
   41 C
   42       R
   42         R
   42       C
   42         C
   43     R
   43     C
   43           R
   43           C
   44   R
   45   C
   72             R
   72             C
   79                   R
   82                   C
  241 C
  241 B
  242         C
  242       C
  242         B
  242       B
  243     C
  243     B
  245   C
  245   B
  251           C
  251           B
  272             C
  272             B
  281 B
  281               R
  282                   C
  282       B
  282                   B
  282                 R
  283     B
  283         B
  285   B
  294           B
  312             B
  321               R
  321               C
  322                   B
  322                 R
  322                 C
  521               C
  521               B
  522                 C
  522                 B
  561               B
  562                 B


text:
Q: Figures and tables moving to end of file I know, a similar question has been asked several times, but as the answers did not fix my issue, I wondered whether I overlooked something in my case. The problem is that I write a document on overleaf and want to include several graphics and tables in my document. They all get pushed to the end of the document with one table or figure on a new page. I understand the concept of floats and that they are allowed to be placed flexibly in the document to get an asthetically pleasing result. I also know that I can influence where they are placed with different parameters. I am aware that different packages, such as placeins and Float, may give me additional options to refrain floats from jumping all over the place. Yet, none of these options have helped me prevent the tables and figures to be placed at the end of the document. I first wondered if the problem was the size of my figures and table. But the issue persists even with one single simple table such as this one which is surrounded by text:
\begin{table}[!htbp]
\caption{Results}
\begin{tabular}{llrrrrrr}
    \hline
 & Type & Df & t & p & M & SD & Cohen's D \\
    \hline
First effect & One-sided & 45 & 9.01 & .000*** & 21.74 & 16.21  & 1.34  \\
Second effect & One-sided & 45 & 7.00 & .000*** & 0.38 &  0.36  & 1.03 \\
Third effect & Two-sided & 45 & 6.34 & .000*** & 0.34 &  0.37  & 0.93 \\
    \hline
\end{tabular}
\end{table}

\FloatBarrier

I tried using the htpb! option and the Float Barrier from the placeins package, as seen above, also the H option of the Float package. None of it helped. May some setting or use of any package influence the placement of the figures? These are all the packages used in the document.
\documentclass[stu, donotrepeattitle, 12pt]{apa7}
\usepackage[american]{babel}
\usepackage{mathptmx, dcolumn}
\usepackage[style=apa, backend=biber]{biblatex}
\addbibresource{bibliography.bib}

\usepackage[document]{ragged2e}
\usepackage{placeins}

\usepackage{graphicx}
\usepackage{graphics} %package to manage images
\graphicspath{ {./images/} }
\usepackage{float}

\usepackage{hyperref}

\linespread{2}

I'm greatful for every hint I get! Thank you all in advance!


text:
Q: Creating filepath using JAVACC with different tokens How would you make a file path using JAVACC where some parts of the file had to be kept constant and you needed to keep separate tokens for this?
For example, if I wanted to go to a directory where there were constants such that the entire directory looked like "[path] [constant] [path]"
My initials thought are I would want the path to consist of a string so
TOKEN:
<IDENTIFIER: (["a"-"z", "A"-"Z"])+>
<NUMBER: (["0"-"9"])+>
<STRING: "\"" (<IDENTIFIER> | <NUMBERS> | " ")+ "\"">
<PATH>: <STRING>
<CONSTANT>: some constant


text:
Q: Unable to find xpath using position(), last(),[1] indexing([1]--eg.) following:siblings, child, parent nothing is working I am trying to find out the XPATH. I am getting 30 matches for an element.
I tried using last(), position(), indexing[], child, parent, following:siblings, preceding:siblings, absolute XPATH is also not working, how to achieve this.

<svg viewBox="0 0 16 20" class="excel-document" style="background-image:none;background-position:0% 0%;display:inline;fill:#333;height:20px;width:16px;" data-reactid=".0.0.1.0.0.1.$termsConditions-component.0.1.3.1.0.0.0.0.0.2.0:$5.5.0.0.0"><path d="M2 0C.9 0 .01.9.01 2L0 18c0 1.1.89 2 1.99 2H14c1.1 0 2-.9 2-2V6l-6-6H2zm7 7V1.5L14.5 7H9zm-2.34 7.39l-3.45-5.1h2.73l2.1 3.42 2.175-3.42h2.58L9.36 14.405 13.095 20H10.29l-2.34-3.705L5.565 20h-2.64l3.735-5.61z" fill="#11764B" data-reactid=".0.0.1.0.0.1.$termsConditions-component.0.1.3.1.0.0.0.0.0.2.0:$5.5.0.0.0.0"></path></svg>

A: If you are trying to access the first matching element of given xpath, then wrap the entire xpath with () and then provide the index as shown below.
First matching element:
 (//span[@class='cursor']//*[local-name()='svg'][@class='excel-document'])[1]

Following Element to the first-matching Element:
(//span[@class='cursor']//*[local-name()='svg'][@class='excel-document'])[1]/following-sibling::*

Last Element:
 (//span[@class='cursor']//*[local-name()='svg'][@class='excel-document'])[last()]


text:
Q: Can the C# compiler optimize this cast away? I'm doing the following cast to double and back to long, intentionally:
var adjustedValue = (long)(double)dateTime.Ticks;

(where dateTime is a System.DateTime and Ticks is a long). Resharper tells me however that the cast to double is "redundant" and this has me wondering if it can be optimized away by the compiler.

A: I tried out this code in LINQPad:
var dateTime = DateTime.Now;
var adjustedValue = (long)(double)dateTime.Ticks;
adjustedValue.Dump();

Both with and without optimizations, it generated identical IL (the only difference being in the labels):
IL_0000:  call        System.DateTime.get_Now
IL_0005:  stloc.0     // dateTime
IL_0006:  ldloca.s    00 // dateTime
IL_0008:  call        System.DateTime.get_Ticks
IL_000D:  conv.r8
IL_000E:  conv.i8
IL_000F:  stloc.1     // adjustedValue
IL_0010:  ldloc.1     // adjustedValue
IL_0011:  call        LINQPad.Extensions.Dump

So the answer is no, the C# compiler does not optimize this double cast. The conversions are there, even when optimizations are turned on.
However, you should also notice that this double-cast does significantly change the original data. Here's a quick demo, also created using LINQPad:
var dateTime = DateTime.Now;
var originalValue = dateTime.Ticks;
var adjustedValue = (long)(double)originalValue;
originalValue.Dump(); // 635385353415288655
adjustedValue.Dump(); // 635385353415288704

This is because a double only has 15-16 digits of precision, but a long may be up to 19 digits long. You're bound to get some amount of rounding error. If this is a problem, you could use a decimal instead. This will avoid any rounding errors, but even in this case, the double-cast will not be optimized away by the C# compiler.
Of course, how the JIT compiler or NGen.exe convert this to native code is an entirely different matter, but I would expect the behavior to be the same.

A: I just checked it out. With "dotPeek 1.1" I "took a look" into the source code of this.
With configuration Debug it keeps as is, because the /optimize flag is not set.
With configuration Release there is indeed something changed, but not the casts. In Release, as default, /optimize switch is turned on.
var adjustedValue = (long)(double)DateTime.Now.Ticks;

Console.WriteLine(adjustedValue);

went to
Console.WriteLine((long) (double) DateTime.Now.Ticks);

Résumé:
It will not optimize this way of cast.


text:
Q: pandas dataframe Shape of passed values is (5, 1), indices imply (5, 2) I see several similar questions but they have not solved my problem.
Short version:
If I create a list of tuples to use as input for a dataframe, all works as intended.
If the list of tuples comes as a result of a SQL query, I get the error mentioned in the topic name. The two lists of tuples look identical to me (I made the first list by copying from the second list so they should be the same), but not to pandas. Any help would be greatly appreciated.
Long version:
If I do this:
query_results = [('Pick_Task', 'task_internal_id'), ('Pick_Task', 'task_id'), ('Pick_Task', 'date_created'),
        ('Pick_Task', 'plan'), ('Pick_Task', 'employee_actual')]

df = pd.DataFrame(query_results, columns=['Table Name','Column Name'])
print(df)

I get this (which is what I would expect):
Table Name       Column Name
0  Pick_Task  task_internal_id
1  Pick_Task           task_id
2  Pick_Task      date_created
3  Pick_Task              plan
4  Pick_Task   employee_actual

If I do this:
query = """SELECT TABLE_NAME, COLUMN_NAME
        FROM Analyst.INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'Pick_Task'
        """
with conn.cursor() as cursor:
    cursor.execute(query)
    query_results = cursor.fetchall()

print(query_results)

df = pd.DataFrame(query_results, columns = ['Table Name', 'Column Name'])

I get this (which is what I would expect):
[('Pick_Task', 'task_internal_id'), ('Pick_Task', 'task_id'), ('Pick_Task', 'date_created'), ('Pick_Task', 'plan'), ('Pick_Task', 'employee_actual')]

But I also get this (which is not what I expected and why I am here looking for help):
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3200/749747456.py in <module>
      9 print(query_results)
     10
---> 11 df = pd.DataFrame(query_results, columns = ['Table Name', 'Column Name'])

~\Miniconda3\envs\da1\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
    709                     )
    710                 else:
--> 711                     mgr = ndarray_to_mgr(
    712                         data,
    713                         index,

~\Miniconda3\envs\da1\lib\site-packages\pandas\core\internals\construction.py in ndarray_to_mgr(values, index, columns, dtype, copy, typ)
    322     )
    323
--> 324     _check_values_indices_shape_match(values, index, columns)
    325
    326     if typ == "array":

~\Miniconda3\envs\da1\lib\site-packages\pandas\core\internals\construction.py in _check_values_indices_shape_match(values, index, columns)
    391         passed = values.shape
    392         implied = (len(index), len(columns))
--> 393         raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
    394
    395

ValueError: Shape of passed values is (5, 1), indices imply (5, 2)

A: Got similar problem, trying to create a DataFrame from list:
dt = ['a','b','c']
df = pd.DataFrame(data=dt, columns=['1','2','3'])

Solved by passing the 'data' argument as list of lists:
df = pd.DataFrame(data=[dt], columns=['1','2','3'])

So you should try:
df = pd.DataFrame([query_results], columns = ['Table Name', 'Column Name'])


text:
Q: which is an abstract class? A question from Oracle exam
which is an abstract class? A question from Oracle exam
Thanks

A: Mouse because the name is italicized.
http://www.ibm.com/developerworks/rational/library/content/RationalEdge/sep04/bell/
Within that url search for specifically for this section:

Abstract classes and operations
The observant reader will notice that
  the diagrams in Figures 4 and 5 use
  italicized text for the BankAccount
  class name and withdrawal operation.
  This indicates that the BankAccount
  class is an abstract class and the
  withdrawal method is an abstract
  operation. In other words, the
  BankAccount class provides the
  abstract operation signature of
  withdrawal and the two child classes
  of CheckingAccount and SavingsAccount
  each implement their own version of
  that operation.
However, super classes (parent
  classes) do not have to be abstract
  classes. It is normal for a standard
  class to be a super class.


text:
Q: assign random values to excel cells from visual basic I have tried using the random function in visual basic with string builder but it repeats the same value for each cell... I need all the cells to be different.
what im trying to say is.....
    Dim validchars As String = "abcdefghijklmnopqrstuvwxyz"
    Dim sb As New StringBuilder()
    Dim rand As New Random()
    For i As Integer = 1 To 12
        Dim idx As Integer = rand.Next(0, validchars.Length)
        Dim randomChar As Char = validchars(idx)
        sb.Append(randomChar)
    Next i
    txtPass.Text = sb.ToString
    If txtPass.Text.Length > 1 Then
        Dim newvar As String
        newvar = txtPass.Text
    End If

I need to use this piece of code to assign values to excel cells about 1000 cells.

A: Since you are outputing to Excel, just let Excel handle the random character generation.
The below would create random strings (A-Z, 10 chars long) in a 4x4 grid:
Dim excelRandomChar As String = "CHAR(RANDBETWEEN(65, 90))"
Dim numberOfChars As Integer = 10

' Write generation formula to Excel (replace with your Excel objects).
xlObject.Sheet.Range("A1:D4").FormulaR1C1 = "=" & _
    String.Join(" & ", Enumerable.Repeat(excelRandomChar, numberOfChars).ToArray)


text:
Q: Do we need to clear Integer and string variables? Do we need to clear Integer and string variables?
I mean after we use integer variable, we have to make it zero also string variable have to clear for better memory performance and etc? or nothing happen?
EDIT:
For example this code is running 24h/7 in a server and don't turn off or restart server and calling this procedure more than 3000 time in 5 minute.
procedure somejob;
i:integer;
Test1,Test2,Test3,Test4:string;
begin

 {Some more job....}
i := {BIG INTEGER};
Test1:= {BIG STRING};
Test2:= {BIG STRING};
Test3:= {BIG STRING};
Test4:= {BIG STRING};
{some more job....}

{we have to clear these variables or not?}

i:= 0;
Test1:= '';
Test2:='';
Test3:='';
Test4:='';
end;

A: No, you don't have to clear any variables in that case.
Strings are reference counted in Delphi. That means that string will be freed automatically after execution of the routine.
Integer and other simple types are allocated in stack and disappear when running thread leaves the routine.


text:
Q: Await iterating a datatable with awaitable methods I have the following Async Method, that awaits separate methods on a per row babsis.  I cannot for the life of me figure out how to take this to the next level, and await the whole datatable to be process (i.e have all rows start start together, instead of one at a time).  Any help would be much appreciated.
    Public Async Function GetLabResultPanelPackByPRN_Async(ByVal ClientID As Integer, ByVal PRN As Integer, ByVal SamplePointID As Integer, ByVal StartDate As DateTime, ByVal EndDate As DateTime, ByVal InequalityMode As InequalityModes) As Task(Of List(Of LabResultPanelPack))
    Dim LRPPs As New List(Of LabResultPanelPack)
    Dim ta As New eniCIP_DataTableAdapters.proc_WebPortal_ResultsByPRNTableAdapter
    Dim dt As New eniCIP_Data.proc_WebPortal_ResultsByPRNDataTable
    ta.Fill(dt, PRN)
    For Each row As eniCIP_Data.proc_WebPortal_ResultsByPRNRow In dt
        Dim LRPP As New LabResultPanelPack
        LRPP.LabResult = GetLabResultByPRNFromRow(row, InequalityMode)

        Dim ResultsByDetAndSPTask As Task(Of List(Of LabResultExtended)) = GetResultsByDetAndSP_Async(ClientID, SamplePointID, row.lDetID, StartDate, EndDate, InequalityMode)
        Dim ResultsBySampleTypeAndDetTask As Task(Of List(Of LabResultExtended)) = GetResultsBySampleTypeAndDet_Async(ClientID, row.lSampleTypeID, row.lDetID, StartDate, EndDate, InequalityMode)
        Dim ResultsBySampleTypeGroupAndDetTask As Task(Of List(Of LabResultExtended)) = GetResultsBySampleTypeGroupAndDet_Async(ClientID, row.lSampleTypeGroupID, row.lDetID, StartDate, EndDate, InequalityMode)

        LRPP.HistoricResultsByDetAndSP = Await ResultsByDetAndSPTask
        LRPP.HistoricResultsByDetAndSampleType = Await ResultsBySampleTypeAndDetTask
        LRPP.HistoricResultsByDetAndSampleTypeGroup = Await ResultsBySampleTypeGroupAndDetTask

        LRPPs.Add(LRPP)
    Next

    Return LRPPs
End Function

A: The solution in this case is simply adding a function and things clear up quickly.
If you create a new function that handles the processing of one row like so:
Private Async Function ProcessRow(row As YourRowType, ...) As Task(Of LabResultPanelPack)
  Dim LRPP As New LabResultPanelPack
  LRPP.LabResult = GetLabResultByPRNFromRow(row, InequalityMode)

  'Add your tasks for processing the row further
  Return LRPP
End Function

Now your main loop looks something like this:
For Each row As eniCIP_Data.proc_WebPortal_ResultsByPRNRow In dt
  Dim LRPP = Await ProcessRow(row, ...)
  LRPPs.Add(LRPP)
Next

And at this point you can change your LRPPs list to
Dim LRPPTasks As New List(Of Task(Of LabResultPanelPack))

And change your loop to
For Each row As eniCIP_Data.proc_WebPortal_ResultsByPRNRow In dt
  Dim LRPPTask = ProcessRow(row, ...)
  LRPPTasks.Add(LRPPTask)
Next

This way you avoid waiting for every row and processing the rows continues as soon as the first await inside the ProcessRow function is reached.
All you need to do at the end is change your return to
Return Await Task.WhenAll(LRPPTasks)

And your are done.
Just as a small addition: After rewriting the code as I suggested, you would end up with the only Await in the Function. This means that you could remove the Async flag from the function and the Await from the Return. This way you get a little less overhead.


text:
Q: Zeit Now routing problem. 404 NOT FOUND when reloading pages other than index page Recently I bought a Next.js template on Themeforest and I tried to deploy it to Zeit Now.
This is a monorepo that using Lerna and Yarn workspace. Code of the Next.js app is inside packages/landing folder
Everything is fine with the index page (the page at / route), I can reload it without any problem.
The problem arises when I tried to add a new page inside pages folder. For example /privacy-policy or /terms-of-service, ...
If I navigate the these pages through a <Link /> from the index page, it works fine. But if I tried to reload these pages or send my users a direct link to them, they can't access these pages. Instead, my users will see 404 NOT FOUND.
You can see what I mean by going to this page https://superprops-2-r09pdhfab.now.sh/. It works fine when reloading.
But if you open this page https://superprops-2-r09pdhfab.now.sh/saas, you will see 404 (the code for /saas is also deployed)
In my localhost development, it works fine for all pages when reloading. So I think that the problem is from Zeit Now configuration.
This is the code inside now.json:
{
  "version": 2,
  "builds": [
    { "src": "packages/landing/package.json", "use": "@now/static-build" }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/packages/landing/$1",
      "headers": {
        "x-request-path": "$1"
      }
    }
  ]
}

How to fix this? Thank you.

A: It turns out the template from Themeforest is using a monorepo with the old configuration that is not compatible with Now zero-config anymore.
So my solution is to create a new Next.js project, copy all code and update next.config.js as below.
This part config.resolve.modules.push(path.resolve('./')); saves me from changing any import statement.
const path = require('path');
const withPlugins = require('next-compose-plugins');
const withOptimizedImages = require('next-optimized-images');
const withFonts = require('next-fonts');
const withCSS = require('@zeit/next-css');
module.exports = withPlugins(
  [
    [
      withOptimizedImages,
      {
        mozjpeg: {
          quality: 90
        },
        webp: {
          preset: 'default',
          quality: 90
        }
      }
    ],
    withFonts,
    withCSS
  ],
  {
    webpack(config) {
      // Here is the magic
      // We push our config into the resolve.modules array
      config.resolve.modules.push(path.resolve('./'));
      return config;
    }
  }
);


text:
Q: When should I use inherited scope and when should I not? When creating a directive, When should I use inherited scope (i.e scope:true) and when I should not use it (i.e scope:false )
I understand the difference between scope types and know what each scope type does. But I don't understand when I should choose one of them rather than the other.

A: As per my knowledge following are the decision making criteria

*

*Controller Scope Data Change  -(One direction)-> Directive Scope Data Change : Use inherited scope. Scope : True

*Controller Scope Data Change <-(Both direction)-> Directive Scope Data Change: Use parent scope. Scope : False

*Controller Scope Data Change -(No data change required)- Directive Scope Data Change: Use new isolated scope. Scope : { }
Suppose we have a functionality as:
 {Username} text box (Outside Directive) and
 Hello {Name} (inside directive, and it is being displayed after the {Username} text box).

*

*If the functionality is like changing {Username} should reflect {Name} then use 1.

*If the functionality is like changing {Name} or {Username} will reflect vice versa, then use 2.

*If there is no relation between {Name} and {Username} then use 3.

Though we can use 3(isolated scope) with 3 types of prefixes (@,=,&) by which we can pass the data between scopes and this is the best approach as per my knowledge.


text:
Q: how to append multiple spreadsheets from multiple workbooks to single dataframe in R I have 10 excel(.xlsx)files ,each has 10 spreadsheets.
I need to read 3 spreadsheets from each workbook and finally append it to single dataframe in R.
Data:
header:
 Country    Jan-14  Feb-14  Mar-14  Apr-14  May-14  Jun-14  Jul-14  Aug-14  Sep-14  Oct-14  Nov-14  Dec-14  FY

actual data
 Austria    43  52  64  82  60  61  57  36  110 96  66  64  791
 Belgium    143 258 184 207 202 191 209 118 136 169 121 108 2,046
 Bulgaria   0   0   0   0   0   0   0   0   0   0   0   0   0

Code:
library(XLConnect)
files = list.files("C:/Users/kushaa/Documents/Frost_casestudy/")

sheet.index <- c(3,6,9)

colname = c("Country","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","FY","truck_type")

data.1 <- data.frame(matrix(rep(NA,length(colname)),ncol = length(colname)))

for (i in 1:length(files)){

   wb = loadWorkbook(files[i])
for (j in 1:length(sheet.index)){
   ss = readWorksheet(wb, sheet.index[j],startRow = 5, header = FALSE)
   truck_type = rep(sheet.names[j],nrow(ss))
   df = data.frame(ss,truck_type)
   names(df) <- colname
   data_merge <- rbind(data.1,df)

 }
}

But struck in getting data from one sheet (truck_type= CV) only but not sheets(truck_type = LCV,HCV )
Output:
         Country  Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec    FY truck_type
1           <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>  <NA>       <NA>
2        Austria   43   54   67   90   68   97   65  108   83   75   87   90   927         CV
3        Belgium  275  232  306  235  330  339  279  239  261  211  155  122 2,984         CV

Also how to extract year from filenames:
  [1] "2014_by_country_and_type_Enlarged_Europe.xlsx"
  [2] "20140211_02_2012_vo_By_Country_Enlarged_Europe.xls"
  [3] "20150219_2013_vo_By_Country_Enlarged_Europe.xlsx"

Query:
  regmatches(files, regexpr("[0-9].*[0-9]", files))

But it gives:
 [1] "2014"
 [2] "20140211_02_2012"
 [3]"20150219_2013"

I need output as :
 2014
 2012
 2013


text:
Q: How to update JSON object using Yojson? After reading some examples, it's easy to construct a JSON object by Yojson.Basic.from_string or from_channel.
On the other side, we could also easily to convert a JSON object to string by pretty_to_string.
However, update an JSON object is tricky, for example the input parameter is as follows:
{
    "content": "test content",
    "base" : {
        "version": 1,
        "id" : "a001"
    }
}

I want to update the "id" in it and return a new JSON object:
{
    "content": "test content",
    "base" : {
        "version": 1,
        "id" : "a002"
    }
}

I tried to write a function to update a JSON object:
let update_json (js: json) (key: string) (new_value: string) : json =
  let rec aux (json_ele:json):json =
    match json_ele with
    | `Bool b -> `Bool b
    | `Float f -> `Float f
    | `Int i -> `Int i
    | `List jl -> `List (List.map jl ~f:aux)
    | `Null -> `Null
    | `String st -> `String st
    | `Assoc kvlist ->
        `Assoc (
        List.map
          kvlist
          ~f:(fun (okey, ovalue) ->
              match ovalue with
              | `String v when okey = key -> (okey, `String new_value)
              | _ -> (okey, aux ovalue)))
  in
  aux js

I was wondering if writing a function as above is the best way to update a JSON object in Yojson?

A: I'm not clear on what you mean by "bugs", but `Assoc doesn't take a string * json, it takes a (string * json) list. This means that in your `Assoc cases, you should do a List.map:
| `Assoc pairs ->
  List.map pairs ~f:(fun (okey, ovalue) ->
    if okey = key then
      key, new_value
    else
      okey, aux ovalue)

You may want to factor this function out and give it a name.


text:
Q: 1 byte 8 bit encoding I need to create System.String from file with some unknown ASCII-compatible 1-byte encoding to replace some numbers in text with regex, but Encoding.ASCII is 7-bit, and Utf-8 is multi-byte so it won't round-trip back to same byte sequence.
Is there encoding in .Net Core which can round-trip any byte sequence?
UPD: Windows-1256 Character set looks promising, but it Windows only.

A: Firstly, if you don't know the encoding, using the string is more a hack than a solution. I guess it can be quicker and possibly easier, but for more robust and clean solution, I'd just work on byte[] or something similar. String would be fine, if it's use-once solution.
If you really want to use strings here, I'd suggest looking into all encodings from windows/cp family or ISO 8859 family. E.g. on my PC, I can use iso-8859-1. Windows 1256 would also be fine, on Linux is often called cp 1256 (CP for Code Page).
However, you are not guaranteed to have that encoding supported on all platforms, AFAIK .NET guarantees only UTFs and Unicode. If you want to have this encoding available everywhere, consider using nuget package like this: https://www.nuget.org/packages/System.Text.Encoding.CodePages/

A: Using ISO-8859-1 will map directly to Latin-1 Supplement Unicode block and back again. And it is one of encodings .NET Core supports by default.
var enc = Encoding.GetEncoding(28591); // ISO-8859-1 (code page 28591)
var b = Enumerable.Range(0, 0xFF + 1).Select(x => (byte)x).ToArray();

enc.GetBytes(enc.GetString(b)).SequenceEqual(b) == true