text:
Q: Error when typing "git commit"? I'm building a ROM but I need a commit into /frameworks/base repo. So i "git fetch" the Github repo and then I type "git commit xxxxx", but the output is:

error: pathspec xxxxx did not match any file(s) known to git.

Any help?

A: You need to do these things in order..
Fetch All Branches
git fetch --all

Check Branch Name
git branch

Then Checkout to branch
git checkout your_branch_name

Now, while committing

*

*Add all files you want to commit in the staging area
git add . (for all files)
git add filename (for respective file)

*Commit to local database
git commit -m "your custom message"

*Push to remote repo

git push origin current_branch_name
Here, origin is the remote name.

A: Try
git checkout -b yourbranchname

And then try again.

A: I think you should clarify some concepts of git before using.
1) 'git fetch' only update those refs to remote branches, it do not merge remote modifications to your worktree. You need run 'git pull' to merge with your worktree.
2) you need a branch to work on. You can run 'git checkout -b' to create a new one, or 'git checkout --track' to create one tracking remote branch.


text:
Q: Uniqueness of Equilibum Solution in an Autonomous 1st order ODE Suppose we have to solve the ODE:
$$\frac{dx}{dt} = f(x) ,\forall t\geq 0 \text{ and } x(0) = x^{*}$$
where $f(x^{*}) = 0$
If we don't know anything about f(x), one obvious solution is $x(t) = x^{*}, \forall t \geq 0$. It satisfies both the ODE and the initial condition.
Intuitively this should be the only solution: we start from a point at which the rate of change of the state vector is $0$, so we should remain there for ever.
Can this be proven?
Under which circumstances is this true?
Are there any edge cases, maybe depending on f(x) e.g. if it is not continuous etc?
I am aware of the uniqueness-existence theorem, however since this seems to be a special problem, if you could help me with intuition.
Any help is appreciated!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Field 'browser' doesn't contain a valid alias configuration with webpack compilation error While running cypress tests getting error:
Error: Webpack Compilation Error
Module not found: Error: Can't resolve 'C:UsersCypressode_modulescypress-cucumberpreprocessorlibesolveStepDefinition' in 'C:\Users\Cypress\cypress\integration\features'
resolve 'C:UsersCypressode_modulescypress-cucumber-preprocessorlibesolveStepDefinition' in 'C:\Users\Cypress\cypress\integration\features'
  Parsed request is a module
  using description file: C:\Users\CypressProject\package.json (relative path: ./cypress/integration/features)

My webpack config file:
module.exports = {
  resolve: {
    extensions: [".ts", ".js"]
  },
  node: { fs: "empty", child_process: "empty", readline: "empty" },
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: [/node_modules/],
        use: [
          {
            loader: "ts-loader"
          }
        ]
      },
      {
        test: /\.feature$/,
        use: [
          {
            loader: "cypress-cucumber-preprocessor/loader"
          }
        ]
      }
    ]
  }
};

My plugins index.js file

// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************

// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)

/**
 * Used to setup TypeScript support in cypress
 */
const wp = require('@cypress/webpack-preprocessor')
const fs = require('fs-extra')
const path = require('path')

function getConfigurationByFile (file) {
  const pathToConfigFile = path.resolve('./cypress/', 'config', `${file}.json`)
  return fs.readJson(pathToConfigFile)
}

module.exports = (on,config) => {
    const file = process.env.ENV_FILE//config.env.envFile
  const options = {
    webpackOptions: require("../webpack.config.js")
  };
  on('file:preprocessor', wp(options))
  if(file==null){
  return getConfigurationByFile('local');
  }
  else{
    return getConfigurationByFile(file);
  }
}

I observed \ , \n , \r missing from the path(1st line of error), due to this only everything is failing I guess. I cleared all the cache but no luck.
Anyone has idea regarding this. Thanks in advance.


text:
Q: blob image display in flutter from mysql database how do we get image from MySQL database and display in flutter?
I have tried many things but I am unable to do it. I converted the blob image but that too isn't working.
and also I am not able to display the whole data even if it is in listview...!
Below is the code for it -:
import 'package:education/Screens/Home_View.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'dart:typed_data';

class ScheduleClass extends StatefulWidget {
  @override
  _ScheduleClassState createState() => _ScheduleClassState();
}

class _ScheduleClassState extends State<ScheduleClass> {

  var course_id, class_id, dates, schedule_image;
  var data;

  Future<http.Request> getData() async
  {
    var client = new http.Client();
    final response = await client.get('http://192.168.0.104:5000/class_schedule');
    final responseJson = json.decode(response.body);
    setState(() {
      dynamic courseid = responseJson['courseid'];
      dynamic classid = responseJson['classid'];
      dynamic date = responseJson['date'];
      dynamic scheduleimage = responseJson['scheduleimage'];
      var blob = responseJson['scheduleimage'];

      Uint8List image = Base64Codec().decode(blob);      // image is a Uint8List

      class_id = classid;
      course_id = courseid;
      dates = date;
      schedule_image = image;
      data = responseJson;

    });

    print(responseJson);
    client.close();
    // return responseJson;
  }

  int i = 1;

  @override
  void initState(){
    getData();
    super.initState();
    print([class_id].length);
  }

  @override
  Widget build(BuildContext context) {
    print({class_id}.length.toString());

    return Scaffold(
      appBar: AppBar(
        title: Text('Class Schedules'),
        backgroundColor: Colors.deepPurpleAccent,
        centerTitle: true,
        elevation: 15,
        leading: InkWell(
          child: Icon(Icons.arrow_back_ios),
          onTap: (){
            Navigator.pushReplacement(context, MaterialPageRoute(
                builder: (context) => homeView()
            ));
          },
        ),
      ),
      body: ListView.separated(
        itemCount: [class_id].length,
        itemBuilder: (context, index) {
          return Padding(
            padding: const EdgeInsets.all(10.0),
            child: Card(
              elevation: 10,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [

                  Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Text(
                      '${dates[i]}',
                      style: TextStyle(
                        fontSize: 20,
                      ),
                    ),
                  ),

                  Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Container(
                      height: 500,
                      child:  Center(
                        child: Image.memory(
                          schedule_image[i],    //'img/ico.jpg',
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),

                ],
              ),
            ),
          );
        },
        separatorBuilder: (context, index) {
          return Divider();
        },
      ),
    );
  }
}

below is the data that I want to display.
I/flutter ( 4830): {alternateno: [7845659877, 9865358577], coachaddress: [anand vihar, delhi, delhi, Gautam Budha nagar, noida], coachemail: [abc@gmail.com, xyz@gmail.com], coachid: [1, 2], coachname: [abc Coaching, xyz Coaching], primary_number: [9865328899, 9898557898], userid: [1, 1]}

please help...


text:
Q: Qwt - how to get the select point index with QwtPlotPicker I plot complex data using QwtPlot, so, I reimplement QwtSeriesData for converting my data into QPointF. The "sample(int)" converts MyObject to QPointf. My QwtSeriesData data manages a
myVector=vector<MyObject>;

Now, I need to select point drawn into my plot. I try to use QwtPlotPicker but it only returns a QPointF.
How to get the index "idx" of the selected point in order to get myObject=myVector[idx]?

A: Use the closestPoint() method in the curve.
int QwtPlotCurve::closestPoint  (   const QPoint &      pos,
    double *    dist = NULL
)

It will return the id of the closest point in the curve!
Hope this helps you.


text:
Q: Optimization of tag searching in XML file I'm writing custom function for getting all tags in an XML file. I'm using this code:
wchar_t *GetLine(wchar_t *fileName=L"indexing.xml", wchar_t endSymbol = '\n')
{
    SetFilePointer(hReadFile,sizeof(wchar_t) * position, NULL, FILE_BEGIN);
    int size;
    wchar_t wchr[1];
    DWORD dw;
    size = 0;
    do
    {
        ReadFile(hReadFile, wchr, sizeof(wchar_t), &dw, NULL);
        if(!dw)
        {
            break;
        }
        tempGetLine[size] = wchr[0];
        size++;
    }while(wchr[0] != endSymbol);
    tempGetLine[size] = '\0';
    position += (size);
    return tempGetLine;
}
wchar_t *GetTag(wchar_t *fileName = L"indexing.xml")
{
    wchar_t *temp = GetLine(fileName,'>');
    int i = 0;
    while(*temp != '\0')
    {
        tempTag[i] = *temp;
        i++;
        temp++;
    }
    tempTag[i] = '\0';
    return tempTag;
}

It works, but in a large file it takes a lot of iterations. How can I optimize my code?

A: You should probably consider moving to a propper parser generator.
A good C++ library for such a task is boost spirit-qi, there is even an XML example.
http://www.boost.org/doc/libs/1_51_0/libs/spirit/doc/html/index.html
xml example

A: It looks like you're calling SetFilePointer() for every single tag.  If you aren't doing any other reads or writes to the file in between calls to GetTag(), don't bother calling SetFilePointer() at all.  It's unnecessary, and it's possible that this call is reducing the amount of buffering done by the OS.


text:
Q: How to filter a list in-place with Kotlin? In Java I can remove items from a list with this code:
private void filterList(List<Item> items) {
    Iterator<Item> iterator = items.iterator();
    while (iterator.hasNext()) {
        if (checkItem(iterator.next())) {
            iterator.remove();
        }
    }
}

How to make the same in Kotlin (i.e. remove some items in a List without re-creation)?

A: Just use .retainAll { ... } or .removeAll { ... }, both accepting a predicate, to filter it in-place:
items.retainAll { shouldRetain(it) }

items.removeAll { shouldRemove(it) }

Note that items should be a MutableList<T> for that, not just List<T>, which is a read-only list in Kotlin and thus does not expose any mutating functions (see: Collections in the language reference).
By the way, these two function are implemented efficiently for lists that support random access: then the list is not compacted after each item is removed (O(n2) time worst-case), and instead the items are moved within the list as it is processed, giving O(n) time.

And if you don't want to modify the original list, you can produce a separate collection with only the items you want to retain using .filter { ... } or .filterNot { ... }, this will work for read-only List<T> as well:
val filtered = items.filter { shouldRetain(it) }

val filtered = items.filterNot { shouldRemove(it) }

A: Kotlin has a lot of neat built-in functions. You can try to use filter here.
val filteredItems = items.filter { checkItem(it) }

Unfortunately, it will recreate the list. This API was designed on purpose to avoid extra mutability.
But if you still want to proceed with a MutableList use retainAll method
items.retainAll { checkItem(it) }

A: This will remove even numbers from the list 1-9, and prints [1, 3, 5, 7, 9]
var myLists = mutableListOf(1,2,3,4,5,6,7,8,9)
myLists.removeAll{ it % 2 == 0 }
println(myLists)

This will retain even numbers and remove others from the list 1-9, and prints [2, 4, 6, 8]
myLists = mutableListOf(1,2,3,4,5,6,7,8,9)
myLists.retainAll{ it % 2 == 0 }
println(myLists)

Try them in https://play.kotlinlang.org/


text:
Q: custom prefix discord.py, json file I have looked at all the turorials, all the forums, and they all say the same thing about a custom prefix for a discord bot.
I've tried it and it doesnt work.
I've EVEN tried to copy-paste the code and changing the names.
idk what to do now, here's my code:
def get_prefix(client, message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

client = commands.Bot(command_prefix = get_prefix, help_command = None)
slash = SlashCommand(client, sync_commands = True)

@client.event
async def on_ready():
    activity = discord.Game(name="!help", type=3)
    await client.change_presence(activity=activity)
    print('online !')

@client.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(guild.id)] = '!'

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.event
async def on_guild_remove(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes.pop(str(guild.id))

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

and here's my error message:
Ignoring exception in on_guild_join
Traceback (most recent call last):
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\ethom\PycharmProjects\discord\rocket_bot\rocket.py", line 32, in on_guild_join
    prefixes = json.load(f)
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

A: In most cases your json.load - JSONDecodeError: Expecting value: line 1 column 1 (char 0) error is due to :

*

*non-JSON conforming quoting

*XML/HTML output (that is, a string starting with <), or

*incompatible character encoding

Ultimately the error tells you that at the very first position the string already doesn't conform to JSON.
Try to debug to verify the content of the file you reading :
@client.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as f:
        #Verify the content is really "{}"
        print(f.read())
        prefixes = json.load(f)

    prefixes[str(guild.id)] = '!'

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

If this verification don't pass, you will need to specify the fix path of your 'prefixes.json' as 'complete_path/prefixes.json' to make sure the correct file is read.
You can also try, if it's not a path problem, to change the encoding when you read the file:
 with open('prefixes.json', 'r') as f:
      prefixes = json.loads(f.read().encode("utf-8"))

A: I have answered my own question.
It says that the json file isn't found but in fact, it's not a code problem.
It's a file problem, I have deleted the __pycache__ file and it suddenly worked correctly.
So, my conclusion is that you have to have no directories in your bot folder.
so, have a nice day ! I hope my response worked for you.


text:
Q: Exam class \ifincomplete not playing nicely with \include I often write exams of the form:
\documentclass[a4paper,11pt,leqno,nocancelspace]{exam}
\begin{document}
  \begin{center}\begin{framed}
  {\bfseries \large EXAMINATION}
\end{framed}\end{center}
\pagebreak
\cfoot{\ifincomplete{\textit{Question continues on next page.}}{}}

\begin{questions}
\include{question_catalogue/first_topic_qn}
\pagebreak
\include{question_catalogue/second_topic_qn}
\end{questions}
\cfoot{}\newpage
\ \vfill
\cfoot{\textit{This page is intentionally left blank.}}\newpage
\ \vfill
\newpage
\ \vfill
\newpage\
\ \vfill
\end{document}

And then each of the questions are in separate files, and are of the form:
\titledquestion{First topic}
This is a question on the first topic.
\begin{parts}
\part Answer this
\begin{solutionorbox}[\stretch{1}]
\end{solutionorbox}
\part Answer that
\begin{solutionorbox}[\stretch{1}]
\end{solutionorbox}
\pagebreak
\part Answer something else
\begin{solutionorbox}[\stretch{1}]
\end{solutionorbox}
\end{parts}

I have just noticed that the footer on the last page of the final question incorrectly says "Question continues on next page." Having played around with things it appears that the problem is the use of \include. When I switch the \include of the last question to \input the footer looks correct. While I'm happy I can write exams this way, it's a little unsatisfactory/hacky that I can't use a standard LaTeX command like \include. Are there any other ways around this problem?

A: \include is designed for top level constructs such as \chapters (specifically things where you need to save the document state so that units can be skipped with \includeonly). So you should use \input here. Changing the page header mid-document is most reliable at a forced page break \include uses  \clearpage before and after the \included text so perhaps that is what you want here.
\clearpage\input{zzzzz}\clearpage

A: If you put the command \nomorequestions immediately following the last question, all should be well.


text:
Q: Example in Milnor's Morse theory book ,$f^{-1}[a,b]$ is not compact I was reading Milnor's Morse theory book,in chapter three , there is a picture to illustrate the case that $f^{-1}[a,b]$ is not compact.
For the theorem that sublevel set diffeomorphic to each other if no critical point in between,and $f^{-1}[a,b]$ is compact.
there is a remark below which says :The condition that $f^{-1}[a, b]$ is compact cannot be omitted. For example Figure $3.2$ indicates a situation in which this set is not compact. The manifold $M$ does not contain the point $p$. Clearly $M^{a}$ is not a deformation retract of $M^{b}$.
the question is why $f^{-1}[a,b]$ is not compact in the picture and why they are not diffeomorphic.

A: The subset $f^{-1}[a,b]$ is not compact because of the hole at $p$. Arguing with sequences should be enough. The spaces $M^a$ and $M^b$ are not diffeomorphic and $M^a$ not a deformation retract of $M^b$, since they have different fundamental groups. Can you point out why?


text:
Q: If certain radio buttons checked, display div else display different div? :) So I'm trying to create a user questionaire type form, it doesnt have to send to anyone just display a div once certain radio buttons are checked and if them certain radio buttons arent checked then display a different div, but also when the webpage opens/refreshes none of the div's I want to display to be displayed (if that makes sense?). I found some code on here to try but it didnt work for me, I'm a noob with JS & Jquery but was hoping anyone could shed some light on my problem. please find my code below.
Jquery?
if($('input[value=yes1]:checked,
 input[value=yes2]:checked,
 input[value=yes3]:checked,
 input[value=yes4]:checked').length == 4){

$("#correct").show();

 }else{

$("#correct").hide();

HTML

            <input type="radio" id="yes1" value="yes1" name="iCheck1">
            Yes
            </input>

            <input type="radio" id="no1" name="iCheck1">
            No
            </input>

            <input type="radio" id="yes2" value="yes2" name="iCheck2">
            Yes
            </input>

            <input type="radio" id="no2" name="iCheck2">
            No
            </input>

                Yes

                No

                Yes

                No

CSS
#correct{width:100%; height:50px; background:green; display:none;}
#incorrect{width:100%; height:50px; background:red; display:none;}

A: I think this is what you're looking for. I had to change the number of "correct" answers to two because that's all the html you have.
JS:
$( "input" ).on( "click", function() {
    if($('input[value=yes1]:checked, input[value=yes2]:checked').length === 2){
       $("#correct").show();
    }else{
       $("#correct").hide();
    }
});

Working JS Fiddle: http://jsfiddle.net/akj84vrq/12/

A: A little something like this would probably get you what you want.
http://jsfiddle.net/uu512erm/
Listen for change event on the radio inputs by $('input:radio').change(function(){}
and then just add the logic inside.

A: I'm not sure that this can be accomplished via CSS.
Now, you are checking against some values/elements that don't exist in your code (ie input[value=yes3]:checked, you don't have input with that value, check it for yourself).
I don't understand what exactly you want to accomplish, but I will still try to help and since you're new let's keep it very basic:
if ($('input[value=yes1]').is(':checked') && $('input[value=yes2]').is(':checked')) {
  // this will fire only if input with values yes1 and yes2 is checked
  $('div_to_show').show(); // put your own selectors here
  $('div_to_hide').hide(); // put your own selectors here
}

if ($('input[value=no1]').is(':checked') && $('input[value=no2]').is(':checked')) {
  // this will fire only if input with values no1 and no2 is checked
  $('some_other_div_to_show').show(); // put your own selectors here
  $('some_other_div_to_hide').hide(); // put your own selectors here
}

if ($('input[value=yes1]').is(':checked') && $('input[value=no1]').is(':checked')) {
  # this will fire only if both input with values yes1 and no1 is checked
  $('some_other_div_to_show').show(); # put your own selectors here
  $('some_other_div_to_hide').hide(); # put your own selectors here
}

# and so on... just type in your conditions and that's it.

If you need some other cases, just add them using this pattern or construct one complex else if statement with all your scenarios.


text:
Q: ANDROID_SDK_ROOT=undefined (recommended setting) ANDROID_HOME=undefined (DEPRECATED) getting error whenever i'm trying to ionic build.showing
cordova-plugin-androidx-adapter: Processed 16 source files in 387ms
Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=undefined (recommended setting)
ANDROID_HOME=undefined (DEPRECATED)
i changed sdk version and i'm using sdk 30 version also change path.but still getting same error

A: This issue should arise because of missing local.properties file where the SDK location is stored. Just check if its present in your project, if not just add it with the correct SDK location from your computer.

A: Try changing your SDK path to C:\Android\SDK
have a look at my environmental variable settings as under and try once


text:
Q: Triggering a function using `ng-click` inside a bootstrap modal I have an app where users can submit posts for review, when they click on the add post button I use a bootstrap to confirm their choice. The bootstrap modal contains a "confirm" button which actually triggers a function.
For some reason that button does not work when placed inside the modal. It works if placed outside the whole modal, anywhere within the body tag.
Below is the code:
<button type="submit" id="createPostBtn" class="btn btn-default" data-toggle="modal" data-target="#confirmModal">CONFIRM & SEND POST</button>

 <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-default" ng-click="addPost('<%= uid %>')">Confirm</button>
  </div>

What am I missing here? Any help will be greatly appreciated.

A: if you want to use bootstrap modal in your angularJS project, you have to use "UI Bootstrap's" directives. visit this


text:
Q: Image Buttons click are not working in IE 11 while clicking on it in c# asp.net Image Button Click is working sometimes. sometimes notihng is happening when i click on it.
I have given two image buttons in gridview.
Im using .Net Framework 4.5
getting error in  __doPostBack('Download_Click','') only in IE 11
Aspx code
<asp:ImageButton ID="gridbtndownload" ToolTip="Download" CommandName="Download"
 OnClientClick="link();"  CommandArgument='<%#((GridViewRow) Container).RowIndex %>'
 runat="server" ImageUrl="Download_Icon.png" alt="Download" />

cs code
DirectoryInfo folder = new DirectoryInfo(mypath); folder.Delete(true);

A: There is a well known IE 10/11 bug, which requires you to upgrade .NET Framework and ASP.NET to workaround,
https://connect.microsoft.com/VisualStudio/feedback/details/755419/asp-net-4-0-and-ie10-click-on-imagebutton-in-updatepanel-produces-error-click-on-normal-button-does-not
Try to follow the direction if your call stack matches it.
Make sure that next time you post as much information as possible so that others can help you out. When you type too little, your question will be voted to close.


text:
Q: Add a div arround a while loop I have this script.
var $bigList = $('.list-products'), group;
while((group = $bigList.find('li:gt(3):lt(4)').remove()).length) {
    $('
').append(group).appendTo('.box-products');
}

But i want a div around every .
$('

').append(group).appendTo('.box-products');

But that is not working. What do i wrong?

A: It looks like you are creating a div, but not actually adding the
 tag as a child, try something like:
 $('

').append($('
').append(group)).appendTo('.box-products');

or if that still doesn't solve your problem, you may want to split the statement.
 var $div = $("

");
 $div.append($('
').append(group)).appendTo('.box-products');

I don't have time to make a fiddle, but I can if neither of these solutions work.


text:
Q: Is there a `USING` clause in SQLAlchemy core? I'm using SQLAlchemy on MySQL database. Is there a way I can use MySQL's USING clause to join tables?
e.g.
SELECT *
FROM
  a JOIN b
    USING(some_id, other_id);

A: Short answer
No.
Longer answer
You could write a compiler extension to render the statement, but I don't think it is worth the effort. Explanation below.
In MySQL you don't have to use USING to join tables. It's considered syntactic sugar over the more general ON construct.
SQLAlchemy does not include handling the special case that the join columns have the same name (main use-case for using USING). It always uses the most general approach (ON).
As SQLAlchemy will render all ON statements for you, and in most cases will infer the join-relationships from your Table definitions and thus obviating the need to specify the join condition at all, this is not necessarily more work.
Example
t1 = Table('a', metadata,
           Column('id', Integer))
t2 = Table('b', metadata,
           Column('id', Integer),
           Column('fk', Integer, ForeignKey('a.id')))

sel = select([
    t1.c.id,
    t2.c.id,
]).select_from(
    t1.join(t2)  # please note, no ON or USING
)
print sel

Will result in
SELECT a.id, b.id
FROM a JOIN b ON a.id = b.fk


text:
Q: PAM's passwd retry prompt fail I am trying to use PAM to stop password reuse. Adding 'remember=24' to pam_unix stores the old passwords hashed with MD5 which I find unnerving. I was recommended 'pam_pwhistory' instead. Here is the password section of my /etc/pam.d/system-auth file that /etc/pam.d/passwd includes
password    requisite     pam_cracklib.so retry=3 try_first_pass
password    requisite     pam_pwhistory.so remember=24 retry=3 use_authtok
password    sufficient    pam_unix.so sha512 rounds=5000 shadow use_authtok
password    required      pam_deny.so

When I try to change my password, if I fail the password reuse test, I don't get to retry. Instead a "Password:" prompt appears
$ passwd
(current) Unix password: <current password>
New password: <old password>
Retype new password: <old_password>
Password has already been used. Choose another.
Password: <current password>
passwd: Authentication token manipulation error

I have a similar same issue if I fail the pam_cracklib test more than the retry #. Except that my current password works with the prompt
$ passwd
(current) Unix password: <correct password>
New password: <too simple password>
BAD PASSWORD: it too simple
New password: <too simple password>
BAD PASSWORD: it too simple
New password: <too simple password>
BAD PASSWORD: it too simple
Password: <current password>
passwd: Have exhausted maximum number of retries for service

If I set retry=1 for pam_pwhistory, then the current password works for the prompt.
$ passwd
(current) Unix password: <current password>
New password: <old password>
Retype new password: <old_password>
Password has already been used. Choose another.
Password: <current password>
passwd: Have exhausted maximum number of retries for service

The inablility to retry if you use an old password and this strange 'Password: ' are the only problem. Old passwords are stored in /etc/security/opasswd using their original hash function.
It looks like

*

*pam_pwhistory can't retry because it's in the middle of the stack?

*A failure in pam_pwhistory doesn't cause pam_unix to fail, it instead
prompts user?
I am on a CentOS 6.3


text:
Q: Does $\int_\cdot f\int_\cdot g$ have the same ordering as $\int_\cdot fg$? Fix an integer $N\geq 2$ and let $f,g:[0,1]\to\mathbb{R}^+$ be continuous. We will divide $[0,1]$ into $N$ subintervals of equal size (disregarding overlapping edges);
$$I_n:=[(n-1)/N,n/N],\qquad n=1,\ldots,N.$$
I'm trying to show that
$$\int_{I_k}f\cdot\int_{I_k}g\leq \int_{I_l}f\cdot\int_{I_l}g\quad\Rightarrow\quad \int_{I_k}fg\leq \int_{I_l}fg.$$
However, I'm not sure whether or not it holds in general. I have managed to break down that if we assume the LHS and additionally assume that there exists a permutation $(n_1,\ldots,n_N)$ of $(1,\ldots,N)$ such that
$$\min_{I_{n_1}}f \:\cdot\: \min_{I_{n_1}}g\leq \max_{I_{n_1}}f \:\cdot\: \max_{I_{n_1}}g\leq\ldots\leq \min_{I_{n_N}}f \:\cdot\: \min_{I_{n_N}}g\leq \max_{I_{n_N}}f \:\cdot\: \max_{I_{n_N}}g,\tag{1}$$
then there exists such a permutation with $i< j$ if $k=n_i$, $l=n_j$ and $k\neq l$ since
$$\min_{I_{n}}f \:\cdot\: \min_{I_{n}}g\leq N^2\int_{I_n}f\cdot \int_{I_n}g\leq \max_{I_{n}}f \:\cdot\: \max_{I_{n}}g.$$
Hence
$$\int_{I_k}fg \leq \max_{I_k}fg\leq \max_{I_{k}}f \:\cdot\: \max_{I_{k}}g\leq \min_{I_{l}}f \:\cdot\: \min_{I_{l}}g\leq\min_{I_l} fg\leq \int_{I_l} fg.$$
But I'm not sure if $(1)$ is a reasonable assumption. I also tried to consider average function values, but it has led me nowhere yet. Perhaps I should look at the integrals as an inner product?

A: I've discovered a counter example for non-continuous $f$ and $g$. Set $N=2$, $c\in[2/3,1)$ and define
$$f = \tfrac{1}{2}\mathbf{1}_{[0,1/2)} + c\mathbf{1}_{[1/2,3/4)}\quad\text{and}\quad g = \tfrac{1}{2}\mathbf{1}_{[0,3/4)} + \mathbf{1}_{[3/4,1]}.$$
Then
$$\int_{0}^{1/2}f \cdot\int_{0}^{1/2}g = \frac{1}{16}\quad\text{and}\quad \int_{1/2}^1 f \cdot\int_{1/2}^1g = \frac{c}{4} \cdot \frac{3}{8} = \frac{3c}{32}\geq\frac{1}{16},$$
but
$$\int_{0}^{1/2}fg = \frac{1}{8}\quad\text{and}\quad \int_{1/2}^1fg = \frac{c}{8}<\frac{1}{8}.$$
For arbitrary $N$ we may can
$$f = \tfrac{1}{N}\mathbf{1}_{[0,1/N)} + c\mathbf{1}_{[1/N,1/N+1/N^2)}\quad\text{and}\quad g = \tfrac{1}{N}\mathbf{1}_{[0,1/N+1/N^2)} + \mathbf{1}_{[1/N+1/N^2,1]}$$
and we can derive a similar contradiction. With this idea in mind, it is conceivable that by smoothly approximating $f$ and $g$ above, we can derive a set of continuous functions for which this does not hold. So it is not true and the reverse statement can also be refuted by the same counter example.


text:
Q: How to pass byte arrays by reference in C# (to C code in a DLL) I'm having trouble figuring out how to pass an I/O array of bytes
from C# to a C routine (which is in a DLL).  By "I/O" I mean that
the C# code wants to setup the data in the array, call the C routine,
and see modified data in the array when it comes back.
(Using Visual Studio 2008 on Win XP.)
I'd been told by various sources that arrays in C# were always
passed by reference ... so I hoped "char [] buf" would be
the solution.  It doesn't appear to be ... it seems like C# is
doing sneaky stuff behind my back (e.g., passing a copy of the data?).
(I've searched, but haven't found a useful "C# for C programmers" that
discusses parameter passing from C# to C :)
(If I could determine how to get the address of 'stemp' below within C#,
I could display it before the call to the C code and after it ...
and display the incoming address within the C code.)
Here's the main C# code:
[DllImport("c:/home/sieler/source/upshift.dll")]
internal static extern void ss_upshift1 (char [] buf, Int32 bytes);

static void Main(string[] args)
   {

   char [] stemp = new char [132];
   string s;

   s = "Testing\n\0";
   stemp = s.ToCharArray ();
   Console.WriteLine (stemp);  // I see "Testing" on console window

   ss_upshift1 (stemp, 7);     // Inside the C routine, I see "Testing\n" and
                               // I change it to "TESTING\n"

   Console.WriteLine (stemp);  // I see "Testing", which is WRONG!

When I come back from ss_upshift1, 'stemp' still has the unchanged
data (even though I know the data was modified...I can print 'stemp'
from inside the C "ss_upshift1" routine before and after the
upshifting!).
If I make the 'buf' parameter be 'out', then (a) I see a buffer of nulls
in the C code (as if C# was saying "I'll allocate you a fresh buffer as
a copy of 'stemp', and zero the buffer, and pass its address),
and if I put data into the buffer within C, the C# code traps when I
come back from ss_upshift1.  (If I don't put in data in C, no trap
(and no useful data, of course :).)
C# doesn't appear to have an "io" tag (as opposed to 'out' or 'ref').
If I make the 'buf' parameter be 'ref', then C# sends the address of the
address of the buffer (e.g., like char **buf in C).  The C code can
dereference it, find the data ... but if the data is changed, the
calling C# code does NOT see the changed data!
So, to ask a formal question: how do I pass an array of byte data from
C# to C, and get modified data back?
thanks,
Stan


text:
Q: command line compliation error Running into some problems with a one liner....
ls *.fq.gz | cut -f 1 -d . | uniq | perl -pe 'chomp; system "bwa-0.7.9a mem  -M /refs/GATK_bundle_2.3//human_g1k_v37.fasta -R'@RG\tID:Foo\tSM:bar' $_.1.fq.gz $_.2.fq.gz > $_.sam"'

Output is
[E::bwa_set_rg] the read group line is not started with @RG
CLMP10920-1[E::bwa_set_rg] the read group line is not started with @RG
CLMP10920-2[E::bwa_set_rg] the read group line is not started with @RG
CLMP10920-3[E::bwa_set_rg] the read group line is not started with @RG
CLMP10920-4W[E::bwa_set_rg] the read group line is not started with @RG
COL1A110908-1[E::bwa_set_rg] the read group line is not started with @RG
COL1A110908-2[E::bwa_set_rg] the read group line is not started with @RG
COL1A110908-3[E::bwa_set_rg] the read group line is not started with @RG
COL1A110908-4Wgleadalln@mgcl01:~/testing/analysis$

Done some reading around but struggling to find a solution for running this command - think it has something to do with the nested ' in the -R option part of the command.... is there any way to escape these?

A: Perl doesn't have a sys function. Did you mean system?
Also, the syntax highlighter is correct about quotes. The signle quote in R'@RG ends the first single quoted string, which doesn't seem right.


text:
Q: Meta programming and runtime code generation I have a requirement where I need to generate the function arguments at runtime.
At compile time, I do not know the number of arguments or their type. It has to be read from a file at runtime, generate the code and dynamically loaded.
I have used the M4 macro generation language before. It provides great performance at the sacrifice of readability and usability.
I did not want to go that route this time and was thinking of using C++11 Variadic templates.
Is there a better alternative?

A: Varadic templates won't work because you will need to know at compile-time all possible argument type lists, and then instantiate a template for each one.
Your problem is essentially run-time serialization and de-serialization of types.  C++ doesn't have any "in-built" standard way to do this.
You will need to create some GenericParameter type and then have:
`vector<GenericParameter*> params`

or similar.  Then for each type you want to encode create a derived class of GenericParameter to box it.  When you serialize a set of parameters you need to create and store some sort of type id for each derived class, and then serialize the data for that class.  Likewise in the opposite direction you read the type id, construct the appropriate derived class of that type id, and then fill it in with the data for that class.
After you have this you may be able to use varadic templates to verify that a vector of params matches a compiled-in function, and bind the runtime vector to the statically known signature of a function, as well as automatically generate the adapter that takes the generic vector and unboxes the parameters into native types.  Likewise in the other direction.
Something to look at is called protobuf, it is heavily used at Google for this sort of thing, and I have heard good things about it.


text:
Q: IMAP partial fetch in mutt The IMAP protocol supports a feature called 'partial fetch', which allows a client to download only a part of a MIME message. This is very useful on slow connections
I am using the mutt MUA. I would like to tell mutt to only download the first part, or only download the text/plain parts, or some other similar rule

*

*Does mutt support IMAP partial fetch?

*If it doesn't, is there any other way to download only a small part of a big message using mutt [ and maybe other programs ]

A: According to http://dev.mutt.org/trac/ticket/3465 mutt does not yet support partial fetch. I'm not aware of a workaround in this case, and any possible workaround would likely be problematic (attachments would be difficult to download, etc) to implement such a solution.

A: I just came across this question while looking for the same facility in Mutt. I have found that on my slow connection I often end up killing mutt to stop it from re-downloading big messages that I accidentally navigate into. However I just found that there is an option to cache messages as well as headers
set message_cachedir="~/.mutt_msgcache"

In this way I only have to wait for the message to download once. This makes it much more usable.  I guess if I had read the help I would have been aware of it sooner...


text:
Q: Rendering difference in custom control I'm currently facing problems rendering an sap.suite.ui.microchart.InteractiveDonutChart. I want to render it in a custom control. When I try to render a simple control like sap.m.Text, it works just fine. However, it doesn't with the donut chart. Generating the donut chart like this in a controller works just fine, though. Any ideas as to why this doesn't work? It doesn't give me any errors...
aggregations
aggregations: {
                content: {
                    type: "sap.ui.core.Control",
                    multiple: true,
                    singluarName: "content"
                }
            }

renderer
        //start of content
        oRM.write("
");
        oRM.renderControl(oControl.getChosenControl());
        oRM.renderControl(oControl.getChosenControl2());
        oRM.write("
"); // close div 3
        //end of content

functions
getChosenControl: function() {
        var flexBox = new sap.m.FlexBox({
            width: "90%",
            alignItems: "Center"
        });

        var textField = new sap.m.Text({
            text: "Dynamically created textfield"
        });

        flexBox.addItem(textField);
        return flexBox;
    },

    getChosenControl2: function() {

        var flexBox = new sap.m.FlexBox({
            width: "90%",
            alignItems: "Center"
        });

        var donutChart = new sap.suite.ui.microchart.InteractiveDonutChart();

        for (var i = 0; i < 3; i++) {
            var segment = new sap.suite.ui.microchart.InteractiveDonutChartSegment();
            segment.setLabel("Parter");
            segment.setValue(50);
            segment.setDisplayedValue("50 %");

            donutChart.addSegment(segment);
        }

        flexBox.addItem(donutChart);
        return flexBox;
    }

A: I actually found a solution myself. I first added it to my aggregation 'content' with the 'AddContent' method. The next step is to get the content with the 'getContent' method. The last step is to render the returned content.
            //start of content
                oRM.write("
");

                //add content
                oControl.addContent(oControl.getChosenControl2());

                //get content
                var items = oControl.getContent();

                //render items
                for (var i = 0; i < items.length; i++) {
                    oRM.renderControl(oControl.getContent()[i]);
                }

                oRM.write("
"); // close div 3
                //end of content


text:
Q: JS: Check if word "handover" contains "hand" I'm working on this simple, straightforward text content filtering mechanism on our post commenting module where people are prohibited from writing foul, expletive words.
So far I'm able to compare (word-by-word, using .include()) comment contents against the blacklisted words we have in the database. But to save space, time and effort in entering database entries for each word such as 'Fucking' and 'Fuck', I want to create a mechanism where we check if a word contains a blacklisted word.
This way, we just enter 'Fuck' in the database. And when visitor's comment contains 'Fucking' or 'Motherfucker', the function will automatically detect that there is a word in the comment that contain's 'fuck' in it and then perform necessary actions.
I've been thinking of integrating .substring() but I guess that's not what I need.
Btw, I'm using React (in case you know of any built-in functions). Much as possible, I wanna deviate from using libraries for this mechanism.
Thanks a heap!

A: "handover".indexOf("hand")

It will return index if it exists otherwise -1
To ignore cases you can define all your blacklisted words in lower case and then use this
"HANDOVER".toLowerCase().indexOf("hand")

A: To detect if a string has another string inside of it you can simply use the .includes method, it does not work on a word by word basis but checks for a sequence of characters so it should meet you requirements. It returns a boolean value for if the string is inside the other string

var sentence = 'Stackoverflow';

console.log(sentence.includes("flow"));

A: You were on the right track with .includes()
console.log('handover'.includes('hand'));

Returns true


text:
Q: I am trying to pass data from one View Controller to another in Swift via 'prepare for segue' but it crashes Good evening,
I am trying to pass data from one View Controller to another, but it crashes my program in the final View Controller. Can anyone help me?
This is the ViewController:
func updateAfterPlayAgain(){
    labelSay.text = ">Result<"

    scoreLabel.text = "Score: 0"

    score = 0

    seconds = 10

    mainButton.isEnabled = true

    userResult.isUserInteractionEnabled = true
}

This is the PopUpViewController:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    var fate: ViewController = segue.destination as! ViewController
    fate.updateAfterPlayAgain()
}

It is from this one that I am trying to access the data from ViewController when it(PopUpViewController) closes. I would like to update the information in the ViewController when I close the PopUpViewController.
Thank you.

A: When prepareForSegue is called the destination view controllers' views haven't been loaded, so all of it's outlets will be nil.
Outlets are set up as implicitly unwrapped optionals, and that causes a crash if you try to reference an outlet that's nil. That's why you're crashing.
You should not call updateAfterPlayAgain() from prepareForSegue, since it tries to reference your outlets before they are connected. Instead call updateAfterPlayAgain() from viewWillAppear (or better yet from viewDidLoad, since that only gets called once when a view controller's views are first loaded.)

A: @Banjo, your question is not completely clear. Please add the crash it self so we will have more information ti help you.
From what I see, when you create a screen, the @IBOutlet labels, are still nil until the screen performs the "viewDidLoad" method, therefore, instead of updating the screen in the prepare(for segue), I'd set a flag using a boolean, i.e.: "requiresUpdate: Bool", and set it here, then in the viewDidAppear, check the flag and call updateAferPlayAgain.
If you are talking about dismissing a controller and updating the main controller instead, you should read about how to use "unwind segues" and handling their events, this way the parent controller gets the event of the displayed controller closing.
This article should help you with that:
https://spin.atomicobject.com/2014/10/25/ios-unwind-segues/
Good luck.


text:
Q: psubscribe scheduled to be closed ASAP for overcoming of output buffer limits this error message has been logged. It has only happened once in about 2 months. We have a sub pub client listening for Redis events. What kind of problem could be causing it? What actions can we take to mitigate it?
Here is the detailed error:

Client id=599475 addr=10.250.0.50:44012 fd=1370 name= age=18039 idle=1 flags=N db=0 sub=0 psub=1 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=555 omem=9085669 events=rw cmd=psubscribe scheduled to be closed ASAP for overcoming of output buffer limits.

Redis is configured to post events to the pub sub using the notify-keyspace-events setting to "AKE". The code used (python) is like this:
#...
redis: StrictRedis = StrictRedis(config.REDIS_HOST, config.REDIS_PORT)
pubsub = redis.pubsub()
pubsub.psubscribe("keyevent@0:*")
PAUSE = True
while PAUSE:
    message = pubsub.get_message()
    if message:
        #.. do something
        time.sleep(0.001)


text:
Q: Difference between Amazon S3 cross region replication and Cloudfront After reading some AWS documentations, I am wondering what's the difference between these different use cases if I want to delivery (js, css, images and api request) content in Asia (including China), US, and EU.

*

*Store my images and static files on S3 US region and setup EU and Asia(Japan or Singapore) cross region replication to sync with US region S3.

*Store my images and static files on S3 US region and setup cloudfront CDN to cache my content in different locations after initial request.

*Do both above (if there is significant performance improvement).
What is the most cost effective solution if I need to achieve global deployment? And how to make request from China consistent and stable (I tried cloudfront+s3(us-west), it's fast but the performance is not consistent)?
PS. In early stage, I don't expect too many user requests, but users spread globally and I want them to have similar experience. The majority of my content are panorama images which I'd expect to load ~30MB (10 high res images) data sequentially in each visit.

A: Cross region replication will copy everything in a bucket in one region to a different bucket in another region. This is really only for extra backup/redundancy in case an entire AWS region goes down. It has nothing to do with performance. Note that it replicates to a different bucket, so you would need to use different URLs to access the files in each bucket.
CloudFront is a Content Delivery Network. S3 is simply a file storage service. Serving a file directly from S3 can have performance issues, which is why it is a good idea to put a CDN in front of S3. It sounds like you definitely need a CDN, and it sounds like you have tested CloudFront and are unimpressed. It also sounds like you need a CDN with a larger presence in China.
There is no reason you have to chose CloudFront as your CDN just because you are using other AWS services. You should look at other CDN services and see what their edge networks looks like. Given your requirements I would highly recommend you take a look at CloudFlare. They have quite a few edge network locations in China.
Another option might be to use a CDN that you can actually push your files to. I've used this feature in the past with MaxCDN. You would push your files to the CDN via FTP, and the files would automatically be pushed to all edge network locations and cached until you push an update. For your use case of large image downloads, this might provide a more performant caching mechanism. MaxCDN doesn't appear to have a large China presence though, and the bandwidth charges would be more expensive than CloudFlare.

A: If you want to serve your files in S3 buckets to all around the world, then I believe you may consider using S3 Transfer acceleration. It can be used in cases where you either upload to or download from your S3 bucket . Or you may also try AWS Global Accelerator

A: CloudFront's job is to cache content at hundreds of caches ("edge locations") around the world, making them more quickly accessible to users around the world. By caching content at locations close to users, users can get responses to their requests more quickly than they otherwise would.
S3 Cross-Region Replication (CRR) simply copies an S3 bucket from one region to another. This is useful for backing up data, and it also can be used to speed up content delivery for a particular region. Unlike CloudFront, CRR supports real-time updating of bucket data, which may be important in situations where data needs to be current (e.g. a website with frequently-changing content). However, it's also more of a hassle to manage than CloudFront is, and more expensive on a multi-region scale.
If you want to achieve global deployment in a cost-effective way, then CloudFront would probably be the better of the two, except in the special situation outlined in the previous paragraph.


text:
Q: Will weak pointer in a block become dangling when I refer it with stong pointer in OC? as the question described, will the wSelf in block become dangling?
1    void bindDefaultCallbacks {
2   __weak typeof(self) wSelf = self;
2   [sessionManager setDataTaskDidReceiveDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSData * _Nonnull data) {
4            __strong typeof(self) sSelf = wSelf;
5            if (!sSelf) {
6                return;
7            }
8
9            // will wSelf here become dangling ?
10           APIRequest *apiRequest = [wSelf apiRequestForTask:dataTask];
11           NSURLResponse *response = dataTask.response;
12           apiRequest.urlResponse = response;
13        }];
14 }

crash info:
Exception Codes: SEGV_ACCERR at 0x0000000000000010
Exception Type: SIGSEGV

0 XXX ___73-[XXXX bindDefaultCallbacks:withSessionManager:]_block_invoke.251 (in XXX) 420
1 XXX -[AFURLSessionManager URLSession:dataTask:didReceiveData:] (in XXX) (AFURLSessionManager.m:1156) 20

A: At line 10, you will not have a dangling pointer. ARC will ensure that the pointer is valid or nil (Chris's reference explains this). However, it is possible that at line 10, the pointer will be nil. There is no promise that the sSelf reference will continue after line 5 since it is not used after that.
There is also no promise that that wSelf will be nil at line 10. Either situation is valid. It is only promised that it is either a valid pointer to self or nil.
The formal definition of this rule comes from the Clang documentation discussion of Precise Lifetime Semantics (emphasis added):

In general, ARC maintains an invariant that a retainable object pointer held in a __strong object will be retained for the full formal lifetime of the object. Objects subject to this invariant have precise lifetime semantics.
By default, local variables of automatic storage duration do not have precise lifetime semantics. Such objects are simply strong references which hold values of retainable object pointer type, and these values are still fully subject to the optimizations on values under local control.
A local variable of retainable object owner type and automatic storage duration may be annotated with the objc_precise_lifetime attribute to indicate that it should be considered to be an object with precise lifetime semantics.

See the surrounding section on "Object liveness" for more explanation.
While it would be very difficult for this particular code to fail (the object would need to be deallocated on a different thread during a very brief window between line 5 and line 10), this general situation is actually a fairly common cause of bugs. In debug builds, strong references tend to live until the end of their scope, but in optimized builds, they tend to be released as quickly as possible. So code that works fine during development can fail (or even crash if you're using raw pointers into objects you believe are being retained) when shipped.
This bug was so common that there are annotations in UIKit to help prevent it. If you look at UIColor.h, you'll see the CGColor property defined this way:
@property(nonatomic,readonly) CGColorRef CGColor;
- (CGColorRef)CGColor NS_RETURNS_INNER_POINTER CF_RETURNS_NOT_RETAINED;

The NS_RETURNS_INNER_POINTER is a warning to ARC that this pointer should cause the object's lifetime to be extended even though normally ARC wouldn't require it. (This was an obnoxious and common cause of crashes in the early days of ARC.)

A: According to the Apple Documentation the weak self pointer will not become dangling:

By capturing the weak pointer to self, the block won't maintain a strong relationship back to the XYZBlockKeeper object. If that object is deallocated before the block is called, the weakSelf pointer will simply be set to nil.

The block in the sample code captures a strong reference to self so if sSelf is non-nil then wSelf should remain non-nil for the life of the block. However, after capturing a strong reference to self, it's typically preferable to exclusively use the strong reference inside the block.


text:
Q: When a transfinite sequence converges with respect the order topology? Is the limit of a transfinite sequence necessarly its supremum? Let be $s_\theta$ a transfinite sequence $(\alpha_\nu)_{\nu\in\theta}$ of length an ordinal theta $\theta$. So any ordinal is totally ordered with respect the usual order relation so that any ordinal is a directed set with respect this relation and moreover it is a well know result that the same relation induced a topology (the order topology) whose prebase is given by the initial and final segment: so observing that
$$
\alpha_\nu\le\sup_{\nu\in\theta}\alpha_\nu
$$
for each $\nu\in\theta$ I like to discuss when $\sup_{\nu\in\theta}\alpha_\nu$ is the limit with respect the order topology on any ordinal $\alpha$ strictly greater then $\sup_{\nu\in\theta}\alpha_\nu$.
So on this purpose we suppose that $s_\theta$ is strictly increasing and moreover we suppose that $\theta$ is a limit ordinal: so in this case $s_\theta$ have not a maximum element and thus (see here for details) $\sup_{\nu\in\theta}\alpha_\nu$ is a limit ordinal so that any its neighborhood contains on the left elements of $s_\theta$ and so in this case $\sup_{\nu\in\theta}\alpha_\nu$ is effectively the limit of $s_\theta$ in $\alpha$ which is moreover the unique limit since the order topology is an hausdorff topology. Anyway more generally if $s_\theta$ has not a maximum element then by the $\underline{\text{same}}$ reasons we exhibited above  $\sup_{\nu\in\theta}\alpha_\nu$ is a limit ordinal and thus another time it is the unique limit of $s_\theta$ in $\alpha$. However if $s_\theta$ has a maximum element $\alpha_{\nu_*}$ then surely
$$
\sup_{\nu\in\theta}\alpha_\nu=\bigcup_{\nu\in\theta}\alpha_\nu=\alpha_{\nu_*}
$$
so that I argue that $\sup_{\nu\in\theta}\alpha_\nu$ is not the limit of $s_\theta$ if $\alpha_{\nu_*}$ is a successor ordinal but this does not prove that $s_\theta$ has not a limit.
So having did these observations I like you explain if they are correct with appropriate argumentations and then I like you show if $s_\theta$ has a limit in the last case: in particular I would like to understand if the limit of a transfinite sequence is necessarly its supremum provided it exists. So could you help me, please?


text:
Q: Is there a way to generate a report in SharePoint showing number of items added to a list/library per day? I currently have a view setup to filter by created items greater than or equal to [today]-1.  Is there another way to get this information without using a view?  I looked at Site Collection audit settings, Audit log reports, Popularity and Search Reports but they don't meet my needs.  Ideally I would like a list or count of items added to a list/library every night and I would like to filter by items.

A: If a code based solution is fine then, I would recommend a simple windows task which executes a powershell script exe which would run every morning and calculate the no. of items added to that particular list from "startdate" to "EndDate". The start date and end date can be calculated based on the current time.
Then it can send out an email or generate an excel or anything that you want to do.
If you have access to the server. Consider a timer job .

A: SharePoint Designer Workflow or Power Automate (Used to be called as Flow) are options to do so.
In workflow you may need to turn to Rest Api to get the item count and more information.
Here is an example for you to follow:https://sharepoint.stackexchange.com/questions/220502/how-to-get-a-list-of-items-created-within-a-certain-time-frame
Example for Flow:https://powerusers.microsoft.com/t5/Building-Flows/FLOW-Get-Items-Filter-SharePoint-list-on-Date/td-p/85238


text:
Q: Force calling the derived class implementation within a generic function in C#? Ok so I'm currently working with a set of classes that I don't have control over in some pretty generic functions using these objects. Instead of writing literally tens of functions that essentially do the same thing for each class I decided to use a generic function instead.
Now the classes I'm dealing with are a little weird in that the derived classes share many of the same properties but the base class that they are derived from doesn't. One such property example is .Parent which exists on a huge number of derived classes but not on the base class and it is this property that I need to use.
For ease of understanding I've created a small example as follows:
class StandardBaseClass {} // These are simulating the SMO objects

class StandardDerivedClass : StandardBaseClass {
    public object Parent { get; set; }
}

static class Extensions
{
        public static object GetParent(this StandardDerivedClass sdc) {
            return sdc.Parent;
        }

        public static object GetParent(this StandardBaseClass sbc)
        {
            throw new NotImplementedException("StandardBaseClass does not contain a property Parent");
        }

        // This is the Generic function I'm trying to write and need the Parent property.
        public static void DoSomething<T>(T foo) where T : StandardBaseClass
        {
            object Parent = ((T)foo).GetParent();
        }

}

In the above example calling DoSomething() will throw the NotImplemented Exception in the base class's implementation of GetParent(), even though I'm forcing the cast to T which is a StandardDerivedClass.
This is contrary to other casting behaviour where by downcasting will force the use of the base class's implementation.
I see this behaviour as a bug. Has anyone else out there encountered this?

A:
I see this behaviour as a bug.

This behavior is correct.  Since your method DoSomething is constraining T to StandardBaseClass, you only have access to the specific methods of StandardBaseClass, not any methods or properties of a derived class.  Since StandardBaseClass does not have a Parent property, this is invalid, and should be invalid, by design.
There are two potential options here - You can use reflection to pull out the Parent property, or use C# 4's dynamic type, and treat this as a dynamic object.  Both bypass the standard type checking in the compiler, however, so will require you to do extra type checking at runtime to verify that the Parent property exists.

A: Create an interface that contains the Parent property. Have each class that has a Parent property implement that interace. You will then be able to create a generic method that accepts a parameter of type IHaveParent, and it will do the right thing.

A: For anyone that is interested an succinct answer to this situation is answered by Stephen Cleary on msdn here:
http://social.msdn.microsoft.com/Forums/en-AU/csharpgeneral/thread/95833bb3-fbe1-4ec9-8b04-3e05165e20f8?prof=required

A: To me this is a divergence in the class hierarchy. By this this I mean that either the base class has parent, or the derived classes with Parent are derived from an abstract child of the base.
Lol as John says, an interface as opposed to an abstract class is sufficient too.

A: You idea won't work because the compiler can never guarantee that the base class actually would have such a property. And it won't just select the "right" one based on if it has it or not.
The only way you can do this is using reflection and then test at runtime if the requested property exists on the inspected class. You have to judge yourself if that is a viable way to do for your project (reflection is slow and requires maximum rights).

A: This is correct, as the compiler only knows that it can bind to your type as a StandardBaseClass. The binding is not done at runtime (where it could potentially decide to use the StandardDerivedClass overload.
If you know that it's a StandardDerivedClass, then why not just cast it as such?
object Parent = ((StandardDerivedClass)foo).Parent;

A: It's a bit ugly, but you can accomplish this using a Registration system, where you register delegates for different possible derived classes that expose the 'shared' property/method and then use something like a Dictionary<Type,Func<SomeT>> to store the delegates.  If you know all of the derived types ahead of time and don't have to load plug-ins or the like, you can also use the classic ugly if/else-if structure.  Either way you're basically creating your own substitute for what should have been supported by the virtual method table.


text:
Q: Separability measures I am just studying pattern recognition. In that regard, my question is
Why we need separability measures?
Would you please give me detail explanation and suggest some books to read?

A: I think the main use of separability measures is to asses the quality of your chosen features under a given classification problem without relying in accuracy estimates for particular classifiers.
And, sometimes you may have a pretty bad performance under a given classifier, so, it might be because your classifier is not appropriate to deal with your data (i.e. you are using a classifier giving linear decision boundaries, when class separation in your data is non linear), or because your data cannot be separable under any kind of decision function (distribution of target classes for your data points approaches randomness)
I found cut edge weight statistic (Zighed, Djamel A., et al., 2002. "Separability Index in Supervised Learning. Principles of Data Mining and Knowledge Discovery".) useful for this purpose.


text:
Q: how to increment between a range of dates using javascript I need to increment between a range of dates using javascript. I have start_date and end_date in the following format.
var start_date = Fri Nov 09 2012
var end_date = Thu Nov 15 2012

I need to call a function which accepts all the dates by looping between start dates and end dates as parameter. Something like this
for (date = start_date; date < end_date; date++) {
    getCellFromDate(date, calInstance);
}

I need to provide the parameters to getCellFromDate in the same date format(Fri Nov 09 2012) . How do I achieve this..I am new to javascript.. Please help

A: To do the iteration in pure JavaScript, without the aid of any other date library, you can change
date++

to
date = new Date(date.getTime() + 86400000)

That will go to the next day at the same time.  There are 86400000 milliseconds in a day.
This will iterate through date objects.  You will need to use a date formatter and parser to go back and forth between date objects and strings.  There are many ways to do this.  See this SO question for help.

A: date.setDate(date.getDate() + 1);

Works for any number of days, negative and positive:
function addDays(date, count) {
    date.setDate(date.getDate() + count);
}

A: Its better to use some date libraries. It helps you in more functions
some advanced and commonly used date libraries are

*

*http://code.google.com/p/datejs/

*http://momentjs.com/


text:
Q: 404 while trying to generate pdf with reportlab I am trying to implement option to generate pdf file for download from views.py. For now I am using sample code provided in django docs however for some reason when I try to generate sample pdf I get 404 error with message that:
The current path, stv/DRG_result, didn't match any of these.

--bunch of urls paths--

The current path, stv/DRG_result, didn't match any of these.

That seems logical, because I did not set any path in urls.py for that (since there was no info that it is needed).
Should I set it? Can somebody tell me how to do it correctly, since I am very new to django. Or error is somewhere else?
My relevant views.py part:
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def DRG_result(request):

    buffer = io.BytesIO()
    p = canvas.Canvas(buffer)

    p.drawString(100, 100, "hello world.")

    p.showPage()
    p.save()

    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

Code part for the button from the template which calls this function:
    <form action='DRG_result' method='GET'>
        {% csrf_token %}
        <button type="submit" >Generuoti PDF</button>
    </form>

A: I find out how to amend urls.py file. Turn out I needed to add this:
from django.conf.urls import url

urlpatterns = [
    url(r'^DRG_result/$', views.DRG_result, name='DRG_result'),
]


text:
Q: firefox (Gecko) conditional style sheet today I'm trying to optimize my website for a better rendering in firefox!
my problems are the text-shadow and font-weight properties ... I would like to set custom values only for firefox (my website is mac only compatible so I don't need IE compatibility) but I don't wont to use separate style sheet for only these two properties!!!
There is any way to do that? Or I must use a php script to filter the user agent and load customized style sheets for firefox?
Thanks in advance!

A: Okay, it is a little late but for people like me who weren't happy to hear the answer above, there is a way to do it.

A: You can use the CSS Browser Selector.

A: You seem like you would want to support ONLY browsers which support text-shadow, so why only target Firefox? Your approach should be to only change font-weight for those browsers which support text-shadow. But this is easier said than done.
Browser sniffers are not going to work unless they can differentiate between Firefox 3.5 and earlier versions. The one linked to by KahWee would not achieve this, but I would NOT recommend browser sniffing anyway -- it is not best practice.
I would instead recommend setting font-weight to whatever is meant for use with text-shadow, and then include an IE conditional to reset the majority of visitors' browsers back to the original, non-shadowed font-weight.
Example:

With this you will achieve text-shadow with proper font-weight in these browsers:

*

*Firefox 3.5+

*Opera 9.5+

*Safari 1.1+ (Since 2003!)

*Chrome 2.0+

*Konqueror 3.4+

And if you want drop shadow in IE you can use filter expressions with DropShadow(), but I personally do not recommend using proprietary CSS extensions.
Your only real "loss", then, would be having an improper font-weight for older, non-IE browsers like Firefox 3.0 and lower, and Opera 9.2x and lower.
So is it really worth JavaScript or PHP browser sniffing to change the font-weight for a very limited subset of older browsers?
If the answer is still yes, there are PHP browser sniffers like this one.

A: Conditionals are for IE only, sorry. Maybe some of those functions can help you, they work in gecko browsers only: Mozilla css extensions


text:
Q: Javascript Event Binding does not work correctly? I have created a list (navigation menu) with 2 different rows. Each of this row is connected to a diagram. For instance row 1 (Temperature) is connected to Temperature diagram (table1 and table2).
I want the user to decide which table to view by clicking on the navigation menu, and if the person wish to view another table the first diagram has to be closed before the next one comes up. So what do I have to do in javascript (JQuery) in order to do this link up the row1 with the table1 and row2 with table2?
The problem is that when I click on the next row, nothing happens.
This index.html:

This is javascript inside another file where I have included in index.html.

Exhaust Temperature

Cylinder Pressure


text:
Q: Laravel 8: How can I make an implicitly model bound route parameter optional instead of throwing 404? I've tried to combine the Laravel docs on implicit binding and optional parameters and have the following code.
routes file:

Route::get('go/{example?}', [ExampleController::class, 'click'])->name('example');

And in the controller:
public function click(Example $example = null)
{
    // Execution never reaches here
}

Execution never reaches the controller unless there is an Example with the correct slug, as it throws a 404. I want to check if $example is null in the controller and use custom logic there. How can this be accomplished?

A: Try this
Route::get('go/{example?}', [ExampleController::class, 'click'])->name('example');

public function click($example)
{
    if($example != null){
        $example = Example::findOrfail($example);
    }

}

in model binding it will automatically run findOrfail to that model so don't you that so you will have control over it then you can manage

A: the @ettdro answer is perfect (and all credit is to him), but i think  an answer with actual code would be useful:
routes:
Route::get('go/{example?}', [ExampleController::class, 'click'])->name('example');

controller:
public function click(Example $example)
{
    // Stuff
}

Model of Example:
 /**
 * Retrieve the model for a bound value.
 *
 * @param  mixed  $value
 * @param  string|null  $field
 * @return \Illuminate\Database\Eloquent\Model|null
 */
public function resolveRouteBinding($value, $field = null)
{
    $result=$this->where('id', $value)->first();
    return ($result)?$result:new Example();
}

You should obtain in the controller always a valid object, empty or not.
Had the same problem, and i'm happy with this solution.

A: To do that, you need use 'id' as your primary key in database and model,
if you are using another name for your pimary key, then you need to define it at your route:
Route::get('go/{example:number?}', [...]);


text:
Q: Compatibility scripting: Save $? for use later I would like to write a small part of a script that saves the error status, executes some other code, and sets the error status to the original error status. In Bash it looks like this:
<< some command >>; _EXIT=$?;( <<other code here>> ;exit $_EXIT)

But I need code that will run no matter if it is being run under bash, zsh, csh or tcsh. I do not know which shell will be used in advance, because it is decided by the user. The user also decides << some command >>.
It is safe to assume that << other code >> will work in all shells, but it is not safe to assume that you can write a file (so putting it into a file will not work).
Background
GNU Parallel executes commands given by the user in the shell decided by the user. When the command is finished, GNU Parallel has some cleanup to do. At the same time GNU Parallel needs to remember the exit value of the command given by the user. The code run before the snippet above is the user given command. << other code >> is the cleanup code.

A: Use perl:
perl -e '$a=shift; `<< other code >>`; exit $a' $? # Fails in csh

Edit This works in csh, too (and zsh, tcsh, sh, pdksh, ksh93 - though not fish):
perl -e '$a=shift; `<< other code >>`; $a=~s/h// and exit $a; exit shift' "$?h" "$status"

A: This answer works in bash-like shells and csh-like shells, and it doesn't require perl:

sh -c '<< other code >>; [ "$0" != "" ] && exit "$0"; exit "$1"' "$?" "$status"

or you can add a dummy/pad parameter:
sh -c '<< other code >>; [ "$1" != "" ] && exit "$1"; exit "$2"' foo "$?" "$status"

and the test can be changed to [ ! -z "$0" ] (or "$1").
I don't know whether it will work in zsh or fish.
Every shell that I'm familiar with will evaluate $? and $status
when the command is parsed, and pass them to the sh -c command as parameters.
The sh shell assigns them to the last two positional parameters.
When the "other code" finishes, the shell will check the positional parameter
that got its value from $? to see whether it is null or non-null,
and exit with the appropriate positional parameter value.
This will fail if the ambient shell uses something other than $? or $status
to hold the exit status.  It will also fail if the shell allows $? to be set
(non-null) if it is not the exit status, or if $? is an invalid character sequence
that causes the entire command to be rejected as a syntax error.


text:
Q: HATEOAS RepresentationModelAssembler, POST with JSON body returns 500: IllegalArgumentException: Not enough variable values available to expand 'id' I followed the Spring on Building REST tutorial using HATEOAS at: https://spring.io/guides/tutorials/rest/ and mixed it with JPA and MySQL DB (Maven). When I run the app, I can see the initial 2 tables in MySQL workbench fine (although there is a 3rd one appearing out of nowhere?). If i perform a GET /players, it works fine. When I do a POST Request (http://localhost:8080/players) in Postman with body as JSON: { "playerName":"Pedro" }, I get a 500 status and I get an error from Spring

Not enough variable values available to expand 'id'] with root cause...

I would like to achieve full CRUD operations. A lot of doubts arises here, given that playerId is autoincrement, and the parameter registrariondate is a TIMESTAMP. This is secondary, as I guess the problem comes from making use RepresentationModelAssembler in my app, but not quite sure how to handle the responses and the petitions.
Here the project structure:

Log of the error:
Hibernate:
    insert
    into
        player
        (player_name, registration_date)
    values
        (?, ?)
2021-04-02 11:20:03.781 ERROR 2312 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: java.lang.IllegalArgumentException: Not enough variable values available to expand 'id'] with root cause

java.lang.IllegalArgumentException: Not enough variable values available to expand 'id'
    at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:370) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:263) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.util.HierarchicalUriComponents$FullPathComponent.expand(HierarchicalUriComponents.java:917) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:434) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:52) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.util.UriComponents.expand(UriComponents.java:172) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.util.DefaultUriBuilderFactory$DefaultUriBuilder.build(DefaultUriBuilderFactory.java:403) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.hateoas.UriTemplate.expand(UriTemplate.java:272) ~[spring-hateoas-1.2.5.jar:1.2.5]
    at org.springframework.hateoas.Link.expand(Link.java:361) ~[spring-hateoas-1.2.5.jar:1.2.5]
    at org.springframework.hateoas.Link.toUri(Link.java:434) ~[spring-hateoas-1.2.5.jar:1.2.5]
    at RESTApiJWTAuthMySQL.controllers.PlayerController.createNewPlayer(PlayerController.java:66) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.44.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.5.jar:5.3.5]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.44.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.5.jar:5.3.5]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.5.jar:5.3.5]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.5.jar:5.3.5]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.5.jar:5.3.5]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.44.jar:9.0.44]
    at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

Controller class:
@RestController
//@RequestMapping("/")
public class PlayerController {

    @Autowired
    private final PlayerRepository repository;
    @Autowired
    private final PlayerModelAssembler assembler;

    PlayerController(PlayerRepository repository, PlayerModelAssembler assembler) {
        this.repository = repository;
        this.assembler = assembler;
    }

    @GetMapping("/players/")
    public CollectionModel<EntityModel<Player>> all() {

      List<EntityModel<Player>> players = repository.findAll().stream().map
              (assembler::toModel).collect(Collectors.toList());

      return CollectionModel.of(players, linkTo(methodOn(PlayerController.class).all()).withSelfRel());
    }

    @GetMapping("/players/{id}")
    public EntityModel<Player> one(@PathVariable Long playerId) {

      Player player = repository.findById(playerId).orElseThrow(() -> new PlayerNotFoundException(playerId));

      return assembler.toModel(player);
    }

    @PostMapping(path="/players", consumes="application/json")
    public ResponseEntity<?> createNewPlayer(@RequestBody Player newPlayer) {

      EntityModel<Player> entityModel = assembler.toModel(repository.save(newPlayer));

      return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()).body(entityModel);

    }

    @PutMapping("/players/{id}")
    public ResponseEntity<?> replacePlayer(@RequestBody Player newPlayer, @PathVariable Long playerId) {

        Player updatedPlayer = repository.findById(playerId) //
          .map(player -> {
            player.setPlayerName(newPlayer.getPlayerName());
            return repository.save(player);
          }) //
          .orElseGet(() -> {
              newPlayer.setPlayerId(playerId);
            return repository.save(newPlayer);
          });

      EntityModel<Player> entityModel = assembler.toModel(updatedPlayer);

      return ResponseEntity //
          .created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()) //
          .body(entityModel);
    }

    @DeleteMapping("/players/{id}")
    public ResponseEntity<?> deleteEmployee(@PathVariable Long playerId) {

          repository.deleteById(playerId);

          return ResponseEntity.noContent().build();
    }
}

PlayerModelAssembler class:
@Component
public class PlayerModelAssembler implements RepresentationModelAssembler<Player, EntityModel<Player>> {

  @Override
  public EntityModel<Player> toModel(Player player) {

      return EntityModel.of(player, //
            linkTo(methodOn(PlayerController.class).one(player.getPlayerId())).withSelfRel(),
            linkTo(methodOn(PlayerController.class).all()).withRel("players"));
  }
}

Player Entity class:
@Entity
@Table(name = "Player")
public class Player {

    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long playerId;

    @Column (name = "player_name")
    private String playerName;

    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column (name = "registration_date", updatable = false)
    private Date registrationDate;

    @OneToMany (mappedBy="player", cascade = CascadeType.ALL, orphanRemoval=true)
    private List<DiceRoll> diceRolls = new ArrayList<>();

    public Player() {

    }

    public Player(Long playerId, String playerName, Date registrationDate) {
        this.playerId=playerId;
        this.playerName = playerName;
        this.registrationDate = registrationDate;
    }

    //getter&setters//

    @Override
      public boolean equals(Object o) {

        if (this == o)
          return true;
        if (!(o instanceof Player))
          return false;
        Player player = (Player) o;
        return Objects.equals(this.playerId, player.playerId) && Objects.equals(this.playerName, player.playerName)
            && Objects.equals(this.registrationDate, player.registrationDate);
      }

      @Override
      public int hashCode() {
        return Objects.hash(this.playerId, this.playerName, this.registrationDate);
      }

      @Override
      public String toString() {
        return "Player{" + "id=" + this.playerId + ", name='" + this.playerName + '\'' + ", date of registration='" + this.registrationDate + '\'' + '}';
      }
}

POM file:
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.10.Final</version><!--$NO-MVN-MAN-VER$-->
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.hateoas</groupId>
            <artifactId>spring-hateoas</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Schema.sql:
USE `dicegame`;

DROP TABLE IF EXISTS `Player`;

CREATE TABLE IF NOT EXISTS `Player`
(
    `player_id` BIGINT PRIMARY KEY  AUTO_INCREMENT,
    `player_name` VARCHAR(45) NOT NULL,
    `registration_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DROP TABLE IF EXISTS `DiceRoll`;

CREATE TABLE IF NOT EXISTS `DiceRoll`
(
    `diceRoll_id` BIGINT PRIMARY KEY AUTO_INCREMENT,
    `d1` INT(55) NOT NULL,
    `d2` INT(55) NOT NULL,
    `result` VARCHAR(45) NOT NULL,
    `diceRoll_registration` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `player_id` BIGINT NOT NULL
);

ALTER TABLE DiceRoll
ADD constraint FK_PLAYER_ID  FOREIGN KEY (player_id)
      REFERENCES Player (player_id);

Any help or direction would be much appreciated. I see in the tutorial they use the curl petiton as:
$ curl -v -X POST localhost:8080/players -H 'Content-Type:application/json' -d '{"playerName": "Pedro"}'

and it should work. Many thanks.

A: The method PlayerModelAssembler.toModel(Player player) uses PlayerController.one(@PathVariable Long playerId) to generate a self link.
If the name attribute of the annotation @PathVariable is not provided, Spring expects the parameter name is same as the name surrounded by {} in @GetMapping.
In your original code, the parameter name playerId is different from id. So to fix it,
@GetMapping("/players/{id}")
public EntityModel<Player> one(@PathVariable("id") Long playerId) {
}

or
@GetMapping("/players/{id}")
public EntityModel<Player> one(@PathVariable Long id) {
}

or
@GetMapping("/players/{playerId}")
public EntityModel<Player> one(@PathVariable Long playerId) {
}


text:
Q: How to do error http error handling in Go language I am little confused on how error handling should be done in go. I have read so many posts about it but still am not able to apply them on my structure of code. I am new to go so please help.
There is a main function which handles two apis: api1 and api2
func main() {
    http.HandleFunc("/offers", api1)
    http.HandleFunc("/getOffersList", api2)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func api1(w http.ResponseWriter, req *http.Request) {
    validateRequestHeader(w, req, "GET")
    // code here....
}

func api2(w http.ResponseWriter, req *http.Request) {
    validateRequestHeader(w, req, "POST")
    //code here....
}

func validateRequestHeader(w http.ResponseWriter, req *http.Request, allowedMethod string) {
    // allow cross domain AJAX requests
    w.Header().Set("Content-Type", "application/json")
    if origin := req.Header.Get("Origin"); origin != "" {
        w.Header().Set("Access-Control-Allow-Origin", origin)
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers",
            "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    // Stop here if its Preflighted OPTIONS request
    if req.Method == "OPTIONS" {
        return
    }
    if req.Method != allowedMethod {
        response := "Only " + allowedMethod + " requests are allowed"
        http.Error(w, response, http.StatusMethodNotAllowed)
        return
    }
}

In both api1 and api2 , function validateRequestHeader is getting called. If this gets true, then in the api1/api2 further code is getting executed which I do not want. How it should be handled?
if req.Method != allowedMethod {
        response := "Only " + allowedMethod + " requests are allowed"
        http.Error(w, response, http.StatusMethodNotAllowed)
        return
    }

A: This blog post goes into some details on how to chain multiple handler functions, which is what you should be doing. That way, you can have a validation handler, a logging handler, an authorization handler, etc etc. and just chain them together.
Essentially
func validator(next http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, req *http.Request) {
            if isRequestValid(req) {
                // a valid request is passed on to next handler
                next.ServeHTTP(w, req)
            } else {
                // otherwise, respond with an error
                http.Error(w, "Bad request - Go away!", 400)
            }
    }
    return http.HandlerFunc(fn)
}

func api1() http.Handler {
    fn := func(w http.ResponseWriter, req *http.Request) {
            // api 1 code
    }
    return http.HandlerFunc(fn)
}

func api2() http.Handler {
    fn := func(w http.ResponseWriter, req *http.Request) {
            // api 2 code
    }
    return http.HandlerFunc(fn)
}

And then chain them up in your main function.
func main() {
    http.Handler("/offers", validate(api1()))
    http.Handler("/getOffersList", validate(api2()))
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}


text:
Q: Scope of Javascript in Datapower (GatewayScript) I'm new to Datapower Gateway script (and Javascript) and following situation totally confuses me. Look:
var inputJson = "default";

//Reading json from input and covert it to string
session.input.readAsJSON( function ( error, json) {
    if ( error ) {
        session.reject( 'Input is not a valid JSON document' );
        return;
    }
    inputJson = JSON.stringify(json);
    console.debug("Inside: ", inputJson);
});

console.debug("Outside ", inputJson);

In Datapower console will be following:
"Inside: { long json string }"
"Outside: default"
It totally breaks my mind and distort my knowleges about variables scopes. Is it feature of javascript, datapower script implementation or what?
UPD. And another brain-cracked thing:
function getFile(options){
    var file="default";
    urlopen.open(options,function(error, response){
        if(error){
            console.error("Unable to find file: "+JSON.stringify(error));
        }else{
            if(response.statusCode==200){
                response.readAsBuffer(function(error, responseData){
                    if(error){
                        console.error("Unable to open file: "+JSON.stringify(error));
                    }else{
                        console.error("Before: ", file);
                        file=responseData.toString('ascii');
                        console.error("After: ", file);
                    }
                });
            }else{
                console.error("Unable to open file: "+response.statusCode);
            }
        }
    });
    return file;
}
console.error("Func result: ", getFile(openSchemaOptions));

Console result:

*

*"Func result: default" (sic!)

*"Before: default"

*"After: --json string--"
How it could be possible to  print function result before the function execution?!

A: Because the session.input.readAsJson(); will take more time to execute. if we number the sequential execution of events in this peace of code:
// 1. functions and vars are moved automatically to the top by the js interpreter in your browser. So this is first
var inputJson = "default";

// 2. a function gets called passing another function as parameter => the callback function of readAsjson
session.input.readAsJSON(
    // 4. the callback function gets executed
    function ( error, json) {
        if ( error ) {
            session.reject( 'Input is not a valid JSON document' );
            return;
        }

        // 5. only executed if no error occured
        inputJson = JSON.stringify(json);
        console.debug("Inside: ", inputJson);
    }
);

// 3. the console output of inputJson, which was put on 'default'
console.debug("Outside ", inputJson);

This is featured by javaScript as there is only function scope. You can't expect the function parameter inside the readAsJSON() to execute prior to the console.debug of "outside".
Compare it with throwing 2 boomerangs but the first one takes more time to return.
Similar behavior can be rewritten:
function doMyJSON(json){
    // do stuff with json
    console.log(json);
}

function getMyJSON(error, json){
    if ( error ) { return; }
    doMyJSON(json);
}

session.input.readAsJSON(getMyJSON);


text:
Q: How to get length of FORMULATEXT() in SUMPRODUCT()? I need to count all cells with a certain length of FORMULATEXT(), I decided to go for SUMPRODUCT() as I believe you can't count by length while using COUNTIF(). The formula that I use while counting cells of certain length is this one:
=SUMPRODUCT(--(LEN(AV3:AV201)<>7))

Adding the FORMULATEXT() function resulted in error.
VBA is unfortunately out of question as our accounting system can't recognise .xlsm files.

A: Try this array formula with CSE,
=SUMPRODUCT(--(IFERROR(LEN(FORMULATEXT(AV3:AV201)), 7)<>7))

If FORMULATEXT sees text, numbers or a blank cell, it returns #N/A. IFERROR can return those as LEN 7 so they are not included in the count.
Without compensating for errors, your formula will only work if AV3:AV201 contains a formula in each cell.