text:
Q: VMware BSOD 0x07 Long story short - was running Win 7 on VMware for a while, then decided to install an antivirus, ran a scan, and it now BSODs on me.
What I've tried - fixed MBR, ran chkdsk, removed the antivirus, reinstalled SCSI controller driver.
Can't boot into safe mode, as it stops on agp440.sys driver. Also I can't get a minidump for Win7, as the control settings / and regedit changes are not saved - I'm running a livecd.
Here's the mem dump from WinDbg, which points to the ntkrpamp.exe fault. Would appreciate if someone could give pointers as to what I can try here.
DUMP:
*******************************************************************************
*                                                                             *
*                        Bugcheck Analysis                                    *
*                                                                             *
*******************************************************************************

INACCESSIBLE_BOOT_DEVICE (7b)

During the initialization of the I/O system, it is possible that the driver
for the boot device failed to initialize the device that the system is
attempting to boot from, or it is possible for the file system that is
supposed to read that device to either fail its initialization or to simply
not recognize the data on the boot device as a file system structure that
it recognizes.  In the former case, the argument (#1) is the address of a
Unicode string data structure that is the ARC name of the device from which
the boot was being attempted.  In the latter case, the argument (#1) is the
address of the device object that could not be mounted.

If this is the initial setup of the system, then this error can occur if
the system was installed on an unsupported disk or SCSI controller.  Note
that some controllers are supported only by drivers which are in the Windows
Driver Library (WDL) which requires the user to do a custom install.  See
the Windows Driver Library for more information.

This error can also be caused by the installation of a new SCSI adapter or
disk controller or repartitioning the disk with the system partition.  If
this is the case, on x86 systems the boot.ini file must be edited or on ARC
systems setup must be run.  See the "Advanced Server System Administrator's
User Guide" for information on changing boot.ini.

If the argument is a pointer to an ARC name string, then the format of the
first two (and in this case only) longwords will be:

    USHORT Length;
    USHORT MaximumLength;
    PWSTR Buffer;

That is, the first longword will contain something like 00800020 where 20
is the actual length of the Unicode string, and the next longword will
contain the address of buffer.  This address will be in system space, so
the high order bit will be set.

If the argument is a pointer to a device object, then the format of the first
word will be:

    USHORT Type;

That is, the first word will contain a 0003, where the Type code will ALWAYS
be 0003.

Note that this makes it immediately obvious whether the argument is a pointer
to an ARC name string or a device object, since a Unicode string can never
have an odd number of bytes, and a device object will always have a Type
code of 3.

Arguments:

Arg1: 8078db58, Pointer to the device object or Unicode string of ARC name
Arg2: c0000034, (reserved)
Arg3: 00000000, (reserved)
Arg4: 00000000

Debugging Details:
------------------

KEY_VALUES_STRING: 1
TIMELINE_ANALYSIS: 1
DUMP_CLASS: 1
DUMP_QUALIFIER: 402
BUILD_VERSION_STRING:  7600.16385.x86fre.win7_rtm.090713-1255
DUMP_TYPE:  0
BUGCHECK_P1: ffffffff8078db58
BUGCHECK_P2: ffffffffc0000034
BUGCHECK_P3: 0
BUGCHECK_P4: 0
CPU_COUNT: 1
CPU_MHZ: f48
CPU_VENDOR:  GenuineIntel
CPU_FAMILY: 6
CPU_MODEL: 9e
CPU_STEPPING: 9
CPU_MICROCODE: 6,9e,9,0 (F,M,S,R)  SIG: 70'00000000 (cache) 0'00000000 (init)
DEFAULT_BUCKET_ID:  WIN7_DRIVER_FAULT
BUGCHECK_STR:  0x7B
PROCESS_NAME:  System
CURRENT_IRQL:  0
ANALYSIS_SESSION_HOST:  DESKTOP-IILFEPS
ANALYSIS_SESSION_TIME:  07-20-2018 14:29:43.0232
ANALYSIS_VERSION: 10.0.17134.12 x86fre
LAST_CONTROL_TRANSFER:  from 8302db92 to 8303eff8
STACK_TEXT:
8078d6f4 8302db92 00001000 00000000 8078d754 hal!READ_PORT_USHORT+0x8
8078d704 8302dcfb 82cf2ec8 04d6b88a 82d40004 hal!HalpCheckPowerButton+0x2e
8078d708 82cf2ec8 04d6b88a 82d40004 00000000 hal!HaliHaltSystem+0x7
8078d754 82cf3d61 00000004 00000000 c0000034 nt!KiBugCheckDebugBreak+0x73
8078db18 82c1c10d 0000007b 8078db58 c0000034 nt!KeBugCheck2+0xa7f
8078db74 82fc1e85 8080a4d8 82fc2ea7 00000000 nt!PnpBootDeviceWait+0x13f
8078dbe4 82fc3757 8080a4d8 8080f7c8 8080a4d8 nt!IopInitializeBootDrivers+0x4ce
8078dc6c 82fc8e6f 0080a4d8 853498b8 853ee020 nt!IoInitSystem+0x5ba
8078dd48 82da147c 8078dd90 82e2466d 8080a4d8 nt!Phase1InitializationDiscard+0xce4
8078dd50 82e2466d 8080a4d8 04d6b24e 00000000 nt!Phase1Initialization+0xd
8078dd90 82cd60d9 82da146f 8080a4d8 00000000 nt!PspSystemThreadStartup+0x9e
00000000 00000000 00000000 00000000 00000000 nt!KiThreadStartup+0x19

THREAD_SHA1_HASH_MOD_FUNC:  c52705e91fd7e0732d9f6441d5450a46f91a9b35
THREAD_SHA1_HASH_MOD_FUNC_OFFSET:  7ca3870a8bc4634d73bd1d9c2cc7332f83f4d934
THREAD_SHA1_HASH_MOD:  a62e82acce9780aeb71ca7a040a198569eeb8e97
FAULT_INSTR_CODE:  24448dcc
SYMBOL_STACK_INDEX:  5
SYMBOL_NAME:  nt!PnpBootDeviceWait+13f
FOLLOWUP_NAME:  MachineOwner
MODULE_NAME: nt
IMAGE_NAME:  ntkrpamp.exe
DEBUG_FLR_IMAGE_TIMESTAMP:  4a5bc007
IMAGE_VERSION:  6.1.7600.16385
STACK_COMMAND:  .thread ; .cxr ; kb
FAILURE_BUCKET_ID:  0x7B_nt!PnpBootDeviceWait+13f
BUCKET_ID:  0x7B_nt!PnpBootDeviceWait+13f
PRIMARY_PROBLEM_CLASS:  0x7B_nt!PnpBootDeviceWait+13f
TARGET_TIME:  2018-07-19T15:33:25.000Z
OSBUILD:  7600
OSSERVICEPACK:  16385
SERVICEPACK_NUMBER: 0
OS_REVISION: 0
SUITE_MASK:  272
PRODUCT_TYPE:  1
OSPLATFORM_TYPE:  x86
OSNAME:  Windows 7
OSEDITION:  Windows 7 WinNt TerminalServer SingleUserTS
OS_LOCALE:
USER_LCID:  0
OSBUILD_TIMESTAMP:  2009-07-14 02:15:19
BUILDDATESTAMP_STR:  090713-1255
BUILDLAB_STR:  win7_rtm
BUILDOSVER_STR:  6.1.7600.16385.x86fre.win7_rtm.090713-1255
ANALYSIS_SESSION_ELAPSED_TIME:  3ab
ANALYSIS_SOURCE:  KM
FAILURE_ID_HASH_STRING:  km:0x7b_nt!pnpbootdevicewait+13f
FAILURE_ID_HASH:  {4e88c8dd-ed64-d78d-36b0-09671c7316ee}
Followup:     MachineOwner


text:
Q: Cachekey generation from object state Background
I am looking to purely store whether or not a query has already been performed.  If it has, the query should be run against a cache of data (internal db, out of process) and if not it should run against the original datasource (3rd party external webservice).  The motivation for this caching is that the number of calls we are allowed to make to this API is limited and we are likely to perform the same query multiple times.
After the query has been run once against the original datasource, it will only ever be run against the cached datasource in subsequent calls.  Note: I'm deliberately ignoring the question of cache expiration for the sake of simplicity in this question.
Given that each query may contain many parameters (currently only 5), and the number of parameters may increase over time I don't want to be querying the cached datasource with something like "WHERE x AND y AND z AND a AND b AND c AND d AND...".
To that end, all I want is to know whether this exact query has been run before and if it has I'll assume the data for it is already available in the cached datastore (albeit in a different format).  I think some form of "cachekey" that identifies any query with the same parameters and associated values would work for me.  Every time I attempt a query I would just generate the cache key based on the state of the query object and check the cachekey store to establish if the query has ever been run before.  The cachekey store needs to faciliate fast lookups.
Question
What I'm finding tricky to work out is what this cachekey should look like and how to generate it.  So far I'm leaning towards

*

*concatenate interesting query parameters and their values into a byte array

*create an MD5 from the byte array

*store this cachekey in a binary(16) indexed column

For the sake of argument I'm willing to accept that there will be some collisions that might result in the cache reporting that cached data is available for the query when it isn't given that the likelyhood is pretty small (although how small I'm not 100% sure).
Does the above solution for creating the cachekey seem reasonable or are there any other approaches that I should consider?

A: Your potential solution is exactly what I've done in the past and it has worked well. I actually concatenated the method/call name, then all the parameter values together into a string, then ran MD5 on it and got my cache key.
I don't see how there could be collisions. If you change a parameter value, the cache key would be different, which would potentially bring back different data.
(All that to say I'm not sure what you mean by "interesting" parameters.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: When and why should I use class in php? I want to know when and why should I use class in php, I read at php.net that a class contains variables (we write var before them) and functions for these variables, so why not use regular functions ? I mean what does class do ?
and thank you.

A: Often suggested advantages to using an Object Oriented Programming (i.e.: OOP aka: class based) approach instead of traditional procedural programming are that OOP aids maintainability and provides a clearer separation of concerns (in the main due to the fact that an object is effectively a set of data and the operations that related to that data), although well constructed procedural code won't necessarily be significantly worse than a OOP approach.
Irrespective, I'd be tempted to take a look at the discussion over on: simple explanation PHP OOP vs Procedural? as I suspect this will answer many of your questions.
That said, it's worth bearing in mind that there's never a "one size fits all" approach, and sometimes a mix of both procedural and OOP is ideal.
Also, if you're a beginner to PHP (or programming in general) sometimes OOP (especially large frameworks like Zend) can initially seem overwhelming, but it's often worth the effort getting to know them. (It'll pay dividends down the line.)
As a final point, I'd personally say that OOP is generally more of a "systems thinking" approach, in that large systems generally break down (reasonably) naturally into objects. From the perspective of someone who's been using OOP for too many years to mention, I'd also say that it's at the very least worthy of some serious investigation. (The Wikipedia entry is as good a place to start as any.)

A: Using a class allows you to encapsulate and re-use code.  Here's an example (PHP 5):
class car {
    public $color;
    public function __construct($color) {
        $this->color = $color;
    }
    public function show_off() {
        return 'This car is ' . $this->color;
    }
}

// And now I can re-use the code elegantly:
$car_one = new car('blue');
$car_two = new car('red');
$car_thr = new car('yellow');

echo $car_one->show_off(); // This car is blue
echo $car_two->show_off(); // This car is red
echo $car_thr->show_off(); // This car is yellow

I must say that, like you—when I was still very green—I felt like OOP was a solution in search of a problem.  But, after diving in and using it, eventually it clicked.
Objects, in their simplest form, are like containers of logic and data that you can pass around.  This can be very advantageous.
And yet, I remember my mindset when I first started learning OOP.  The above example would not click.  The only way to appreciate it is to use it.  Once you do, you'll be very glad you did.

A: Classes are a convenient way to group data and functionality. You could make a class to contain person information. Then, if you want a list of persons, you can make an array and put in it an instance of the class for each person. You fill the variables of the instances with data for the persons. This looks a lot like a two dimensional array (like an array of array of persondata), but it is more. You can build functions that are contained in the class that operate on the variables in the class. You could hide functions and variables from outside, so when you're building a framework you can distinguish between internal and external functionality.
And then, there is not even spoken about inheritance, which gives you even more possibilities.
All of this can be done in procedural code as well, but OOP (for Object Oriented Programming, which is programming using classes) gives you a whole new view on structuring your code.
Many big books have been written about this subject, so it is impossible to describe the exact details and possibilities in this post. All I can tell you is that you should give it a try, keep trying a while during the initial frustrations you'll encounter. And then, when someone else asks you this question, you'll advise them the same thing. :)


text:
Q: Linux Fedora virtualenv site-packages incorrect location I have just tried to set install an application in my new virtual environment.
To create my virtual environment I used:
virtualenv -p /usr/bin/python2.6/python2.6 rollEnv2 --no-site-packages

Then to install the application, I used:
python setup.py install

But I get an error at the end:
File "/home/aaron/workspace/rollEnv2/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg/setuptools/package_index.py", line 475, in fetch_distribution
AttributeError: 'NoneType' object has no attribute 'clone'

Well lets try to serve the application anyway:
paster serve development.ini

Error:
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 588, in resolve
raise VersionConflict(dist,req) # XXX put more info here
pkg_resources.VersionConflict: (WebOb 1.0.8 (/usr/lib/python2.7/site-packages), Requirement.parse('WebOb==0.9.6.1'))
(rollEnv2)

Seems like an obvious error, lets just:
easy_install WebOb==0.9.6.1

But:
WebOb 0.9.6.1 is already the active version in easy-install.pth

So what could be the problem here? It is as if easy install is looking in the base Python directory instead of the virtualenv directory. But ideally it would be nice to fix the original AttributeError: 'NoneType' object has no attribute 'clone'.
I've googled around, but I just cant seem to find a decent answer to this.
Any ideas?

A: First I would advise you to try out mkvirtualenv also, why are you still using easy_install and haven't switched to pip ?
By default virtualenv uses Distribute not setuptools. I think you are using setuptools, so just recreate your environment with setuptools.
From the virtualenv:
--distribute          Ignored.  Distribute is used by default. See
                      --setuptools to use Setuptools instead of Distribute.


text:
Q: How do I make by "put on hold for being too broad" question less broad? This question How to properly namespace bootstrap 3 to work with other bootstrap 3 instances which are not namespaced was closed as too broad.
I can't think on how to make it less broad as i have one precise problem:  Bootstrap developers choose to use really common class names like .row or .table and i use bootstrap in a wordpress plugin and i need a simple and reproducible way to namespace classes to .namespace-row and .namespace-table because otherwise if a them or another plugin style .row and .table.
I could make it less general by saying "i want to do this after compiling bootstrap with Lessphp" but this wouldn't be true, i just need this to be done at any level, i might do it with a regexp
find /path/to/css/directory -type f -name \*.css -exec perl -i -pe 's|([\.#])([a-z][^\s,]+)|$1ai1ec-$2|gi' {} \;

but maybe there are better options.
Any advice?

A: Be more specific about the problem you are having.
In your question, it's clear that you're having a namespacing problem, but not at all clear what the nature of your specific problem is.  Also, we don't know what you mean by "efficient."
Showing us some code that illustrates your problem would help.

A: I see this as being too broad because it is asking for a very broad category of answer, since there are probably multiple ways to do this and a lot could be said about it.  It would seem less broad if you could give a specific situation you're in, and specific code examples that you are looking at.
Having said that I see that this question could easily be seen as "primarily opinion based", since you're just asking for a recommendation on how to proceed.  It would probably be better placed on Programmers, though I would try to tighten the question up to be more focused.


text:
Q: Weird behavior with canvas Context variable definition location causing canvas render freeze when tab is inactive I have come across a very odd behavior that is causing issues in Chrome (only tested browser).  I have a canvas that is being used to render an audio frequency spectrum visual.  Whenever I define the CanvasRenderingContext2D variable
var canvasCtx;
canvasCtx = canvas.getContext("2d");

or define the ScriptProcessorNode variable
var scriptNode;
scriptNode = audioCtx.createScriptProcessor(2048, 1, 1);

and the variable definition is inside any closure or function, the visualization rendering will freeze if you switch tabs, change windows, or even change the window width size.
However, I found out that if the variable definition for those two types are defined at the global scope outside all functions, the canvas will continue to render even if the page is inactive.
Here is a JSFiddle demonstrating the bug:
http://jsfiddle.net/K8J26/541/
(Audio may not play in JSFiddle due to cross-origin safety, so a local file may be needed)
I am wondering, why is this happening?
Does the browser hold onto the state of variables and objects that are tied to the global scope even if the page is inactive? Or is it something completely unrelated to the location of variable definition, and instead something I just completely overlooked?
Thanks!

A: Your problem seems to be that you are calculating the new size and creating the gradient while the browser has not updated the size of your elements yet.
Pass the updateScale in a requestAnimationFrame call so the browser has the time to render the elements :

(function initVisualizer() {
  var AudioContext = window.AudioContext || window.webkitAudioContext;
  if (!AudioContext) {
    return;
  }

  var PERCENT_HIGH_FREQ_TRIM = 0.3;
  var PERCENT_HEIGHT_OF_WITDH = 0.25;
  var SMOTHING_CONSTANT = 0.6;

  var audioCtx = new AudioContext();
  var canvas = document.getElementById("visualizer");
  canvas.style.width = "100%";

  // Defining canvasCtx here causes frozen canvas rendering when tab is inactive
  var canvasCtx = canvas.getContext("2d");
  // Defining scriptNode here causes frozen canvas rendering when tab is inactive
  var scriptNode = audioCtx.createScriptProcessor(2048, 1, 1);
  scriptNode.connect(audioCtx.destination);

  var analyser = audioCtx.createAnalyser();
  analyser.smoothingTimeConstant = SMOTHING_CONSTANT;
  analyser.connect(scriptNode);

  var widthMax;
  var heightMax;
  var dataCount;
  var barWidth;
  var barOffset;
  var gradient;

  scriptNode.onaudioprocess = function() {
    var frequencyData = new Uint8Array(dataCount);
    analyser.getByteFrequencyData(frequencyData);

    canvasCtx.clearRect(0, 0, widthMax, heightMax);

    canvasCtx.fillStyle = gradient;

    var modifier = heightMax / 255;
    for (var i = 0; i < dataCount; i++) {
      var value = ~~(frequencyData[i] * modifier);

      canvasCtx.fillRect(i * (barWidth + barOffset), heightMax - value, barWidth, heightMax);
    }
  };

  window.addEventListener("resize", function() {
    if (canvas.parentElement.offsetWidth !== widthMax) {
      requestAnimationFrame(updateScale);
    }
  });

  function updateScale() {

    widthMax = canvas.offsetWidth;
    heightMax = ~~(widthMax * PERCENT_HEIGHT_OF_WITDH);

    var size = nearestPow2(~~(widthMax / 4));
    dataCount = ~~((size / 2) * (1 - PERCENT_HIGH_FREQ_TRIM));
    var rectWidth = widthMax / dataCount;
    barOffset = rectWidth * 0.25;
    barWidth = rectWidth - barOffset;
    analyser.fftSize = size;

    canvas.setAttribute("width", widthMax);
    canvas.setAttribute("height", heightMax);

    gradient = canvasCtx.createLinearGradient(0, 0, 0, heightMax);
    gradient.addColorStop(1, "#ff6600");
    gradient.addColorStop(0, "#ffff00");
  }

  function playAudio(audio) {
    var sourceNode = audioCtx.createMediaElementSource(audio);
    sourceNode.connect(analyser);
    sourceNode.connect(audioCtx.destination);
    console.log(audio.play());
    setTimeout(function() {
      audio.pause();
    }, 30000);
  }

  function nearestPow2(size) {
    return Math.pow(2, Math.round(Math.log(size) / Math.log(2)));
  }

  updateScale();
  playAudio(document.getElementById('audio'));
})();
body {
  background: #222;
}
<audio id="audio" controls crossorigin="anonymous">
  <source src="https://upload.wikimedia.org/wikipedia/en/d/dc/Strawberry_Fields_Forever_%28Beatles_song_-_sample%29.ogg" />
  <source src="https://upload.wikimedia.org/wikipedia/en/d/dc/Strawberry_Fields_Forever_%28Beatles_song_-_sample%29.ogg" />
</audio>
<canvas id="visualizer"></canvas>

However I don't know why it was working when you set the variable in global context...
Ps : your fiddle wasn't working on FF and only worked on chrome because of a bug, you need to set the crossorigin attribute before the resource are loaded, otherwise it has no effect.


text:
Q: How can i have access to stored files on my different server via php header? Is there any way to download stored file in sub domain(dl1.example.com) via dl.php file that's stored in original domain name(example.com/dl.php?id=12)
In this case that file that need's to be downloadable is located on dl1(sub domain from different server and connected via add DNS record option on cpanel)
dl.php working with php header to make links for clients
Url fetched from db ($path) and used as an input in below function:
downloadFile($path,$file_name, 1024, false);

$path variable is contain something like below variable:
$path="http://dl1.example.com/Lamp%20with%20phpmyadmin.mp4";

I don't have any problem with stored files on my master domain name, my problems occurred when i want to use sub domain to make downloadable links
All of my codes:
/* List of File Types */
function fileTypes($extension){
$fileTypes['swf'] = 'application/x-shockwave-flash';
$fileTypes['pdf'] = 'application/pdf';
$fileTypes['exe'] = 'application/octet-stream';
$fileTypes['zip'] = 'application/zip';
$fileTypes['doc'] = 'application/msword';
$fileTypes['xls'] = 'application/vnd.ms-excel';
$fileTypes['ppt'] = 'application/vnd.ms-powerpoint';
$fileTypes['gif'] = 'image/gif';
$fileTypes['png'] = 'image/png';
$fileTypes['jpeg'] = 'image/jpg';
$fileTypes['jpg'] = 'image/jpg';
$fileTypes['rar'] = 'application/rar';

$fileTypes['ra'] = 'audio/x-pn-realaudio';
$fileTypes['ram'] = 'audio/x-pn-realaudio';
$fileTypes['ogg'] = 'audio/x-pn-realaudio';

$fileTypes['wav'] = 'video/x-msvideo';
$fileTypes['wmv'] = 'video/x-msvideo';
$fileTypes['avi'] = 'video/x-msvideo';
$fileTypes['asf'] = 'video/x-msvideo';
$fileTypes['divx'] = 'video/x-msvideo';

$fileTypes['mp3'] = 'audio/mpeg';
$fileTypes['mp4'] = 'audio/mpeg';
$fileTypes['mpeg'] = 'video/mpeg';
$fileTypes['mpg'] = 'video/mpeg';
$fileTypes['mpe'] = 'video/mpeg';
$fileTypes['mov'] = 'video/quicktime';
$fileTypes['swf'] = 'video/quicktime';
$fileTypes['3gp'] = 'video/quicktime';
$fileTypes['m4a'] = 'video/quicktime';
$fileTypes['aac'] = 'video/quicktime';
$fileTypes['m3u'] = 'video/quicktime';
return $fileTypes[$extention];
};

/*
Parameters: downloadFile(File Location, File Name,
max speed, is streaming
If streaming - videos will show as videos, images as images
instead of download prompt
*/
function downloadFile($fileLocation, $fileName, $maxSpeed = 100,     $doStream = false) {
if (connection_status() != 0)
    return(false);
//    in some old versions this can be pereferable to get extention
//    $extension = strtolower(end(explode('.', $fileName)));
$extension = pathinfo($fileName, PATHINFO_EXTENSION);

$contentType = fileTypes($extension);
header("Cache-Control: public");
header("Content-Transfer-Encoding: binary\n");
header('Content-Type: $contentType');

$contentDisposition = 'attachment';

if ($doStream == true) {
    /* extensions to stream */
    $array_listen = array('mp3', 'm3u', 'm4a', 'mid', 'ogg', 'ra', 'ram', 'wm',
        'wav', 'wma', 'aac', '3gp', 'avi', 'mov', 'mp4', 'mpeg', 'mpg', 'swf', 'wmv', 'divx', 'asf');
    if (in_array($extension, $array_listen)) {
        $contentDisposition = 'inline';
    }
}

if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
    $fileName = preg_replace('/\./', '%2e', $fileName, substr_count($fileName, '.') - 1);
    header("Content-Disposition: $contentDisposition;
        filename=\"$fileName\"");
} else {
    header("Content-Disposition: $contentDisposition;
        filename=\"$fileName\"");
}

header("Accept-Ranges: bytes");
$range = 0;
$size = filesize($fileLocation);

if (isset($_SERVER['HTTP_RANGE'])) {
    list($a, $range) = explode("=", $_SERVER['HTTP_RANGE']);
    str_replace($range, "-", $range);
    $size2 = $size - 1;
    $new_length = $size - $range;
    header("HTTP/1.1 206 Partial Content");
    header("Content-Length: $new_length");
    header("Content-Range: bytes $range$size2/$size");
} else {
    $size2 = $size - 1;
    header("Content-Range: bytes 0-$size2/$size");
    header("Content-Length: " . $size);
}

if ($size == 0) {
    die('Zero byte file! Aborting download');
}
set_magic_quotes_runtime(0);
$fp = fopen("$fileLocation", "rb");

fseek($fp, $range);

while (!feof($fp) and ( connection_status() == 0)) {
    set_time_limit(0);
    print(fread($fp, 1024 * $maxSpeed));
    flush();
    ob_flush();
    sleep(1);
}
fclose($fp);

return((connection_status() == 0) and ! connection_aborted());
}

/* Implementation */
// downloadFile('path_to_file/1.mp3', '1.mp3', 1024, false);

if(isset($_GET['i']) && is_numeric($_GET['i'])){
$file_id=input_security($_GET['i']);
$linkque=mysqli_query($connection,"SELECT * FROM download_links WHERE dl_id='".$file_id."'");
$checkexist=mysqli_num_rows($linkque);
$f_row=mysqli_fetch_array($linkque);
    if($checkexist==0){
        echo 'Invalid file id';
    }else if($checkexist>=1 && $f_row['payment_model']=="free"){
    /* Function: download with resume/speed/stream options */
        $path=$f_row['url'];
        $sep_parts = pathinfo($path);
        $file_name  = $sep_parts['basename'];
        $file_ext   = $sep_parts['extension'];
        if (file_exists($path)) {
        downloadFile($path,$file_name, 1024, false);
        }else{
            echo "File is not exist or url is wrong.";
        }
}else if($checkexist>=1 && $f_row['payment_model']=="nofree"){
    if(isset($_SESSION['username'])){

    $client_id=input_security($_SESSION['username']);
    $client_id_query="SELECT userid FROM users WHERE emailuser='".$client_id."'";
    $session_query=mysqli_query($connection,$client_id_query);
    $clientidrow=mysqli_fetch_assoc($session_query);
    $client_id=$clientidrow['user_id'];
    $link_pid=$f_row['post_id'];
        $userorderque=mysqli_query($connection,"SELECT * FROM user_orders WHERE post_id='".$link_pid."' AND order_client_id='".$client_id."'");
        $checkorderexist=mysqli_num_rows($userorderque);
        $checktobuy_row=mysqli_fetch_array($userorderque);

        if($checkorderexist>=1 && $checktobuy_row['paid']==1){

        $path=$f_row['url'];
        $sep_parts = pathinfo($path);
        $file_name  = $sep_parts['basename'];
        $file_ext   = $sep_parts['extension'];
        if (file_exists($path)){
        //echo "thank you for purchase and support us. You can download now.";
            downloadFile($path,$file_name, 1024, false);
        }else{
            echo "File is not exist or url is wrong.";
        }
        }else if($checkorderexist>=1 && $checktobuy_row['paid']==0){
            echo "You Need to pay for download this file";
        }
    }else{
        echo "This file needs to login";
    }

}else{
    echo "You don't have permission to download this file please purchase this product and trying to download again";
    }
}else{
    header('Location: index.php');
}

How can i have access to stored files on my different server that's connected to my domain name as sub domain (dl1.example.com) from my script that's stored on my domain name (i mean my master web server host (example.com)) ?
I would appreciate any help

A: It is not 100% clear how your communication flow is, but from your description you just deal with a cross domain problem. You might be able to go on by allowing cross domain calls on your servers by adding this header to your servers response for download:
header("Access-Control-Allow-Origin: *");

Good examples using different environments can be found here:
https://enable-cors.org/


text:
Q: select from large data with database or public variable I have table content with 100,000 records
I call function getNameProcess around 200 times
PHP Code with select from database
function getNameProcess($id)
{
    $time1=microtime(true);
    $baseClass = new MsDatabase();

    $query = "select CON_VALUE,CON_ID,CON_CATEGORY from content where CON_ID=$id and CON_VALUE<>'' and CON_CATEGORY='PRO_TITLE'";
    $res= $baseClass->query($query,WF_WORKFLOW_DB_NAME);

    $time2=microtime(true);
    $timeTotal=($time2-$time1);
    echo $timeTotal;
    return $res[0]["CON_VALUE"];
}

PHP Code with select from public variable
$contentTable=array();
function getNameProcess($id)
{
    $time1=microtime(true);
    $baseClass = new MsDatabase();
    if(empty($GLOBALS['contentTable']))
    {
        $query = "select CON_VALUE,CON_ID,CON_CATEGORY from content ";
        $GLOBALS['contentTable']= $baseClass->query($query,WF_WORKFLOW_DB_NAME_MARKAZE);
    }
    foreach($GLOBALS['contentTable'] as $R)
    {
        if($R['CON_ID']==$id && $R['CON_VALUE']!='' && $R['CON_CATEGORY']=='PRO_TITLE' )
        {
            $time2=microtime(true);
            $timeTotal=($time2-$time1);
            echo $timeTotal;

        return $R["CON_VALUE"];
       }
    }
     return 0;
}

When using database for get process name $totalTime is 1.2 second and when use public variable totalTime is 3.5 second?
Why I use public variable $totalTime is greater than when use database?
How to reduce $totalTime?
thanks

A: There are two issues:

*

*The first version only transfers the selected rows from the database to PHP, the second one transfers all the rows. Copying all that data takes time.

*The first version can make use of indexes to speed up finding the selected rows. The second version reads through all the rows.

A: To speed things up:

*

*Create and index for CON_CATEGORY + CON_ID (or CON_ID + CON_CATEGORY depending on other queries)

*Change your lookup code:
New code:
$contentTable=array();
function getNameProcess($id)
{
    $time1=microtime(true);
    if(empty($GLOBALS['contentTable']))
    {
        $baseClass = new MsDatabase();
        $query = "select CON_VALUE,CON_ID from content WHERE CON_CATEGORY = 'PRO_TITLE'";
        $result= $baseClass->query($query,WF_WORKFLOW_DB_NAME_MARKAZE);

        $GLOBALS['contentTable'] = array();
        foreach($result as $R) {
            if ($R['CON_VALUE'] != '') $GLOBALS['contentTable'][$R['CON_ID']] = $R['CON_VALUE'];
        }
    }

    $retval = 0;
    if (isset($GLOBALS['contentTable'][$id])) {
        $retval = $GLOBALS['contentTable'][$id];
    }

    $time2=microtime(true);
    $timeTotal=($time2-$time1);
    echo $timeTotal;

    return $retval;
}

*A third way to optimize is combining the 2 methods. First it is important to have some statistics: How many times is the same id needed? If for example an ID is requested 20 times on average, you would only need 10 queries instead of 200.

Like:
$contentTable=array();
function getNameProcess($id)
{
    $time1=microtime(true);

    if (isset($GLOBALS['contentTable'][$id])) {
        $retval = $GLOBALS['contentTable'][$id];
    }
    else {
        $baseClass = new MsDatabase();
        $query = "select CON_VALUE,CON_ID,CON_CATEGORY from content where CON_ID=$id and CON_CATEGORY='PRO_TITLE'";
        $res= $baseClass->query($query,WF_WORKFLOW_DB_NAME);

        $retval = ($res[0]['CON_VALUE'] == '' ? 0 : $res[0]['CON_VALUE']);
        $GLOBALS['contentTable'][$res[0]['CON_ID']] = $retval;
    }

    $time2=microtime(true);
    $timeTotal=($time2-$time1);
    echo $timeTotal;

    return $retval;
}

A: Also, second version need to iterate (foreach) through all elements. Which takes more time.

A: add CON_CATEGORY column to index of table


text:
Q: "Hosted network couldn't be started" when I try to run "netsh wlan start hostednetwork" When I try to run netsh wlan start hostednetwork, I get the following message:

The hosted network couldn't be started. A device attached to the system is not
  functioning.

What should I do?

A: Try the following three ways to see whether any of them helps:

*

*Device Manager --> Network Adapter. On the menu, click View-->Show hidden devices, and see whether you can find the one (in Network Adapter) for hosted network. If yes, right click it and select "Enable" to enable it.

*If it doesn't work, reinstall the wifi driver. Right click the wireless device in Network adapter and uninstall it. Then scan for hardware changes to re-install it automatically. See whether the hosted network can be started or not.

*Otherwise, right click the wifi device in Network Adapter, and select Properties. In the Power Management tab, tick "Allow the computer to turn off this device to save power".

A: After i tried all the solutions given above and it proved abortive, i further on with my research to solve the problem which was later solved. What was mistaking is that, my wifi switch (on & off switch) was off, well not all system has switch. But turning on my wifi solved the problem


text:
Q: How much data can you put on the stack? I try to create a ~975KB array on the stack and it crashes.
const int size = 500;
cout << (sizeof(float)*size*size)/1024 << endl;
float myArray[size*size]; // crash

This seems like a very small amount of space. Is there any way to know how much space is available (total and currently) before I initialize a variable?

A: The stack is limited in nearly all systems. How big it's allowed to be depends on the OS/Compiler combination. Putting VERY large amounts of data on the stack is a poor idea. Either use C++ standard types (e.g. vector) or use your own dynamic memory allocation. You never know when some other function adds a bit of extra stack, and all of a sudden, you go over the limit - best to not get anywhere near the max size of the stack.

A: In Visual C++ the default stack size is managed by the linker option /STACK (doc). By default it is 1 MB.
Note that each new thread will have its own stack, and you can specify the initial size with parameter dwStackSize in function CreateThread. If it is 0 it will default to the one used in the linker command.
About your other questions, there is no way to query the current/maximum stack size. To avoid problems it is better to use the heap for any significant memory allocation.

A: The default stack size for Visual Studio is 1MB, as Andre said you can use std::vector to avoid this problem or you can dynamically allocate memory. You can adjust the stack size on Visual Studio using  /F. If there is not a compelling reason to allocate the data on the stack it probably makes more sense to use another option.


text:
Q: how to pass java script values to controller using post method in .net core application? I am developing .net core application.i need to pass java script values to my controller using Post method. i am using java script code is below
 data = {'imageValue':'some test'}
    $.ajax({
      type: 'Post',
      url: '/Home/UploadData',
      dataType: 'json',
      contentType: 'application/json',
      data: data,
      success: function (data) {
      alert(data);
      console.log('sample');
      },
      error:  function(){
    }
    });

my controller is
 [HttpPost]public string UploadData([FromBody] string imageValue)
        {return imageValue;} but imageValue always it return null.if any mistake in my code please solve the problem.

A: When you make the ajax call, you should stringify the javascript object and send it. You can use the JSON.stringify method to convert the js object to it's JSON string equivalent.
var data = {'imageValue':'some test'}
$.ajax({
    type: 'Post',
    url: '/Home/UploadData',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(data),
    success: function (data) {

        console.log('sample', data);
    },
    error:  function(){
    }
});

Now since the ajax call is sending the data in the request body (since it is a POST request),You need to decorate the HttpPost action method parameter with [FromBody] attribute so that model binder knows it should read the data from the request body and map to the method parameter(YourViewModel) object.
public IActionResult UploadData([FromBody] YourViewModel d)
{
    return Json(d);
}


text:
Q: 'Field required a bean of type that could not be found.' error spring restful API using mongodb So I've been learning Spring in the couples of week, been following this tutorial
Building a RESTful Web Service
All was well until I tried to integrate it to mongodb. So I follow this tutorial.
Accessing Data with MongoDB
But my practice is partially still using the first one. So my project directory structure is like this.
src/
├── main/
│   └── java/
|       ├── model/
|       |   └── User.java
|       ├── rest/
|       |   ├── Application.java
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── service/
|           └── UserService.java
└── resources/
    └── application.properties

This is my model/User.java file
package main.java.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="user")
public class User {

    private int age;
    private String country;
    @Id
    private String id;
    private String name;

    public User() {
        super();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

This is my rest/UsersController.java file
package main.java.rest;

import java.util.List;
import main.java.service.UserService;
import main.java.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/users")
public class UsersController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public List<User> getAllUsers() {
        return userService.findAll();
    }
}

This is my service/UserService.java file
package main.java.service;

import java.util.List;
import main.java.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserService extends MongoRepository<User, String> {
    public List<User> findAll();
}

I could compile them (I'm using gradle for compilation because I'm following the tutorial), but when I run the jar file it was throwing this error.

APPLICATION FAILED TO START

Description:
Field userService in main.java.rest.UsersController required a bean of
  type 'main.java.service.UserService' that could not be found.
Action:
Consider defining a bean of type 'main.java.service.UserService' in
  your configuration.

Not sure what is wrong I start googling around and found that I need to include Beans.xml file and register the userService in it. I did that but it's not working. I'm really new to this so I really have no clue on what's going on.

A: Normally we can solve this problem in two aspects:

*

*proper annotation should be used for Spring Boot scanning the bean, like @Component;

*the scanning path will include the classes just as all others mentioned above.

By the way, there is a very good explanation for the difference among @Component,  @Repository, @Service, and @Controller.

A: I had the same issue. My mistake was that I used @Service annotation on the Service Interface.
The @Service annotation should be applied to the ServiceImpl class.

A: Add @Repository in you dao class
example:
@Repository
public class DaoClassName implements IIntefaceDao {
}

A: Using all @ Annotations fixed my problem. (Yes, I'm new into Spring)
If you are using a service class add @Service, and same for @Controller and @Repository.
Then this annotations on the App.java fixed the issue (I'm using JPA + Hibernate)
@SpringBootApplication
@EnableAutoConfiguration(exclude = { ErrorMvcAutoConfiguration.class })
@ComponentScan(basePackages = {"es.unileon.inso2"})
@EntityScan("es.unileon.inso2.model")
@EnableJpaRepositories("es.unileon.inso2.repository")

Package tree:
src/
├── main/
│   └── java/
|       ├── es.unileon.inso2/
|       |   └── App.java
|       ├── es.unileon.inso2.model/
|       |   └── User.java
|       ├── es.unileon.inso2.controller/
|       |   ├── IndexController.java
|       |   └── UserController.java
|       ├── es.unileon.inso2.service/
|       |    └── UserService.java
|       └── es.unileon.inso2.repository/
|            └── UserRepository.java
└── resources/
    └── application.properties

A: you have to import  spring-boot-starter-data-jpa
as dependency if you use spring boot

A: For anybody who was brought here by googling the generic bean error message, but who is actually trying to add a feign client to their Spring Boot application via the @FeignClient annotation on your client interface, none of the above solutions will work for you.
To fix the problem, you need to add the @EnableFeignClients annotation to your Application class, like so:
@SpringBootApplication
// ... (other pre-existing annotations) ...
@EnableFeignClients // <------- THE IMPORTANT ONE
public class Application {

In this way, the fix is similar to the @EnableMongoRepositories fix mentioned above. It's a shame that this generic error message requires such a tailored fix for every type of circumstance...

A: I also had the same error:
***************************
APPLICATION FAILED TO START
***************************

Description:

Field repository in com.kalsym.next.gen.campaign.controller.CampaignController required a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' that could not be found.

Action:

Consider defining a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' in your configuration.de here

And my packages were constructed in the same way as mentioned in the accepted answer. I fixed my issue by adding EnableMongoRepositories annotation in the main class like this:
@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = CustomerRepository.class)
public class CampaignAPI {

    public static void main(String[] args) {
        SpringApplication.run(CampaignAPI.class, args);
    }
}

If you need to add multiple don't forget the curly braces:
@EnableMongoRepositories(basePackageClasses
    = {
        MSASMSRepository.class, APartyMappingRepository.class
    })

A: Add the @Component in your controller class. May this work

A: You have to add the @Service annotation to the implementation of your service.

A: I had the same problem I removed the @Autowired Annotation from the controller. If your repository is a class then the Autowired Annotation is needed to use the repository but when it is an interface you do not need to add the @Autowired Annotation from my experience.

A: Solved it. So by default, all packages that falls under @SpringBootApplication declaration will be scanned.
Assuming my main class ExampleApplication that has @SpringBootApplication declaration is declared inside com.example.something, then all components that falls under com.example.something is scanned while com.example.applicant will not be scanned.
So, there are two ways to do it based on this question. Use
@SpringBootApplication(scanBasePackages={
"com.example.something", "com.example.application"})

That way, the application will scan all the specified components, but I think what if the scale were getting bigger ?
So I use the second approach, by restructuring my packages and it worked ! Now my packages structure became like this.
src/
├── main/
│   └── java/
|       ├── com.example/
|       |   └── Application.java
|       ├── com.example.model/
|       |   └── User.java
|       ├── com.example.controller/
|       |   ├── IndexController.java
|       |   └── UsersController.java
|       └── com.example.service/
|           └── UserService.java
└── resources/
    └── application.properties

A: Spent a lot of time because of the auto-import.
Intellij Idea somewhy imported @Service from import org.jvnet.hk2.annotations.Service; instead of import org.springframework.stereotype.Service;!

A: I have same Issue, fixed by Adding
@EnableMongoRepositories("in.topthree.util")
package in.topthree.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import in.topthree.util.Student;

@SpringBootApplication
@EnableMongoRepositories("in.topthree.util")
public class Run implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(Run.class, args);
        System.out.println("Run");
    }

    @Autowired
    private Process pr;

    @Override
    public void run(String... args) throws Exception {
        pr.saveDB(new Student("Testing", "FB"));
        System.exit(0);
    }

}

And my Repository is:
package in.topthree.util;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface StudentMongo extends MongoRepository<Student, Integer> {

    public Student findByUrl(String url);
}

Now Its Working

A: I have come to this post looking for help while using Spring Webflux with Mongo Repository.
My error was similar to owner
Field usersRepository in foobar.UsersService required
a bean of type 'foobar.UsersRepository' that could not be found.

As I was working before with Spring MVC I was surprised by this error.
Because finding help was not so obvious I'm putting answer to this question as it is somehow related and this question is high in search results.
First thing is you must remember about what was mentioned in answer marked as accepted - package hierarchy.
Second important thing is that if you use Webflux you need to use some different package while when using Spring MVC e.g. for MongoDB you need to add
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>

with -reactive at the end.

A: you can add @Service, when defining your service class
ex:
@Service
public class myService {

    public String getData(){
       return "some data";
    }

}

A: You need to add to your main class a @ComponentScan annotation, telling it to scan the package of the services, otherwise it will not initialize these beans

A: I was wondering problem for hours. The reason was this excluding command. I added this before for testing (then forgot). I am sure someone can make the same mistake.
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })

... change to fix:
@SpringBootApplication

A: I encountered the same issue and all I had to do was to place the Application in a package one level higher than the service, dao and domain packages.

A: This thread is old now but I am posting my answer, which may be useful for others.
I had the same issue.
It turned out that there is another class with the same name in other module. I renamed that class and it solved the issue.

A: Add the @Service in the service/UserService.java.

A: In order to spring to create bean and inject it class should be marked with @Componet,@service or @Repository any one of it, in your context it should be
package main.java.service;

import java.util.List;
import main.java.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
@Repository
public interface UserService extends MongoRepository<User, String> {
    public List<User> findAll();
}

A: This may happen when two beans have same names.
Module1Beans.java:
@Configuration
public class Module1Beans {
    @Bean
    public GoogleAPI retrofitService(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.google.com/")
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(GoogleAPI.class);
    }
}

Module2Beans.java:
@Configuration
public class Module2Beans {
    @Bean
    public GithubAPI retrofitService(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.github.com/")
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(GithubAPI.class);
    }
}

A bean named retrofitService is first created, and it's type is GoogleAPI, then covered by a GithubAPI becauce they're both created by a retrofitService() method.
Now when you @Autowired a GoogleAPI you'll get a message like Field googleAPI in com.example.GoogleService required a bean of type 'com.example.rest.GoogleAPI' that could not be found.

A: My Mapper implementation classes in my target folder had been deleted, so my Mapper interfaces had no implementation classes anymore. Thus I got the same error Field *** required a bean of type ***Mapper that could not be found.
I simply had to regenerate my mappers implementations with maven, and refresh the project...

A: Add @Repository in your dao class
    @Repository
    public interface UserDao extends CrudRepository<User, Long> {
         User findByUsername(String username);
         User findByEmail(String email);
      }

A: Spent about 2 hours debugging this error then somewhat figured out I forgot to add Spring Web Mvc Dependency
   <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.9</version>
    </dependency>

A: In my case i have just put the Class MyprojectApplication in a package(com.example.start) with the same level of model, controller,service packages.

A: I know it is old, but wanna add my 5 cents.
I used .service and .service.impl in a folder structure to separate the service with it's implementation. Forget to implement the ServiceImplementation piece.

A: For me this message:
org.apache.wicket.WicketRuntimeException: Can't instantiate page using constructor 'public org.package.MyClass(org.apache.wicket.request.mapper.parameter.PageParameters)' and argument ''. Might be it doesn't exist, may be it is not visible (public).

meant "in my wicket unit test at the top you have to manually add that bean in like"
appContext.putBean(myClass);

A: I followed all steps and instructions followed by OP here, took care of blank space around username and password(even though spring takes care of whitespaces in properties file), still was either facing
could not find bean for ___Repository

(you interface which extends JPARepository)
OR after adding @EnableJPARepository
could not find bean for EntityManagerFactory

i solved it by changing spring boot starter parent version from 2.3.2 to 2.2.1 in pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

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

I did not need to add any of following, spring boot does it itself

*

*@EnableJPAReposity - since i already had all class with same root package

*spring.data.jpa.repositories.enabled  in application.properties

*spring.datasource.driverClassName=com.mysql.jdbc.Driver in application properties

A: Two types of mongo dependencies -
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Two types of repositories -
MongoRepository
ReactiveMongoRepository

Make sure you are using the right combination.

A: The class annotated with @SpringBootApplication should be in your root package (by default all classes in this package and subpackages are scanned) or you need to specify other packages (controller, entity and others) in @ComponentScan.
In order to create bean and inject it class in spring framework, Class should be marked with @Componet, @Service or @Repository in class level accordingly.  Make sure you have used it.

A: Putting this value in application.properties worked for me
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

Note that if your package structure is the same as that in the accepted answer, all you need is @SpringBootApplication annotation on your main class (no additional parameters inside it)
Source :
Spring boot Field required a bean of type that could not be found

A: For me adding dependency 'org.mongodb:mongodb-driver-sync:4.3.2' works perfectly.
Didn't found that answer here.

A: ONLY INTERESTING IF YOU TRY TO AUTOWIRE AN ABSTRACT CLASS!
You are running in to this issue because Spring Boot can't find an abstract class by default.
First, an abstract class isn't component-scanned since it can't be instantiated without a concrete subclass.
Means you have to create a subclass for this abstract class to solve the issue.

A: Faced same issue when initialise the gradle project in kotlin.
Reason: Actually it is not able to scan build.gradle.kts file.
Solution: We can add a @ComponentScan("build.gradle.kts") before the main function declaration so that it can go to the gradle file and scan all the required dependencies.

A: This error will happen when you add this ...
   <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
   </dependency>

instead of this...
   <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
   </dependency>

In your scenario remove the -reactive and the bean creation should work

A: Using this solved my issue.
@SpringBootApplication(scanBasePackages={"com.example.something", "com.example.application"})


text:
Q: Gorm how to find rows by result? I have a table:
               room_id                |    user_id    |  role
--------------------------------------+---------------+--------
 a1d11dcb-b399-4282-9ec2-7dc3df6d1f88 | usrZK8kZTzEHC | member
 a1d11dcb-b399-4282-9ec2-7dc3df6d1f88 | usrItug3Lj2c5 | member
 c2503ab5-1ee4-428a-be1a-d561f6fab068 | usrItug3Lj2c5 | member
 c2503ab5-1ee4-428a-be1a-d561f6fab068 | usrh8hqEpSWLG | member
 9c866cc2-91f1-4658-9843-2c31cff2edfa | usrItug3Lj2c5 | member
 9c866cc2-91f1-4658-9843-2c31cff2edfa | usrh8hqEpSWLG | member
 0e63d78f-3b51-42f7-9ca3-80b93ede6a82 | usrZK8kZTzEHC | member
 0e63d78f-3b51-42f7-9ca3-80b93ede6a82 | usrh8hqEpSWLG | member

I want select all rows out with user_id=usrItug3Lj2c5
meanwhile, also need found out if user_id=usrItug3Lj2c5, if room_id same as that row, will also be searched out.
For example:
in above, I need search out:
               room_id                |    user_id    |  role
--------------------------------------+---------------+--------
 a1d11dcb-b399-4282-9ec2-7dc3df6d1f88 | usrZK8kZTzEHC | member
 a1d11dcb-b399-4282-9ec2-7dc3df6d1f88 | usrItug3Lj2c5 | member
 c2503ab5-1ee4-428a-be1a-d561f6fab068 | usrItug3Lj2c5 | member
 c2503ab5-1ee4-428a-be1a-d561f6fab068 | usrh8hqEpSWLG | member
 9c866cc2-91f1-4658-9843-2c31cff2edfa | usrItug3Lj2c5 | member
 9c866cc2-91f1-4658-9843-2c31cff2edfa | usrh8hqEpSWLG | member

How to write in gorm in this situation?

A: It is easy when you have the raw sql ready. Then you can easily rewrite that in gorm way.
Raw SQL
SELECT t2.* FROM "tablename" AS t2 where t2.room_id IN (SELECT t1.room_id FROM "tablename" AS t1 where t1.user_id = 'usrItug3Lj2c5')

Gorm
var res UserRoom // just assuming the type
subquery := db.Select("t1.room_id").
    Table("tablename as t1").
    Where("t1.user_id = ?", userID)

err := db.Select("t2.*").
      Table("tablename as t2").
      Where("t2.room_id IN (?)", subquery).
      Scan(&res).Error

Hopefully this will work!


text:
Q: Can we have an RSS feed for /tools/new-user-posts? (NB: I had asked this over on meta.stackexchange.com, as this question. However, with the advent of StackExchange 2.0, meta.SE seems to have become redundant, so I'm moving it here.)
Background: I'm a moderator on mathoverflow.net. We're one of the most successful Stack Exchange 1.0 sites, and hope to migrate to 2.0.
The /tools/new-user-posts page (only accessible to moderators) is extremely useful for keeping a close eye on new users, especially during occasional troubles with trolls. Could we have an RSS feed for it?

A: These are the kinds of things you'd have to migrate to SE 2.0 for, to align core engine features.
But yes, I would be interested in implementing a feature like this, in a way that all sites could benefit.


text:
Q: Responding to URL other than Google I use the answer from Android Respond To URL in Intent for responding to URL. However, it just works for Google. When I change the host in manifest, it doesn't work. How to use another URL?

A: IN INTENT FILTER CHANGE THE HOST TO YOUR HOST URL
<intent-filter>
  <action android:name="android.intent.action.VIEW"></action>
  <category android:name="android.intent.category.DEFAULT"></category>
  <category android:name="android.intent.category.BROWSABLE"></category>
  <data android:host="www.youtube.com" android:scheme="http"></data>
</intent-filter>


text:
Q: Change socklen_t int to uint32_t in sys/socket.h I have a conflicting typedef for socklen_t in a library I'm trying to build and an included file from ndk-path/platforms/android-19/arch-arm/usr/include/sys/socket.h.
The library has typedef uint32_t socklen_t but includes sys/socket.h which typedefs it as int. I could make the library use the sys/socket.h version (int) or redefine it in the socket.h header (as below). Which is safer? I tried contacting the author of library but no response. Is changing the definition in socket.h safe?
#ifndef _SYS_SOCKET_H_
#define _SYS_SOCKET_H_

#include <sys/cdefs.h>
#include <sys/types.h>
#include <cstdint>
#include <linux/socket.h>

__BEGIN_DECLS

#define SOCK_STREAM      1
#define SOCK_DGRAM       2
#define SOCK_RAW         3
#define SOCK_RDM         4
#define SOCK_SEQPACKET   5
#define SOCK_PACKET      10

#ifdef __i386__
# define __socketcall extern __attribute__((__cdecl__))
#else
# define __socketcall extern
#endif

/* BIONIC: second argument to shutdown() */
enum {
    SHUT_RD = 0,        /* no more receptions */
#define SHUT_RD         SHUT_RD
    SHUT_WR,            /* no more transmissions */
#define SHUT_WR         SHUT_WR
    SHUT_RDWR           /* no more receptions or transmissions */
#define SHUT_RDWR       SHUT_RDWR
};

typedef uint32_t socklen_t;

__socketcall int socket(int, int, int);
__socketcall int bind(int, const struct sockaddr *, int);
__socketcall int connect(int, const struct sockaddr *, socklen_t);
__socketcall int listen(int, int);
__socketcall int accept(int, struct sockaddr *, socklen_t *);
__socketcall int getsockname(int, struct sockaddr *, socklen_t *);
__socketcall int getpeername(int, struct sockaddr *, socklen_t *);
__socketcall int socketpair(int, int, int, int *);
__socketcall int shutdown(int, int);
__socketcall int setsockopt(int, int, int, const void *, socklen_t);
__socketcall int getsockopt(int, int, int, void *, socklen_t *);
__socketcall int sendmsg(int, const struct msghdr *, unsigned int);
__socketcall int recvmsg(int, struct msghdr *, unsigned int);

extern  ssize_t  send(int, const void *, size_t, unsigned int);
extern  ssize_t  recv(int, void *, size_t, unsigned int);

__socketcall ssize_t sendto(int, const void *, size_t, int, const struct sockaddr *, socklen_t);
__socketcall ssize_t recvfrom(int, void *, size_t, unsigned int, const struct sockaddr *, socklen_t *);

#undef __socketcall

__END_DECLS

#endif /* _SYS_SOCKET_H */

A: Changing system includes is a bad idea, as the rest of the system most certainly relies on what is protoyped/typdefed/declared/definded in there.
So adjust the obviously un-portable library code.


text:
Q: Web server slow on lan using URL, fast using local IP I have a web (HTTP) server set up behind a router in my house. I have set it up to use DuckDNS with a subdomain name. For the purpose of this explanation I'll say that the subdomain is sub1.duckdns.org (that is not the actual domain) and I have forwarded port 80 to the server.
From outside my lan the server provides pages really fast and works great. I had a friend across town test it and he sees pages fine. I also tested on my smart phone. Also fine when typing in sub1.duckdns.org into any outside web browser.
The problem is when I try to access the server using that subdomain from inside my lan for testing. It's very very slow and most of the time the connection is reset before any usable output. If the page does load it is missing the css. However, if I type in the IP address of the machine (192.168.0.x) in my web browser it loads fast again.
Is there some setting in apache that will correct this problem or do I have to keep using the IP address when I am trying to view that computer from inside my lan?

A: I have found this same problem on two different routers and a subnet over a WiFi relay.
The only fix I have found is to map your domains to the private IP address in the hosts file.


text:
Q: How to filter data in Microsoft Excel? I am filtering data using the method described here but it only hides the rows, it doesn't really filter them out. E.g.: if I type in a formula SUM(A1:A1000) I get the same result on the raw worksheet and the filtered worksheet. How can I filter so that the non-matching rows are excluded in the SUM?

A: You can use the SUBTOTAL-function. Depending on if you want to include manually hidden rows or not, you'll use either:
=SUBTOTAL(9,A1:A1000)

or
=SUBTOTAL(109,A1:A1000)

The latter will not include manually hidden rows, the first one will. Both will ignore filtered out rows.


text:
Q: Installing Xdebug for MAMP with pecl At http://xdebug.org/docs/install I read:
Installing with PEAR/PECL is as easy as:

# pecl install xdebug

When I try this, I get errors:
$ pecl install xdebug
bash: pecl: command not found

Trying again, from the folder that contains pecl:
cd /Applications/MAMP/bin/php/php5.5.3/bin/
bash-3.2$ ./pecl install xdebug
No releases available for package "pecl.php.net/xdebug"
install failed

However visiting pecl.php.net/xdebug redirects to http://pecl.php.net/package/xdebug, which indicates that the package clearly exists.
What else can I try?

A: Try running the following command,
pecl channel-update pecl.php.net

A: To get it working what I did was manually compile and install the debug extension with the following commands:
wget http://xdebug.org/files/xdebug-x.x.x.tgz
tar -xzvf xdebug-x.x.x.tgz
cd xdebug-x.x.x
phpize
./configure
make
make install

A: Installing as root may fix it
I got the same error message when trying to install Xdebug via PECL. When I tried to follow user1310789's advice to update the channel, I got the same error message as in this question:
Updating channel "pecl.php.net"
Channel "pecl.php.net" is not responding over http://, failed with message:
Connection to 'pecl.php.net:80' failed: Connection refused
Trying channel "pecl.php.net" over https:// instead
Cannot retrieve channel.xml for channel "pecl.php.net" (Connection to `pecl.php.net:443' failed: Connection refused)

The accepted answer to that question indirectly held the answer. I didn't have to create a proxy, but I noticed the pear command in the answer was run as root.
I tried updating the PEAR and PECL channels using sudo – and voilà, it worked immediately. Installing Xdebug still failed with the same error, but sudoing it again fixed it.
Why PEAR and PECL appear to suddenly require being run as root to function I have no idea. It feels quite iffy, running a remote, online installer with root access. But it was apparently what was needed in my case.

A: This worked for me. Installed on Mac, not MAMP though
brew install php
sudo pecl install xdebug


text:
Q: Limit proof for rational function $\frac{1}{x}$ A while ago I posted another one like this with a incorrect approach, please see this one!
Is this an accurate proof for limits for the function $\frac{1}{x}$
$\displaystyle \lim_{x\to1} \frac{1}{x} = \frac{1}{1} = 1$
Using $\epsilon-\delta$  So,
$\displaystyle \frac{|x-1|}{|x|} < \epsilon$ for some $\displaystyle |x-1| < \delta$
Lets assume $|x - 1| < \frac{1}{3}$
$\displaystyle \frac{2}{3} < |x| < \frac{4}{3}$
$= \frac{3}{2} > \frac{1}{|x|} > \frac{3}{4}$
So we have,
$|x - 1| < \delta$
$\frac{1}{x} < \frac{4}{3}$
Therefore we get: $\frac{|x-1|}{|x|} < \frac{3\delta}{4}$
It is the equation: $\frac{3\delta}{4} = \epsilon$, which is possible only if, $\delta_1 = \frac{4\epsilon}{3}$
Therefore, $\delta = \min(\frac{1}{3},\frac{4\epsilon}{3})$

A: I think you have the right idea, but it is a bit unorganized, separate the scratch work from the proof. This is how I would approach it.
Let $\epsilon>0$ be arbitrary, let $\delta=\min(1/2,\epsilon/2)$ such that $\vert x−1\vert<\delta$,   then $$\left\vert\frac{1}{x}−1\right\vert=  \frac{\vert x−1\vert}{\vert x\vert}< 2\vert x−1\vert <2\epsilon/2=\epsilon.$$


text:
Q: Typo3-9.x Felogin- login problem with multiple domains I have two domains. E.g-:: a.domain.com, b.domain.com . In both domains I have used the fe_login plugin. In backend I have 2 folder Fe-User1 for a.domain.com and other Fe-User2 for b.domain. And both folder have different login users.
So the problem is that a.domain.com users can login in b.domain.com login panel and viceversa. I want different users for both domains. In database table both domain users details are added but with different pid.
So I can differentiate users for a.domain.com and b.domain.com?
Could anyone please tell me how can I do this? How can I write typoscript for this? Thanks in advance!

A: In Flexform "User Storage Page", respectively in TypoScript "plugin.tx_felogin_pi1.storagePid" is the way to define certain sysfolders for allowed fe_users. This way, for both Login plugins you can define separate sysfolders as used storage.

A: The authentication part of the core is executed before any TS configuration is loaded. It does not know about a sys-folder restriction from there.
See \TYPO3\CMS\Sv\AuthenticationService::getUser()
The allowed storage must be present as POST parameter named pid.
(felogin usually generated the login form accordingly.)
The initialization happens in: \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::initFEuser


text:
Q: Memory leak in CardboardActivity While profiling my Google Cardboard application, I found out a very large memory leak (15Mb!) each time I left the activity with the 3D graphics.
After a long and grievous investigation, I found out that the source of the problem was a Context leak that happened each time I closed my CardboardActivity subclass.
The solution can be found in the accepted answer*
* wow... this is awkward... Note for any kind (and experienced) reviewer: I am writing a question to whom I know the answer already: am I supposed to do something for style, like add some fake suspense ("will our heroes prevail?! Find out in the accepted answer!"), like in a old Batman TV series or something?

A: After dicing and slicing my CardboardActivity subclass, until nothing else but the base class remained, I had to conclude that the base class itself was leaking the context.
I searched the web and found this post explaining how the activity in question leaked the context by failing to un-register a listener with a private instance of a class.
Upon trying to invoke said method manually (using reflection), I found out that in the current version of the Cardboard SDK (0.5.4 at the time of writing), the field is not present anymore.
Long story short: all sensors are now handled by an undocumented (yet public) SensorConnection class instantiated in CardboardActivity as a sensorConnection field, which is still plagued by the bug detailed in my first link.
This led me to this solution:

*

*get the sensorConnection field in the CardboardActivity by reflection

*use it to get the magneticSensor field, again by reflection

*invoke the setOnCardboardTheaterListener with null argument, to clear the binding holding the reference to the Context in the Activity onDestroy method.

this boils down to the following code:
private void workAroundLeak() {
    try {
        // Get the sensor Connection
        Class<?> c1 = Class.forName("com.google.vrtoolkit.cardboard.CardboardActivity");
        Field sensorsField = c1.getDeclaredField("sensorConnection");
        sensorsField.setAccessible(true);
        SensorConnection sc = (SensorConnection) sensorsField.get(this);
        if(sc == null) return;

        // Get the magnetSensor
        Class<?> c2 = Class.forName("com.google.vrtoolkit.cardboard.sensors.SensorConnection");
        Field magnetField = c2.getDeclaredField("magnetSensor");
        magnetField.setAccessible(true);
        MagnetSensor ms = (MagnetSensor) magnetField.get(sc);
        if(ms == null) return;

        ms.setOnCardboardTriggerListener(null);
    } catch(Exception e) {}
}

@Override
protected void onDestroy() {
    workAroundLeak();
    super.onDestroy();
}

which solved the problem entirely.
A word to the wise: since this solution relies on reflection, it might break (without consequences other than doing nothing, likely) as soon as Google will update the SDK (possibly fixing the issue in a clean way).
Hope this helps someone


text:
Q: intergal properities (square root) I have this question below ,I don't know if this thing right or not but i've just wonders about it
If we have
$$
A=\int \sqrt(f_x)
$$
Can we do this move
$$
A^2=\int f_x
$$
Thanks

A: No
Counterexample:
$\int xdx = \frac{1}{2}x^2$
$\int x^2dx = \frac{1}{3}x^3$
$(\frac{1}{2}x^2)^2=\frac{1}{4}x^4\neq\frac{1}{3}x^3$

A: No. As an analogy, we can consider A as a simple summation.
$$A = x_1 + x_2 + ... + x_n$$
$$A^2 = (x_1 + x_2 + ... + x_n)^2\neq x_1^2 + x_2^2 + ... + x_n^2$$


text:
Q: How do I structure a bunch of items that chain together in a MySQL database? I apologize for the vagueness of my question title, but I don't even know what to call what I'm trying to accomplish.
The best way to describe what I want is that I want to be able to chain a bunch of items together, and then (possibly) recursively find all the items that are part of any chains that contain the target item. For example, note item3 in the following chains:
item1 => item2 => item3 => item4
item5 => item3 => item6
item3 => item7 => item8
item3 => item9 => item10
item11 => item12 => item13 => item3
If a user were to do a search for item3, then I'd want all five chains above to be displayed. In other words, I want to be able to find all descendants and ancestors of item3, so that I can display the data in an HTML table (or whatever HTML structure works best).
The thing that makes this tricky is that (as shown above) any given item may have many descendants and many ancestors. As such, I'm not sure that regular recursion in MySQL would work.
I did have a look at both of the articles linked to in the top answer for the following SO thread, but I don't think that the suggested solutions will work for my desired data structure:
Mysql recursion?
Is there any way to structure this kind of data into a MySQL DB so that with fairly easy and lightweight queries (i.e., hopefully one query per item request), I can get the information and structure I'm looking for?
Thank you very much.

A: I have a suggestion.
Store item in the following structure.
+---------+-----------+
|   id    |    item   |
+---------+-----------+
|   1     |   item3   |
+---------+-----------+

And add the link references in the following
+---------+-----------+------------+
|  itemid |  ancestor | descendant |
+---------+-----------+------------+
|  1      |  3        | 2          |
+---------+-----------+------------+
|  1      |  5        | 7          |
+---------+-----------+------------+

Create a index on all three columns. This will enable you to add same time as many times as it appears on a chain.
Also you can query a particular item to find all its related links.


text:
Q: NGINX Ingress Controller's Load Balancer is hiding the real client IP Setup
I'm playing around with K8s and I set up a small, single-node, bare metal cluster. For this cluster I pulled the NGINX Ingress Controller config from here, which is coming from the official getting started guide.
Progress
Ok, so pulling this set up a bunch of things, including a LoadBalancer in front. I like that.
For my app (single pod, returns the caller IP) I created a bunch of things to play around with. I now have SSL enabled and another ingress controller, which I pointed to my app's service, which then points to the deployed pod. This all works perfectly, I can browse the page with https. See:

BUT...
My app is not getting the original IP from the client. All client requests end up as coming from 10.42.0.99... here's the controller config from describe:

Debugging
I tried like 50 solutions that were proposed online, none of them worked (ConfigMaps, annotations, proxy mode, etc). And I debugged in-depth, there's no X-Forwarder-For or any similar header in the request that reaches the pod. Previously I tested the same app on apache directly, and also in a docker setup, it works without any issues.
It's also worth mentioning that I looked into the ingress controller's pod and I already saw the same internal IP in there. I don't know how to debug the controller's pod further.
Happy to share more information and config if it helps.
UPDATE 2021-12-15
I think I know what the issue is... I didn't mention how I installed the cluster, assuming it's irrelevant. Now I think it's the most important thing
I set it up using K3S, which has its own LoadBalancer. And through debugging, I see now that all of my requests in NGINX have the IP of the load balancer's pod...
I still don't know how to make this Klipper LB give the source IP address though.
UPDATE 2021-12-17
Opened an issue with the Klipper LB.

A: Make sure your Nginx ingress configmap have enabled user IP real-ip-header: proxy_protocol try updating this line into configmap.
apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    app.kubernetes.io/component: controller
  name: ingress-nginx-controller
  namespace: ingress-nginx
data:
  compute-full-forwarded-for: "true"
  use-forwarded-headers: "false"
  real-ip-header: proxy_protocol

still if that not work you can just inject this config as annotation your ingress configuration and test once.
nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "X-Forwarded-For $http_x_forwarded_for";

A: @milosmns - one of the ways i have been trying is to not install servicelb (--no-deploy=servicelb) and remove traefik (--no-deploy=traefik).
Instead deploy haproxy ingress (https://forums.rancher.com/t/how-to-access-rancher-when-k3s-is-installed-with-no-deploy-servicelb/17941/3) and enable proxy protocol. When you do this, all requests that hit the haproxy ingress will be injected with proxy protocol and no matter how they are routed you will be able to pick them up from anywhere. you can also get haproxy to inject X-Real-IP headers.
the important thing is that haproxy should be running on all master nodes. since there is no servicelb, your haproxy will always get the correct ip address.

A: Just set externalTrafficPolicy to "Local" if using GCP


text:
Q: invalid key after changing domain I run multiple domains on my server. I have phpmyadmin installed and access it via an url in domain A. For a specific user I have two-factor authentication enabled and configured two hardware keys (FIDO-U2F). This works fine.
Now I configured another url to access the same pma instance via domain B. This works for all users which do not have 2fa enabled. When I try to log in with that specific user, it tells the key would be invalid.
Is there a database entry of config setting I can change to solve this problem?


text:
Q: ng-disable doesn't work within SVG element I'm working on an angularjs directive where a circle element needs to be disabled once it has been clicked on once.
The ng-click event works as expected, but the ng-disable is not working. I can see the disabled class being added in the html, but the clicking event is still being triggered.
Any thoughts?
<svg width="100" height="100">
      <circle ng-disabled="disableme" ng-click="clickme()" ng-init="count=0" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
    </svg>

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.clickme = function () {
    $scope.count=$scope.count+1;
    $scope.disableme = true;
  };

http://plnkr.co/edit/dK07QfKoA9qOrNsdlypE?p=preview

A: ng-disabled does not work on svg. Alternatively, you can do this with ng-class
.disable {
     pointer-events: none;
     opacity: 0.5;
 }

Add the ng-class to the svg element
 <svg width="100" height="100"  ng-class="{'disable': disableme}">
      <circle ng-click="clickme()" ng-init="count=0" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
    </svg>

Demo


text:
Q: authlogic - do I still need Rails sessions? I'm a newbie to Rails and am starting a new project that uses AuthLogic. I'm just a little confused about whether AuthLogic provides everything I need to store session state, or whether I still have to include the Rails mechanism (rake db:sessions:create).
Thanks!
Tim

A: Yes you need sessions but you don't necessarily need db:sessions:create for that as it's only needed for the db session store. You can use the default cookie store and all the data will be stored encrypted in the cookie.


text:
Q: How can we count the r-combinations of a multiset? Problem
Define a split of a multiset M to be an ordered pair of multisets of equal size whose union is M.
How can we count the splits of a multiset?
Discussion
This question stems from this one.
This problem is identical to counting the number of r-combinations of a multiset with 2r elements, for which a solution is shown in section 6.2 of Introductory Combinatorics by Richard A. Brualdi, Second Edition, 1992, Prentice-Hall, Inc. To see they are identical, observe there is a 1-1 correspondence between any r-combination X of a multiset M of 2r elements and the split (X, Y), where Y is all the elements of M that are not in X, that is, Y = M−X.
Brualdi's solution using the inclusion-exclusion principle is well known to mathematicians and is suitable for algorithmic implementation.
In spite of the fact that it is well known to mathematicians, it was only partially answered here at Mathematics Stack Exchange and here at Quora.

A: Here is a solution. I have included explanation in the comments.
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

typedef uintmax_t UInt;
#define UIntFormat PRIuMAX

#define NumberOf(a) (sizeof (a) / sizeof *(a))

/*  In this code, a multiset is represented with:

        an integer N0 which is the number of types of elements in the set,

        an integer N1 which is the number of types of elements in the set that
        each appear finitely many times (N0-N1 types each appear infinitely
        many times), and

        an array M[] in which each M[i] is the number of times that an element
        of type i appears.

    Collectively, this is referred to as the multiset M.
*/

/*  Return the number of ways to choose r things from n things.  This is
    n! / (r! * (n-r)!).
*/
static UInt Choose(UInt r, UInt n)
{
    UInt result = 1;
    for (UInt i = 1; i <= r; ++i)
        result = result * n-- / i;
    return result;
}

//  Count the number of r-combinations of a multiset.
static UInt CountRCombinations(UInt r, size_t N0, size_t N1, UInt M[])
{
    /*  If we have only the unlimited types, there is a one-to-one
        correspondence between r objects with N0-1 dividers placed between
        them, each divider marking a transition from one type to another.  For
        example, consider four objects of three types.  Below "o" represents
        any object, and "|" is a divider.  For each arrangement of four o's and
        two |s, we show how it defines a selection of four objects of three
        types:

            oooo|| -> aaaa||
            ooo|o| -> aaa|b|
            ooo||o -> aaa||c
            oo|oo| -> aa|bb|
            oo|o|o -> aa|b|c
            oo||oo -> aa||cc
            o|ooo| -> a|bbb|
            o|oo|o -> a|bb|c
            o|o|oo -> a|b|cc
            o||ooo -> a||ccc
            |oooo| -> |bbbb|
            |ooo|o -> |bbb|c
            |oo|oo -> |bb|cc
            |o|ooo -> |b|ccc
            ||oooo -> ||cccc

        Therefore, the number of combinations equals the number of ways to
        arrange r indistinguishable objects of one type with N0-1
        indistinguishable objects of a different type.
    */
    if (N1 == 0)
        return Choose(r, r+N0-1);

    /*  Otherwise, we count the combinations:

            Select one of the limited types (we use the last one, N1-1, because
            it is easily removed from the array simply by reducing the size of
            the array).

            Count the number of combinations there would be if that type were
            unlimited.

            Count the number of combinations there would be if there were at
            least M[i]+1 instances of elements of that type.

            Subtract to get the number of combinations that have 0 to M[i]
            instances of elements of that type.
    */
    else
    {
        /*  Let M' be the multiset M with the last type changed to unlimited.

            So, where M is represented with N0, N1, M[], M' is represented with
            N0, N1-1, M[].
        */

        //  Change the last limited type to unlimited.
        N1 -= 1;

        //  Count the r-combinations drawn from M'.
        UInt C = CountRCombinations(r, N0, N1, M);

        /*  Now we count the combinations which have at least M[N1]+1 instances
            of the (formerly) last type.

            Consider that each such combination has M[N1]+1 instances of that
            type plus some combination of r - (M[N1]+1) elements drawn from M',
            including zero or more instances of the last type.  (Note that if r
            <= M[N1], there are no such combinations, since we would be asking
            for a negative number of elements.)

            So the number of combinations which have at least M[N1]+1 instances
            of the last type equals the number of combinations of that type
            plus some combination of r - (M[N1]+1) elements drawn from M'.
        */
        if (M[N1] < r)
            C -= CountRCombinations(r - (M[N1] + 1), N0, N1, M);

        return C;
    }
}

//  Count the number of splits of a multiset M that contains N types of things.
static UInt CountSplits(size_t N, UInt M[])
{
    //  Count the number of elements.
    UInt T = 0;
    for (size_t i = 0; i < N; ++i)
        T += M[i];

    //  Return the number of T/2-combinations of M.
    return T % 2 ? 0 : CountRCombinations(T/2, N, N, M);
}

int main(void)
{
    UInt M[] = { 3, 4, 5 };
    size_t N = NumberOf(M);

    printf("The number of splits of {");
    for (size_t i = 0; i < N; ++i) printf(" %" UIntFormat, M[i]);
    printf(" } is %" UIntFormat ".\n", CountSplits(N, M));
}

A: It's certainly the case that the original problem is isomorphic with the problem of counting r-combinations of a multiset of size 2r.
As an alternative to the inclusion-exclusion formula (which is certainly of analytic value, but possibly of less algorithmic value), we can construct a recursive solution which computes the counts of k-combinations of the set for all values of k, using a very similar approach to recursion employed in the recursive algorithm for counting the binomial coefficients C(n,k), the counts of k-combinations of a set of n elements.
Suppose we represent the multiset as a sorted vector V of size n (where n = 2r). (Technically, it doesn't have to be sorted; it is sufficient for it to be "clumped" so that all the identical elements are consecutive. However, the easiest way to do this is to sort the vector.) We want to produce all unique k-combinations of this vector. All such combinations have one of two forms:

*

*"Choose the first element". The combination starts with V1 and continues with a (k−1)-combination of (V2, V3, …, Vn).

*"Skip the first element". The combination is a k-combination of (Vi, Vi+1, … Vn) where i is the smallest index such that Vi ≠ V1. (We need to skip all elements identical to the first element in order to avoid duplication.)
The only difference here with the binomial recursion is the use of the index i in the second option; if the set has no repeated elements, this reduces to i=2, which yields the recursion C(n, k) = C(n − 1, k − 1) + C(n − 1, k).
A naive implementation of this recursion will take exponential time because each computation requires two recursive calls; however, there are only a quadratic number of unique calls so the computation can be reduced to quadratic time by memoisation or dynamic programming. The solution below uses dynamic programming, because that only requires linear space. (Memoisation would require quadratic space since there are a quadratic number of subproblems.)
The dynamic programming solution inverts the recursion by computing the number of k-combinations for the successive suffixes of the vector. It needs to keep the values for only two suffixes: the previous suffix and the previous suffix with a different first element, corresponding to the counts needed by the first and second option of the above recursion. (The actual code uses prefixes instead of suffixes, but it makes absolutely no difference.)
As a minor optimisation, we only compute the counts of k-combinations for values of k between 0 and ⌈n/2⌉. As with binomial coefficients, the counts are symmetrical: the number of k-combinations is equal to the number of (n−k)-combinations because every k-combination corresponds to a unique (n−k)-combination consisting of all the unselected elements. An additional optimisation is possible based on the fact that we only need one count at the end, but the additional complication only obscures the basic algorithm.
The fact that the solution is O(n2) is a little annoying, but since n will generally be a smallish number (otherwise the counts will be astronomical) the computation time seems reasonable. There are undoubtedly further optimisations possible, and it's quite possible that a sub-quadratic algorithm exists.
Here's a basic implementation in C (using an array of strings):
/* Given a *sorted* vector v of size n, compute the number of unique k-combinations
 * of the elements of the vector for values of k between 0 and (n/2)+1.
 * The counts are stored in the vector r, which must be large enough.
 * Counts for larger values of k can be trivially looked up in the returned
 * vector, using the identity r[k] == r[n - k].
 * If v is not sorted, the result will be incorrect. The function does not
 * check for overflow, but the results will be correct modulo (UINTMAX + 1)
 */
void multicomb(const char** v, size_t n, uintmax_t* r) {
  size_t lim = n / 2 + 1;
  // Prev retains the counts for the previous prefix ending with
  // a different element
  uintmax_t prev[lim];
  // If there are no elements, there is 1 0-combination and no other combinations.
  memset(r, 0, sizeof prev);
  r[0] = 1;
  // Iterate over the unique elements of v
  for (size_t k = 0; k < n; ) {
    // Save the counts for this prefix
    memcpy(prev, r, sizeof prev);
    // Iterate over the prefixes with the same ending value
    do {
      for (size_t i = lim - 1; i > 0; --i)
        r[i] = r[i - 1] + prev[i];
    } while (++k < n && strcmp(v[k - 1], v[k]) == 0);
  };
}

In comparison with the solution in OP's self-answer, this version:

*

*overflows later because it only depends on addition. (The  fact that there is no division also makes it much easier to compute the count modulo a prime.)

*takes quadratic time instead of exponential time.

A: I don't think that that's quite right, Eric.  The original question asks, if my source array contains A, A, B, B then how many ways can it be uniquely split between two recipients - the answer in this case will be three because the array could be split as follows:
Child Array 1 | Child Array 2
-----------------------------
A A           | B B
A B           | A B
B B           | A A

This source code (C++ function) works but it's horribly slow and inefficient.  Brute force and ignorance.
int countPermutations(vector<int> itemset) {

  vector<vector<int> > permutations;

  do {
    vector<int> match;

    for(int i = 0; i < itemset.size(); i+=2) {
         match.push_back(itemset.at(i));
    }
    sort(match.begin(), match.end());

    int j = 0;
    bool found = false;
    while (!found && (j < permutations.size())) {
        found = (match == permutations.at(j))?true:false;
        j++;
    }
    if (!found) {
        permutations.push_back(match);
    }

  } while (next_permutation(itemset.begin(), itemset.end()));

  return permutations.size();
}

Any thoughts on optimisation?


text:
Q: How to make http client for GWT-RPC service I want to make client for GWT service, which does not belong to me.  Service uses RPC. I would like to use apache httpclient but there is problem with strong hash name, which are changed sometimes and messages contains a lot of values which are not understandable for human. I know that java scripts generate this message.
By now I watch every request by Firebug and I copy content of request to my client app and I change a few vaules which I need from a lot of values which are included in message. This takes time and sometimes a strong hash names are changed so I have to change my client code.
Is there any better solution? I think that the best solution is to execute javascript and generate right message, but I have no idea how to do that and I am afraid that this add complexity to my app.
I have a very little knowledge about GWT.


text:
Q: Rsync and df/du commands output different sizes for source I'm syncing three drives with a remote nfs share with rsync. Before starting, I analyze all disks with the following commands:
rsync -avn --delete --human-readable --stats dir1/ dest/
rsync -avn --delete --human-readable --stats dir2/ dest/
rsync -avn --delete --human-readable --stats dir3/ dest/
and at the end of the outputs, rsync tells the total size of the files to be transferred.
Problem is, these 3 disk's capacity is a total of 6TB. Rsync tells me it will transfer 5.9TB of data. But when I execute df and du, I see a total of 2.7 TB used space in these 3 disks. So rsync claims it will transfer more space that I can see on the filesystem and I'm all O.K with that, but I'm logging my transfers for future reference and this difference is really annoying.
I've searched for a solution a lot and looked for hard and symlinks only to find none. Can anyone explain this difference.
P.s. The source dirs are vmfs partitions. And the transfer operatiron is a fresh one, so the target share is empty.


text:
Q: How do we access loop variable and bind variable in ASP.Net Repeater? I have a peculiar case in ASP.Net Web Forms. I have a repeater in which I want to loop through a list and generate controls dynamically.
If I use <%#,
<% for (var index = 1; index < MyNamespace.Model.Count; index++)
{ %>

<%# Eval(String.Format("v{0}_vendor_name", index.ToString())) %>:

 <% } %>

I can access Eval but not my loop index variable. I get below build error:

The name 'index' doesn't exist in the current context.

If I use <%=,
 <% for (var index = 1; index < MyNamespace.Model.Count; index++)
{ %>

<%= Eval(String.Format("v{0}_vendor_name", index.ToString())) %>:

 <% } %>

I don't get any build errors, but at run-time, I get below error:

Databinding methods such as Eval(), XPath(), and Bind() can only be
  used in the context of a databound control.

I have looked into a number of questions on this forum but none of them have the requirement of getting both types of variable in a single statement.
If you wonder what I'm trying to achieve, my DataTable bound to this Repeater has some dynamic columns.  I want to add them dynamically depending on the count.  So, my Eval should pick up v1_vendor_name, v2_vendor_name, if there are 2 columns.
I have v1_vendor_name, v2_vendor_name in the DataTable bound to this Repeater; Instead of using Eval("v1_vendor_name") and Eval("v2_vendor_name"), I'm trying to use a loop so the column in Eval is dynamically applied. I have to do this dynamically since I have no control over the number of columns. It could go up to v10_vendor_name.
I have tried using a property from code behind, as suggested by @tweray,
 for (this.index = 1; this.index < MyNamespace.Model.Count; this.index++)
   { %>

<%# Eval(String.Format("v{0}_vendor_name", this.index.ToString())) %>:

 <% } %>

But, this.index in eval always takes 0 even though I assigned 1 in the loop.

A: It apparently is not similar to MVC to loop through in Repeater with Bind variables.
When there is a bind variable in Repeater, it expects that field to be present in the data set bound to that control irrespective of conditions present in HTML.  It doesn't pre-validate conditions.
For this scenario, I changed my data set to multiple rows instead of dynamic columns and handled with a nested repeater.

A: I think you are misunderstanding the use of Eval(), look at this answer to find what is Eval() use for.
That beign said, if your remove Eval from your code, you should be good to go:
<% for (var index = 1; index < 3; index++)
{ %>

<%= String.Format("v{0}_vendor_name", index.ToString()) %>:

<% } %>


text:
Q: FAILED: list-all did not return any version I'm trying to install Java with the asdf plugin.
I could get the plugin but I cannot get the Java list.
The command:
asdf plugin-test java https://github.com/halcyon/asdf-java.git

gives me the message:
FAILED: list-all did not return any version

I'm on Windows 11 in a Tabby 1.0.179 / Git bash terminal.
Previously I could run the commands:
asdf plugin list
asdf plugin list all
asdf plugin add java
cd ~/dev/projects/myproject
asdf list
asdf list java

But the command:
asdf list all java

fails with the message:
Plugin java's list-all callback script failed with output:
/c/Users/stephane.2143929/.asdf/plugins/java/bin/list-all: line 1: functions: command not found

Indeed the ~/.asdf/plugins/java/bin/list-all file contains only one word: functions
As the access to the git repository is done through https and not ssh I have previously specified the GITHUB_API_TOKEN environment variable which is correctly set as seen by an echo $GITHUB_API_TOKEN command.
Regarding the git configuration, I was having the error message:
SSL certificate problem: unable to get local issuer certificate

and the property http.sslbackend had the value openssl
as showed by the command:
git config -l --show-origin

Then I typed in the command:
git config --global http.sslbackend schannel

and verified the changed property again:
git config -l --show-origin

and I could then clone some repository.