text:
Q: last participant support extension websphere Is there any jython script available to set Accept Heuristic Hazard property under Last Participant Support Extension setting of an application installed in WebSphere?

A: Here is a link to an article that describes how to set it for a specific application, which is what you asked about,
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014090728
Alternately, to set it on the transaction service, the following can be used,
wsadmin>transactionService = AdminConfig.list('TransactionService')
wsadmin>AdminConfig.modify(transactionService, [['acceptHeuristicHazard', 'true']])
''
wsadmin>print AdminConfig.show(transactionService)
[LPSHeuristicCompletion ROLLBACK]
[WSTransactionSpecificationLevel WSTX_10]
[acceptHeuristicHazard true]
[asyncResponseTimeout 30]
[clientInactivityTimeout 60]
[context (cells/Node01Cell/nodes/Node01/servers/server1|server.xml#ApplicationServer_1183122130078)]
[enable true]
[enableFileLocking true]
[enableLoggingForHeuristicReporting false]
[enableProtocolSecurity true]
[heuristicRetryLimit 0]
[heuristicRetryWait 0]
[httpProxyPrefix []]
[httpsProxyPrefix []]
[maximumTransactionTimeout 0]
[properties []]
[propogatedOrBMTTranLifetimeTimeout 300]
[totalTranLifetimeTimeout 120]
[waitForCommitOutcome false]
[wstxURLPrefixSpecified false]


text:
Q: Two encoding in one HTML document My problem is this:
I am copying a set of HTMLs from a machine to other one, and I am adding more information into the target HTMLs as a  element. The problem I have is that the source documents are encoded in a lot of different encodings [UTF8, 8859-1, GB1232, etc.] and the meta information is stored as UTF-8, so, when I "dummily" merge my meta info with the original document, my meta info [that contains international characters] looks weird.
So, is there a way of use the HTML encoding defined in the <META> and in the !DOCTYPE tags in all an HTML document except in a TABLE or in a DIV Section that will use another encoding specified there?
thanks in advance,
Ernesto

A: No, there isn't.
I suggest you use DOM parsers to read the various HTML bits into memory, and then construct a combined document in UTF-8. Once these HTML fragments are in memory (after parsing) they'll be in some sort of Unicode representation (depending on the programming language), and so no information should get lost along the way.

A: No, you need to use a character encoding that is a union of the encodings that are used. So in your case I suggest you to use UTF-8 for all of your documents. Or you use character references instead of the plain character itself, if they can not be encoded with the encoding that is used in the document.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP line break between content and date I am trying to have the title and date break to two lines but they are currently running in one line.
PHP novice here needs help!
<?php echo esc_html(get_the_title()); echo nl2br(the_date());?>

A: All you need to do is echo a line break and not use the nl2br() function:

    <?php
        echo esc_html(get_the_title());
        echo '
';
        echo (the_date());
     ?>

A: As long as you're jumping in and out of PHP and HTML, I would separate the dynamic content from the HTML layout.  You can accomplish your goal in this fashion with something like the following:

        <?php echo esc_html(get_the_title()); ?>

        <?php echo (the_date()); ?>

You can then style the HTML elements however you need to in order to achieve the exact layout you're going for.  However the above code will get you the basic effect of putting the output of your two functions on separate lines.

A: You can also:

<?php echo esc_html(get_the_title());?>

<?php echo (the_date());?>

have the brake not in php


text:
Q: ionic 4 importing IonInfiniteScroll throws error at compile time as no exported members I am trying to implement infinite scroll and the import statement like below
import { IonInfiniteScroll } from '@ionic/angular';

shows me a error in the editor that ../@ionic/angular/dist/index has no exported members.
my package.json has
    "@ionic/angular": "4.0.0-beta.16",

A: i realized that this a 11 months old version. updated to 4.11.x and did a clean build and it worked fine


text:
Q: clang-format 3.8 breaks before and after comment blocks Is there a way to control the break before and after comment blocks?
I'd like to have my comment blocks to be connected with the following function. I'd also like to have one line break before a comment block.
For example this code:
/**
 * \breif some comments
 */

void f1()
{
}

/**
 * \breif some comments
 */

void f1()
{
}

class A {

/**
 * \breif some comments
 */

void f1()
{
}

/**
 * \breif some comments
 */
void f1()
{
}
};

template<typename T>
class A {

/**
 * \breif some comments
 */

void f1()
{
}

/**
 * \breif some comments
 */
void f1()
{
}

};

To be formatted like this:
/**
 * \breif some comments
 */
void f1()
{
}

/**
 * \breif some comments
 */
void f1()
{
}

class A
{
  /**
   * \breif some comments
   */
  void f1() {}

  /**
   * \breif some comments
   */
  void f1() {}
};

template < typename T >
class A
{
  /**
   * \breif some comments
   */
  void f1() {}

  /**
   * \breif some comments
   */
  void f1() {}
};

But what I'm getting is this:
/**
 * \breif some comments
 */

void f1()
{
}

/**
 * \breif some comments
 */

void f1()
{
}

class A
{
  /**
   * \breif some comments
   */

  void f1() {}
  /**
   * \breif some comments
   */
  void f1() {}
};

template < typename T >
class A
{
  /**
   * \breif some comments
   */

  void f1() {}
  /**
   * \breif some comments
   */
  void f1() {}
};

Here is my .clang-format:
---
Language:        Cpp
BasedOnStyle:  Google
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false

AlignEscapedNewlinesLeft: true
AlignOperands:   true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true

AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false

AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true

BinPackArguments: true
BinPackParameters: true

BraceWrapping:
  AfterClass:      false
  AfterControlStatement: false
  AfterEnum:       false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     false
  AfterUnion:      false
  BeforeCatch:     false
  BeforeElse:      false
  IndentBraces:    false

BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
ColumnLimit:     100
CommentPragmas:  '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 0
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat:   false
ExperimentalAutoDetectBinPacking: false
ForEachMacros:   [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories:
  - Regex:           '^<.*\.h>'
    Priority:        1
  - Regex:           '^<.*'
    Priority:        2
  - Regex:           '.*'
    Priority:        3
IndentCaseLabels: false
IndentWidth:     2
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd:   ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments:  true
SortIncludes:    true
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: Never
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles:  true
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: true
SpacesInParentheses: true
SpacesInSquareBrackets: true
Standard:        Auto
TabWidth:        2
UseTab:          Never
...

A: I've found that this problem can be solved by setting:
KeepEmptyLinesAtTheStartOfBlocks: true


text:
Q: Tika - Out Of memory Exception I have been working on Tika to extract text contents only from various files. I found a peculiar issue when I was parsing a doc file with images inside. The Image fetcher was called and it threw java.lang.OutOfMemoryError: Java heap space.
I was trying the same in tika-app 1.22 gui and was getting the following exceptions:
Exception in thread "Image Fetcher 2" java.lang.OutOfMemoryError: Java heap space
    at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:75)
    at java.awt.image.Raster.createPackedRaster(Raster.java:467)
    at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1032)
    at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:253)
    at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:559)
    at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:138)
    at sun.awt.image.PNGImageDecoder.sendPixels(PNGImageDecoder.java:549)
    at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:470)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)
Exception in thread "Image Fetcher 0" java.lang.OutOfMemoryError: Java heap space
    at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:75)
    at java.awt.image.Raster.createPackedRaster(Raster.java:467)
    at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1032)
    at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:253)
    at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:559)
    at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:138)
    at sun.awt.image.PNGImageDecoder.sendPixels(PNGImageDecoder.java:549)
    at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:470)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
    at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:75)
    at java.awt.image.Raster.createPackedRaster(Raster.java:467)
    at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1032)
    at sun.awt.image.ImageRepresentation.createBufferedImage(ImageRepresentation.java:253)
    at sun.awt.image.ImageRepresentation.setPixels(ImageRepresentation.java:559)
    at sun.awt.image.ImageDecoder.setPixels(ImageDecoder.java:138)
    at sun.awt.image.PNGImageDecoder.sendPixels(PNGImageDecoder.java:549)
    at sun.awt.image.PNGImageDecoder.produceImage(PNGImageDecoder.java:470)
    at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:269)
    at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
    at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)

My questions are:

*

*Why would I need to fetch the image for text only extraction from
documents?

*How do I configure Tika to skip fetching images
like in this case. I don't wish to increase my heap memory to solve
this instead gracefully skip the images.

Edit: I am reading a file as stream and wrapped it as tikaInputStream and then opened an outputStream to write the result in another file.
        outputWriter = new OutputStreamWriter(outputStream);
        WriteOutContentHandler writeOutContentHandler = new WriteOutContentHandler(outputWriter, writeLimit);

        AutoDetectParser parser = new AutoDetectParser();
        Metadata metadata = new Metadata();

        parser.parse(inputStream, writeOutContentHandler, metadata);

I have attached the file which I used for testing and got the following exception:
org.apache.tika.exception.TikaException: Unexpected RuntimeException from org.apache.tika.parser.microsoft.OfficeParser@4f209819
    at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:282)
    at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:280)
    at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:143)
    at tika.Tikaimpl.main(Tikaimpl.java:49)
Caused by: java.lang.IndexOutOfBoundsException: Block 96991 not found
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.getBlockAt(POIFSFileSystem.java:434)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.readBAT(POIFSFileSystem.java:406)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.readCoreContents(POIFSFileSystem.java:359)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:239)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:172)
    at org.apache.tika.parser.microsoft.OfficeParser.parse(OfficeParser.java:121)
    at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:280)
    ... 3 more
Caused by: java.lang.IndexOutOfBoundsException: Position 49659904 past the end of the file
    at org.apache.poi.poifs.nio.FileBackedDataSource.read(FileBackedDataSource.java:88)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.getBlockAt(POIFSFileSystem.java:432)
    ... 9 more

File used for testing.

A: Increase the size of -XX:MaxPermSize upto 1GB


text:
Q: Efficient algorithm to found duplicated values I'm practice some algorithms lessons at Codility, and i'm now at that lesson
To resolve that, I created the algorithm as follow:
A = [9,3,9,3,9,7,9]
for index, item in enumerate(A):
    counter = A.count(item)
    if(counter == 1):
        output = item
        print(output)

The algorithm works as well, but he is not performatic... I get just 25% of efficient and I will appreciate opinions about how can I make that code better?
I guess that he count each index can make it not-performatic... any suggestion to improve that?
Thank you!


text:
Q: Either remove ListView divider colour so transparent or set background without redrawing pixels. - Android I have a quite easy question here. Can you remove the ListView divider colour as so it is just left transparent as the default app background has a slight gradient to it and looks strange if you set the divider to a certain colour of the background as it matches some places and doesn't in others.
My other question if this is not possible is that is it possible to set a custom background for the app without making the app redraw the pixels adding extra GPU Overdraw. If you do it the normal way which is making the app set a background using android:background="#e6e6e6" then the pixel has another layer added onto it leading to less performance. That is why I would to set the master colour for the style preferably although I am somewhat sure this isn't possible.

A: Just set the divider color to transparent:
android:divider="@android:color/transparent"
android:dividerHeight="0dp"


text:
Q: Open CV SurfFeatureDetection in iOS I was referring to OpenCV on iOS: False matching with SurfFeatureDetector and FlannBasedMatcher
Tried to implement my own function, with minor changes:-
+ (void)checkImageWorks: (UIImage *)inputImage mainImageView:    (UIImageView *)mainImageView{
  UIImage *sceneImage, *objectImage1;
  cv::Mat sceneImageMat, objectImageMat1;
  cv::vector<cv::KeyPoint> sceneKeypoints, objectKeypoints1;
  cv::Mat sceneDescriptors, objectDescriptors1;
  cv::SurfFeatureDetector *surfDetector;
  cv::SurfDescriptorExtractor surfExtractor;
  cv::FlannBasedMatcher flannMatcher;
  cv::vector<cv::DMatch> matches;
  int minHessian;
  double minDistMultiplier;

  minHessian = 400;
  minDistMultiplier= 3;
  surfDetector = new cv::SurfFeatureDetector(minHessian);

  sceneImage = inputImage;

  objectImage1 = [UIImage imageNamed:@"small.png"];

  sceneImageMat = cv::Mat(sceneImage.size.height, sceneImage.size.width, CV_8UC1);
  objectImageMat1 = cv::Mat(objectImage1.size.height, objectImage1.size.width, CV_8UC1);

  cv::cvtColor([sceneImage CVMat], sceneImageMat, CV_RGB2GRAY);
  cv::cvtColor([objectImage1 CVMat], objectImageMat1, CV_RGB2GRAY);

  if (!sceneImageMat.data || !objectImageMat1.data) {
    NSLog(@"NO DATA");
  }

  surfDetector->detect(sceneImageMat, sceneKeypoints);
  surfDetector->detect(objectImageMat1, objectKeypoints1);

  surfExtractor.compute(sceneImageMat, sceneKeypoints, sceneDescriptors);
  surfExtractor.compute(objectImageMat1, objectKeypoints1, objectDescriptors1);

  flannMatcher.match(objectDescriptors1, sceneDescriptors, matches);

  double max_dist = 0; double min_dist = 100;

  for( int i = 0; i < objectDescriptors1.rows; i++ )
  {
    double dist = matches[i].distance;
    if( dist < min_dist ) min_dist = dist;
    if( dist > max_dist ) max_dist = dist;
  }

  cv::vector<cv::DMatch> goodMatches;
  for( int i = 0; i < objectDescriptors1.rows; i++ )
  {
    if( matches[i].distance < minDistMultiplier*min_dist )
    {
      goodMatches.push_back( matches[i]);
    }
  }
  NSLog(@"Good matches found: %lu", goodMatches.size());

  cv::Mat imageMatches;
  cv::drawMatches(objectImageMat1, objectKeypoints1, sceneImageMat, sceneKeypoints, goodMatches, imageMatches, cv::Scalar::all(-1), cv::Scalar::all(-1),
                  cv::vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);

  std::vector<cv::Point2f> obj;
  std::vector<cv::Point2f> scn;

  for( int i = 0; i < goodMatches.size(); i++ )
  {
    //-- Get the keypoints from the good matches
    obj.push_back( objectKeypoints1[ goodMatches[i].queryIdx ].pt );
    scn.push_back( sceneKeypoints[ goodMatches[i].trainIdx ].pt );
  }

  cv::vector<uchar> outputMask;
  cv::Mat homography = cv::findHomography(obj, scn, CV_RANSAC, 3, outputMask);
  int inlierCounter = 0;
  for (int i = 0; i < outputMask.size(); i++) {
    if (outputMask[i] == 1) {
      inlierCounter++;
    }
  }
  NSLog(@"Inliers percentage: %d", (int)(((float)inlierCounter / (float)outputMask.size()) * 100));

  cv::vector<cv::Point2f> objCorners(4);
  objCorners[0] = cv::Point(0,0);
  objCorners[1] = cv::Point( objectImageMat1.cols, 0 );
  objCorners[2] = cv::Point( objectImageMat1.cols, objectImageMat1.rows );
  objCorners[3] = cv::Point( 0, objectImageMat1.rows );

  cv::vector<cv::Point2f> scnCorners(4);

  cv::perspectiveTransform(objCorners, scnCorners, homography);

  cv::line( imageMatches, scnCorners[0] + cv::Point2f( objectImageMat1.cols, 0), scnCorners[1] + cv::Point2f( objectImageMat1.cols, 0), cv::Scalar(0, 255, 0), 4);
  cv::line( imageMatches, scnCorners[1] + cv::Point2f( objectImageMat1.cols, 0), scnCorners[2] + cv::Point2f( objectImageMat1.cols, 0), cv::Scalar( 0, 255, 0), 4);
  cv::line( imageMatches, scnCorners[2] + cv::Point2f( objectImageMat1.cols, 0), scnCorners[3] + cv::Point2f( objectImageMat1.cols, 0), cv::Scalar( 0, 255, 0), 4);
  cv::line( imageMatches, scnCorners[3] + cv::Point2f( objectImageMat1.cols, 0), scnCorners[0] + cv::Point2f( objectImageMat1.cols, 0), cv::Scalar( 0, 255, 0), 4);

  [mainImageView setImage:[UIImage imageWithCVMat:imageMatches]];
}

but it throws me an error:-
libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /Users/alexandershishkov/dev/opencv2.4.9/opencv/modules/calib3d/src/fundam.cpp:1074: error: (-215) npoints >= 0 && points2.checkVector(2) == npoints && points1.type() == points2.type() in function findHomography

Please help me out!


text:
Q: Is it suggested not to import parent's or siblings' class header file in cocos2d? For example, there're three classes, Aclass, Bclass, and Cclass.
Aclass initializes some instances of Bclass and Cclass as different children. Normally I'll import Bclass.h and Cclass.h in Aclass.h or Alcass.m. So far Bclass and Cclass don't know each other yet. However there're cases for example Bclass needs to know Cclass's properties and methods. One way to do this is to import Cclass.h in Bclass.h or Bclass.m; later on Cclass needs to know about Bclass, then I'll import Bclass.h in Cclass.h or Cclass.m. Sometimes if there's "import cycle" that can't pass the compiling, then I may change one of the import from xx.h into @class Xclass.
Though this works, however I feel it's not the right or delegate way to do. I used to use delegate only to avoid importing parent's class. So what's the best way to design if one class needs to know about it's siblings?

A: if you are getting import cycles, what you should do is just import the headers into the .m files, then if you really need that object in the .h, use @class ClassName; at the top of your header to promise to the compiler that the type of object exists.
edit:
my bad, tl;dr'ed the last sentance, that is the correct way to approach it


text:
Q: Flash AS3: How to gradually limit rotation of an object influenced by y position of mouse I have created a flash app in which there is a circle with circles plotted along it's circumference, it is rotated when the mouse is moved up or down. The rotation is drawn directly from the y position of the mouse pointer. What I would like to do is grade the movement some how so that the further down the mouse pointer goes the less impact on rotation the movement has.
My current code is like this:
myCircle.rotationZ = e.localY;

Is there some form of math formula I could use which would reduce the amount of rotation the greater the y position of the mouse position?
Thanks,
eb_dev

A: Well, it depends on how fast you want to decay the rotation angle. You can use simply use linear decay.rot = ((Rmax - Rmin) / (Ymax - Ymin)) * y + ((Rmin * Ymax) - (Rmax * Ymin)) / (Ymax - Ymin) Above expression will change the rotation angle 'rot' linearly from Rmax to Rmin depending on 'y' value from Ymax to Ymin. The same thing you can do using exponential decay.Maths behind it:rot = a * y + b //(where a,b are constants)
first boundary condition
Rmax = a * Ymax + b
second boundary condition
Rmin = a * Ymin + b
Solve above 2 equations to find out a and b.
a = (Rmax - Rmin) / (Ymax - Ymin)
b = ((Rmin * Ymax) - (Rmax * Ymin)) / (Ymax - Ymin)

A: There are any number of ways to do what you want.  Basically it sounds like you're trying to take the linear Y coordinate and turn it into a curve.
Something like this might do what you want (I'm a bit rusty at AS3 so it will need some tweaking but it should give you the idea - YMMV):
var distance:Number = (Stage.Height - e.localY) / Stage.Height;
distance = distance * distance;
myCircle.rotationZ = distance * 2 * 3.1415927;

It's converting the distance into a number from 0 to 1 where 0 is at the bottom and 1 is at the top.
Distance is then adjusted from a linear to parabolic curve.
Finally we convert the value from the range 0 - 1 to 0 to 2PI (the rotation angle).

A: bhups is right. Here is the Exponential version
Please don't be scared by the name,read the comments and visit wikipedia for a visual representation :)
var scale:int=360;
var val:Number;
//From the exponential graph I chose the interval [-5,0]
//Consult http://en.wikipedia.org/wiki/Exponential_function , the image on the top-right
//corner for visual
/*For a value of 0 Math.exp returns 1;While going down to -5 it returns
values closer and closer to 0
*/
var intervalMaxValue:Number=0;
/* Warning! if you change the  intervalMaxValue to something different than 0 you have to revise the formula
*/
var intervalLength:Number=5;
stage.addEventListener(Event.ENTER_FRAME,handlerEnterFrame);
function handlerEnterFrame(e:Event):void{
/*
 intervalMaxValue-intervalLength -> we start at -5
1-(stage.mouseY/stage.stageHeight)) * intervalLength -> and gradually add a number between 5 and 0 as the mouse goes down
Math.exp -> transforms it into something between 0 and 1 for this interval that ends with 0
scale -> Multiply it by scale to get the full 0-360 interval*/
val=Math.exp(intervalMaxValue-intervalLength+((1-(stage.mouseY/stage.stageHeight)) * intervalLength))*scale;
myCircle.rotation=val;
}

A:
(source: mathnstuff.com)
The above graph is from -4 to 4 on the x axis , it's easy to figure out the y value for x=-5 - it's almost 0 - so please consider this when reading the following.
Please see the above graph, it's the graph of the exponential function. See how it grows for x values from -5 to 0? It's not a linear growth but rather it's a bigger and bigger growth while it reaches 0. This is exactly what you need for your animation.
val=Math.exp(intervalMaxValue-intervalLength+((1-(stage.mouseY/stage.stageHeight)) * intervalLength))*scale;

intervalMaxValue-intervalLength is actually 0-5 which would be -5
So we start with -5!
Next
stage.mouseY/stage.stageHeight = 0 when your mouse is at the top of the stage(as stage.MouseY would be 0) and 1 when the mouse is at the Bottom of the stage ( stage.mouseY is then equal to stage.stageHeight so you divide stage.stageHeight by stage.stageHeight which will be 1)
For your effect you want it to be inverted, 1 when you are at the top and 0 when you are at the bottom so  that's why you have to use (1-(stage.mouseY/stage.stageHeight))
Now when the mouse is at the top the above formula returns 1 and when it's at the bottom returns 0 ( exactly like you want it to behave , a big spin when it's at the top and a small one when it reaches the bottom )
Let's now take only the Math.exp part and see how it behaves
val=Math.exp(intervalMaxValue-intervalLength+((1-(stage.mouseY/stage.stageHeight)) * intervalLength);

When your mouse is at the TOP the above formula would be -5+((1-(0))*5(<-- 5 is here the intervalLength);  this would return 0. Take a look at the graph now, for 0 on the x axis you get 1 on the y axis.
Now let's see what happens when the mouse is at the BOTTOM -5+(1-(1))*5; this would return -5. For -5 on the x axis you get something very close to 0 on the y axis as you can see in the image above.
Let's see what happens when the mouse is at the MIDDLE -5+(1-(0.5))*5; this would return -5+2.5 which would be -2.5.For -2.5 on the x axis you have something more closer to 0 on the y axis rather than on 1.This is what the exponential function does.
As you can see, on this interval [-5,0] the exponential function generates a y value from 0 to 1 and this value's growth is bigger as it approaches the x value of 0.
Considering that it generates a value from 0 to 1, that drops a lot while going to -5, you now multiply this value with 360 so you will get an angle value out of it.
At the TOP, the angle value is   1*360;
MIDDLE: the Math.exp for -2.5 returns a value somewhere near 0.1, multiply this by 360 and you get 36.If you compare it to the 360 for the TOP of the stage you observer that it sharply fell while the mouse reached the middle.
BOTTOM: Math.exp for -5 returns a value very close to 0. Multiply 0 with 360 and you get no angular movement. So when mouse is at the bottom of the stage the rotation value is extremely close to 0.
Hope this is clear, it was written at 6:53 AM, after a night out
Cheers.


text:
Q: Running a C++ compiled program in the background and sending input whenever needed I have a compiled program written in C++ for a UNIX environment which has this kind of structure:
int main(){
...
LoadEngine()
...
while(1){
    std::cin >> buffer;
    ...
    ExecuteFunction(buffer);
}
}

Loading the engine takes quite a while, so I'm trying to start the program in the background first, then send the input whenever I need to.
Running the program with the standard ampersand appended at the end seemingly does not make the program run in the background, but rather halts at std::cin until an input is received from the console, and stops after an input is accepted from the console.
How do I execute the program such that the program runs continuously in the background and receive input and execute the function whenever it is needed?
EDIT: The final product is a small device (RaspberryPi) which recognizes speech, and does something based on the words recognized. The program that I have is the part where the device does something based on the word input, and the word input corresponds to the variable buffer from the code snippet above.
So the std::cin part is a dummy line code that I'm using for testing out that my part of the code starts up in the background process (to load the engine) and does whatever it is designed to do.
EDIT 2 : To clarify what I'm trying to achieve, the program takes an input from a speech recognizer and does things (e.g. synthesize speech from input, send out signals to LEDs, etc.). The text input can be taken directly from the console (which my code is currently doing), or some other method that I'm not knowledgeable in. The only thing that the input adheres to is that it must be a text, and is sent from another program that recognizes speech (which is handled by some other developer). So the exact method isn't specified. All I have to worry about is my side of the program, which executes a function from a text input (i.e. buffer from the code snippet).
So the general structure would look something like this:
Int main(){
LoadEngine()
while(1){
    buffer = ReceiveInput();
    ExecuteFunction(buffer);
 }}

Where the ReceiveInput() part is currently implemented as std::cin. It really can be any method, as long as the engine is loaded once in the beginning, and the program is able to perform ExecuteFunction from an input until the device is turned off.

A: Unlikely that is possible. In such cases typically you need to listen network port, accept() connection and read from it data, and do whatevet you need. Then you need some client app also to send data. This is how background apps typically work.

A: You would need to send your application some wake-up call, so it knows when to listen to the input, and where to expect it(since running it in background separates it from the terminal process). The better solution would be(imho) creating separate program that would serve as an interface to the engine - as engine looks like your problem. Provide set of functions to communicate with it, and write simple script that when run, will send input to the engine. Engine will run in background, and other programs will just connect to it. That's the best thing I can come up with at the moment.

A: This is awkward and inconvenient, but possibly less so than the other answers:
Every time your program asks for input:

*

*Get to a shell prompt — and I mean the shell that launched your program.
(I.e., the fact that you're not just running your "engine" program
in the foreground suggests that you're using the terminal for something else,
like maybe editing files.  Every time your program asks for input,
you'll need to save and quit out of the editor,
and get back to your primary shell.  Or you may be able to suspend the editor;
but that makes the next step more complicated.)

*Type fg (followed by Enter, of course)
to bring your background job into the foreground.
If you have multiple background jobs (as suggested above),
do what you need to do to bring your "engine" program into the foreground.

*Interact with the program.

*When it's ready to resume running (computing, etc.) for a while, press Ctrl+Z, and then bg
(followed by Enter).

Repeat the above as long as the program runs.


text:
Q: Upload Image to Facebook Objective-C I'm currently trying to upload an image from my Mac application to Facebook. To do this, I'd like for the user to simply input his username and password, and to click a button.
The only issue is, Facebook doesn't actually have an API for the Mac, it only has one for iOS. This shouldn't be a problem, except for the fact that to login, you must use a web view, something I'm not to keen on doing, since I'd like the interface to be two simple text fields.
I've also looked into PHFacebook, a class I found online, but it also seems to utilize an NSWebView.
I'm wondering if there's a security issue when you use text fields; indeed, it's slightly strange no available API offers this function !
So, to conclude, is it possible, or is there an API, that lets you upload an image and lets you provide the user's credentials through simple NSStrings?

A: There's a Cocoa framework called MKAbeFook that lets you access Facebook APIs. I don't know if it's up to date, but you should give it a try.

A: You could do this through JSON on your mac app but I think the way Facebook protocols work you simply provide the image to upload and then the user logs into their Facebook account through a webview and has to authorize it.

A: It looks like this is not supported unless you can embed a web browser.
If you scroll to the bottom of: facebook authentication docs, it seems to say this.
Embedding a web browser is generally doable, but may be overkill for what you are trying to do.
Good luck!


text:
Q: Optimizing Mysql role management query in web-application? Let me start off by the structure of mysql
Table structure for groups
CREATE TABLE `groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `org_id` int(11) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `org_id` (`org_id`),
  CONSTRAINT `groups_ibfk_1` FOREIGN KEY (`org_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Table structure for groups_perm
CREATE TABLE `group_perm` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `group_id` int(11) DEFAULT NULL,
  `permission_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `group_id` (`group_id`),
  KEY `permission_id` (`permission_id`),
  CONSTRAINT `group_perm_ibfk_1` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`),
  CONSTRAINT `group_perm_ibfk_2` FOREIGN KEY (`permission_id`) REFERENCES `perm` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Table structure for perm
CREATE TABLE `perm` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `app_id` int(11) NOT NULL,
  `namespace` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `description` text COLLATE utf8mb4_unicode_ci,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `default_perm` int(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `app_id` (`app_id`),
  CONSTRAINT `perm_ibfk_1` FOREIGN KEY (`app_id`) REFERENCES `applications` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Now i am running a couple of sql query when a new group is created in following format
[1ms] select count(*) from user where username= ?
[290ms] insert into user (username, active, is_organization, owner_id) values ( ? , 1, 1, ?);
[144ms] insert into groups (title, org_id) values ('default', ? )
[199ms] insert into group_perm (permission_id, group_id) select id, ? from perm where perm.default_perm=1;
[31ms] insert into user_group (user_id, group_id, org_id) values ( ? , ? , ?)

As you can see that running all queries on a single route is bad from user experience side and adds up to latency. I know an option would be to push that as a background job but i was really interested to know if somehow i can optimize the queries itself to execute faster.
Important stuff to know

*

*User and organization are stored in same table with is_organization flag set and in case of organization referencing to same table.

*The 4th query mentioned needs to be dynamic as default permissions to be given to new organization can change over time.

*I would prefer to keep foreign key index but am open to hear out any other suggestions as well.


text:
Q: Creating a reusable component that has dynamic children I've been trying to search for a solution, but I don't quite know what to search for. I basically want to create a reusable component that has a top and bottom toolbar, like this:
<StackLayout>
    <StackLayout Orientation="Horizontal" VerticalOptions="Start" BackgroundColor="{StaticResource ToolbarColor}">
        <!-- Top toolbar content-->
    </StackLayout>

    <!- ??? -->

    <StackLayout Orientation="Horizontal" VerticalOptions="End" BackgroundColor="{StaticResource ToolbarColor}">
        <!-- Bottom toolbar content -->
    </StackLayout>
</StackLayout>

I then want to be able to use it like so:
<ToolbarComponent>
    <!-- Contents -->
</ToolbarComponent>

What I don't know how to do, is the markup for the ToolbarComponent, what do I put where the ??? is, so that the page content I specify gets inserted in there?

A: The thing to do would be to create two separate UserControls for the toolbars.
Then use them like this.
<StackLayout>
    <controls:TopToolbar/>

    <!-- Contents -->

    <controls:BottomToolbar>
</StackLayout>


text:
Q: MULTER-S3: TypeError: Cannot convert object to primitive valu…diate [as _immediateCallback] I'm building a MEAN stack app using Multer-s3 to upload images to my database. However when I call the upload function I get this error:
POST http://localhost:3000/api/upload/single 500 (Internal Server Error)
TypeError: Cannot convert object to primitive valu…diate [as _immediateCallback](timers.js:354:15)↵", status: 500, config: Object, statusText: "Internal Server Error"

In my server side app.js
    // MULTER
    var s3config = require('./config/s3');
    var upload = multer({
      storage: s3({
        dirname: s3config.dirname,
        bucket: s3config.bucket,
        secretAccessKey: process.env.AWS_ACCESS_SECRET,
        accessKeyId: process.env.AWS_ACCESS_KEY,
        region: s3config.region,
        contentType: function(req, file, next) {
          next(null, file.mimetype);
        },
        filename: function(req, file, next) {
          var ext = '.' + file.originalname.split('.').splice(-1)[0];
          var filename = uuid.v1() + ext;
          next(null, filename);
        }
      })
    });

    // UPLOAD SINGLE FILE
    app.post('/api/upload/single', upload.single('file'), function(req, res) {
      var clothing_1 = {
        type: req.body.type,
        image: req.file.key
      };
      console.log('req.body =' + req.body);
      console.log('req.body.type =' + req.body.type);
      console.log('req.file.key =' + req.file.key);
      // get the user model User.findOne({ id: req.user._id })
      User.findOne({ _id: req.user._id }, {}, { new: true }, function(err, user){
        user.clothing.push(clothing_1);
        // save this user
        user.save(function(err, user){
          if(err) return res.status(401).send({ message: 'your error:' + err });
          else return res.json({ user: user })
        });
      });

    });

In my Front-end Controller:
  self.uploadSingle = function() {
    Upload.upload({
      url: API + '/upload/single',
      data: { file: self.file, type: self.clothingType }
    })
    .then(function(res) {
        self.usersClothing = res.data.user.clothing.map(function(clothing) {
            clothing.image = S3_BUCKET + clothing.image;
            return clothing;
        });
    })
    .catch(function(err) {
      console.error(err);
    });
  }

This function is executed when I press upload button.

A: Was simply a matter of server not being able to find the user as req.body gave _id inside _doc.
 User.findOne({ _id: req.user._doc._id } fixed the issue


text:
Q: How to transfer data from one sql table to another using php (delete previous data) I am working on a school project in which i have to let students request a course and an admin has to approve them. i have made 2 tables namely "requests" and "courses" what im failing to achieve is to get the data transferred from the requests table to the courses table all the while deleting the selected entry from the requests table. Below is the code from the first page. and the image is from the second
https://i.stack.imgur.com/ihwqZ.png]

    Student Name
    Student ID
    Course Name
    Course ID
    Course Faculty
    Course Timings
    Action

  <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM requests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
       echo "
". $row["u_name"]. "	". $row["u_id"]. "	". $row["c_name"]. "	". $row["c_id"]. "	" . $row["c_fac"] . "	".$row["c_time"]."	<form action=cnext2.php method=POST><input type=submit value=Accept>	</form>
";
    } echo "
";
} else {
    echo "0 results";
}

$conn->close();
?>

A: Find out the name of the requests table's primary key field.
If it doesn't have a primary key, then add one to the table (make it an UNSIGNED INTEGER). Then fill this hidden field with the value of the primary key. (Also, close the form before closing the td, and note, that input fields are self-closing):
<form action='cnext2.php' method='POST'>
    <input type='hidden' name='request_id' value=".$row['PRIMARY KEY FIELD NAME HERE']." />
    <input type='submit' value='Accept' />
</form>

Then in cnext2.php:
if(isset($POST)){
    // When getting data from post or get request or other user input, sanitize it
    $id = filter_input(INPUT_POST, "request_id", FILTER_SANITIZE_NUMBER_INT);
    $errors = array();

    if(!$id){
        errors[] = "No id submitted in request.";
    }
    // If you want to check other things, do it here and add error messages to the $errors array (validate your data)

    if(count($errors) > 0){
        foreach($errors as $error){
            echo $error . "
";
        }
    } else {
        // Create connection
        ...
        // Check connection
        ...
        $sql = "SELECT * FROM requests WHERE id = ".$id.";";
        $result = $conn->query($sql);
        while($row = $result->fetch_assoc()){
            $sql2 = "INSERT INTO courses (field1, field2, ...) VALUES ('".$field1."', '".$field2."', ...);";
            $res2 = $conn->query($sql2);
            $sql3 = "DELETE FROM requests WHERE id = ".$id.";";
            $res3 = $conn->query($sql3);
            echo "Request with the id $id has been accepted.
";
        }
    }
}


text:
Q: Photo app does not display photos Recently (~2 weeks), the Windows Photo app does often (~40%) not display the picture that I double clicked. The app is just empty:

The cursor is a blue "waiting" circle.
In that state, the call stack is
0:000> k
 # Child-SP          RetAddr               Call Site
00 00000019`06b3eb88 00007ffe`13198037     ntdll!NtWaitForMultipleObjects+0x14
01 00000019`06b3eb90 00007ffe`10627f01     KERNELBASE!WaitForMultipleObjectsEx+0x107
02 00000019`06b3ee90 00007ffe`10626d4c     twinapi_appcore!Event::WaitWithFreeUnusedLibraries+0xc9
03 00000019`06b3f110 00007ffe`10629202     twinapi_appcore!<lambda_aba22e915cba93f52f317319f66b8a2d>::operator()+0x1cc
04 00000019`06b3f230 00007ffe`04d68140     twinapi_appcore!Windows::ApplicationModel::Core::CoreApplicationFactory::Run+0x252

What can I do to make the app work as reliable as before?

A: Try to repair the app in the windows settings:

*

*Press Windows + I to open the settings app

*Go to "Apps"

*Go to "Apps & Features"

*Search for the Windows Photos App

*Click on it to navigate to the options

*Click the "Repair" button

After I repaired it, the Windows Photos app works again.


text:
Q: Long precedure in timer's callback I am working on a timer now, timers are maintained by a linked list.Like this:
struct timer
{
    struct timer* prev;
    struct timer* next;
    struct timespec start;
    struct timespec interval;
    void* par;
    int (*handler) (void* par);
};

Then I use a thread called dispatch to sleep and pick timers from the list.The code is simplified as below:
//just pseudo code here
void dispatch() {
    for (;;) {
        while (list_empty()) {
            wait();
        }
        timer* ptr = listhead();
        if (timer_begin(ptr)) {
            ptr->handler(ptr->par);
            list_pop_front();
        }
    }
}

Question:
When there is a long precedure in the callback function handler(say the handler function costs 500ms to execute, then dispatch stucks), the rest timers in the list may not be processed in time.So do we need a thread pool here?Or is there any other advices?

A: The problem of long duration tasks interleaved with short duration tasks is a fundamental problem of real-time (and near-real-time) systems. Having a separate thread to handle longer running tasks, and delegating longer tasks to a second thread is a good solution.  But is your long-running task waiting on io, or just heavy processing?
Should the delay be caused by asynchronous processing (waiting on io, for example), You might split the work into a 'top-half' and a 'bottom-half', where the 'top-half' dispatches the io request, and then schedules a 'bottom-half' to check for the results.  Alternatives are to handle the signal from the response, possibly with a promise (really interesting technique).
Should the delay be cause by a processing heavy task, you might still be able to use a similar technique, by forming your compute heavy task in such a way that it 'yields' periodically.  Threading is better, but may not be available in some embedded environments.


text:
Q: Add series to only the first row in a DataFrame in Python i have a series of tickers of the S&P500 constituents (ticker). I want to add all the tickers to my DataFrame (SP) within the column Ticker and within the row of the 2021-01-22.

So just copy all the tickers into one cell, like this:
SP = pd.DataFrame(data={'Date': "2021-01-22", 'Ticker': ['MMM,ABT,ABBV,...','NaN','NaN']})
SP

    Date    Ticker
0   2021-01-22  MMM,ABT,ABBV,...
1   2021-01-22  NaN
2   2021-01-22  NaN

I have tried SP.at[0, 'Ticker'] = ticker , but it did not work.

A: Ok, you can do this way
ticker_list = list(ticker.values)
SP.iloc[5494,1] = ', '.join(ticker_list)
SP

Here I have just made a list of ticker values and appended it to the row you want.
By seeing your image, your row for date '2021-01-22' seems to be 5494.

A: Create SP Data frame with Date Field
SP = pd.DataFrame(data={'Date': ["2021-01-22","2021-01-21","2021-01-20"]})

Create Ticker Column with 'NaN' Value
SP['Ticker']='NaN'

Create Ticker Data frame - You can ignore this step if you are converting list to data frame in order work on this requirement
Ticker=pd.DataFrame(['MMM','ABT','ABBV','...','NaN','NaN'])

Convert Ticker data frame column data into list and assign it to Ticker column in SP data frame
SP['Ticker'][0]=Ticker[0].tolist()  #From Data Frame

OR
Ticker  = ['MMM','ABT','ABBV','...','NaN','NaN']
SP['Ticker'][0]=Ticker              #From pre-defined list

display(SP)


text:
Q: Как можно объявить имя и тип переменной условно? Возможно ли объявлять переменные условно в функциях или процедурах?
Например, можно ли сделать что-то такое:
CREATE OR REPLACE FUNCTION get_total_sales(in_year PLS_INTEGER) RETURN NUMBER IS
    IF condtion THEN
        variable_name_1 BINARY_FLOAT;
    ELSE
        variable_name_2 NUMBER;
    END;
BEGIN
    NULL;
    -- логика функции
END;

Если условие condtion выполнится, то нужно объявить переменную с именем variable_name_1, если нет, то вместо этой переменной нужно объявить другую переменную - variable_name_2.

Свободный перевод вопроса Oracle PL/SQL Conditional Declaration? от участника @Ashan Priyadarshana

A: Условная компиляция (Conditional Compilation) досупна с версии 10g.
Пример:
create or replace procedure cctest as
$IF $$cctest_on $THEN
    var1 binary_float;
$ELSE
    var2 number;
$END
begin
$IF $$cctest_on $THEN
    var1 := 1.23E+004;
$ELSE
    var2 := 999;
$END
end cctest;
/
Procedure CCTEST compiled

alter procedure cctest compile PLSQL_CCFLAGS='cctest_on:true' reuse settings
/
Procedure CCTEST altered.

Так можно посмотреть исходный код последней компиляции:
exec dbms_preprocessor.print_post_processed_source ( -
    object_type => 'procedure', -
    schema_name => 'myschema',  -
    object_name => 'cctest');

procedure cctest as
var1 binary_float;
begin
var1 := 1.23E+004;
end cctest;

Свободный перевод ответа от участника @pifor

A: Не всегда условная компиляция возможна, например, значение условия вычисляется и на момент компиляции неизвестно. В этом случае можно воспользоваться условным оперетором IF-ELSE, чтобы поделить блок на подблоки, другими словами, на отдельные пространства имён.
Для избежания дубликации кода можно определить внутренние перегруженые функции. Принятые для этих целей в других ЯП синтктические конструкцие вида template, generic, в PL/SQL отсутствуют.
Примерно так это будет выглядеть:
create or replace procedure condtest (cond boolean) as
    function checkCondition return boolean is
    begin return cond;
    end;
    function foo (par binary_float) return binary_float is
    begin dbms_output.put_line ('foo(float)='||par); return par;
    end;
    function foo (par number) return number is
    begin dbms_output.put_line ('foo(number)='||par); return par;
    end;
begin
    if checkCondition then <<cond_on>>
        declare
            var1 binary_float := 1.23E+004;
            res binary_float := foo (var1);
        begin null;
        end;
    else <<cond_off>>
        declare
            var2 number := 999;
            res number := foo (var2);
        begin null;
        end;
    end if;
end condtest;
/

exec condtest (true)
foo(float)=1,23E+004

exec condtest (false)
foo(number)=999


text:
Q: Hide page loader spinner I have developed a login page. When a user press login button, I show a 'Loader spinner' and a second page shows up. But when user press back button in second page, Loader is still visible in first page. I can't hide it. How can I solve the problem? Is there any easier way to do this using AJAX?  My code: First page
enter code here
<!DOCTYPE html>

 <title>Forms with jQM</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />

Forms with jQM

 <form id="login" name="login" action="http://www.vyingbrain.net/testajax.aspx" method="POST" class="hide-page-loading-msg">

 Username:
 <input type="text" name="usr" id="usrn" value="" />

 Password:
 <input type="password" name="pss" id="pass" value="" />

 <input type="hidden" name="hiddenInput" id="hiddenInput" value="secret message" />
 <input type="submit" name="loginSubmit" id="loginSubmit" value="Login" class="show-page-loading-msg" />
 </form>

Second Page: testajax.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="TestAjax.aspx.vb" Inherits="TestAjax" %>

<!DOCTYPE html">

 <title>JQuery Test</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />

TestAjax

Go Back
 <form id="form1" runat="server">

 <asp:Label ID="lblDet" runat="server" Text="Label"></asp:Label>

 </form>

A: Try adding this to your script
    window.onload = window.onpageshow = function () {
        $.mobile.loading('hide');
    };

A: Try this...
$( document ).on( "pagechange", function() {
     $.mobile.loading('hide');
});


text:
Q: Postgres Flask Password Hash not working on Heroku What worked in Sqlite3 easily is posing a sudden issue in Postgres (Heroku). I have abstracted quite simply below, the issue of "bcrypt.check_password_hash" not matching the password user provides while logging in with the password saved in the database.  None of the solutions to previously asked questions, using encode or converting login password to bytes with utf8 seem to work as I have tried below:
from someproject.model import User, bcrypt
##>> Original password used when signing up: 123 ####

##>> Password was hashed and saved in Database using :
bcrypt.generate_password_hash(password).decode(utf8) ##

## Retrieving hashed password from Database User model ##
user = User.query.filter_by(email='pocofi9623@esmoud.com').first()
print('password saved in postgres database is:',user.password)
output: $2b$12$XK8aUYc9TfFtVtvcow/pPuORPHCXs4GJGCGb3IT4Hjg/EHfq0iQiG

## Password typed in login form : 123 ##
login_password = '123'

### Checking password match using 1 ##
if bcrypt.check_password_hash(user.password.encode(), bytes(login_password, 'utf8')):
   print('True')
else:
   print('False')

output FALSE

#### Checking password match using 2 ###
if bcrypt.check_password_hash(user.password, bytes(login_password, 'utf8')):
   print('True')
else:
   print('False')

output FALSE

### Checking password match using 3 ####
if bcrypt.check_password_hash(user.password, login_password):
   print('True')
else:
   print('False')

output FALSE

Can someone point me in the right direction ?


text:
Q: Convolutional Neural Networks batch size Question1.
Let us say the image have a shape of (batchsize=100,height=28,width=28,channel=1)
and if we put this image in the model CNN underneath,
class CNN(torch.nn.Module):

        def __init__(self):
            super().__init__()

            # ImgIn shape=(100, 28, 28, 1)
            #   Image shape after Conv     -> (100, 28, 28, 32)
            #    Image shape after Pool     -> (100, 14, 14, 32)
            self.layer1 = torch.nn.Sequential(
                torch.nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1),
                torch.nn.ReLU(),
                torch.nn.MaxPool2d(kernel_size=2, stride=2))

            # second layer
            # ImgIn shape=(100, 14, 14, 32)
            #   Image shape after Conv      ->(100, 14, 14, 64)
            #   Image shape after Pool      ->(100, 7, 7, 64)
            self.layer2 = torch.nn.Sequential(
                torch.nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
                torch.nn.ReLU(),
                torch.nn.MaxPool2d(kernel_size=2, stride=2))

            # THESE PART CONFUSE!!!
            self.fc = torch.nn.Linear(7 * 7 * 64, 10, bias=True)

            torch.nn.init.xavier_uniform_(self.fc.weight)

        def forward(self, x):
            out = self.layer1(x)
            out = self.layer2(out)
            out = out.view(out.size(0), -1)
            out = self.fc(out)
            return out

WHAT HAPPENS to the batchsize of the image after self.fc.
Is it size(batch_size=100,10)?
Qustion 2.
Also, I am confused of mini-batch. If there is 5 mini batch, and the loss is [5,-5,4,-4,0], then the average loss will be zero, then will the neural network stop training even if there is loss in each mini-batch?
Qustion 3.
Can neural network be expressed my complex matrix multiplication?

A: Q1
self.fc is just a single linear layer. The key line here is out.view(out.size(0), -1) which is nothing but flatten (reshape in NumPy), where out.size(0) is your batch size and -1 is all elements of the tensor (See torch.view).
In other words, this line transforms your 4d (Batch, C, H, W) Conv layer into 2d (Batch, 7 * 7 * 64). Finally, your fc layer outputs (Batch, 10)
Q2
This question is confusing. How did you get this loss? It seems, that there is a missing part of your code.
Q3
A linear multilayer perceptron is actually a matrix multiplication. We can apply nonlinear activation function to the output of each layer (which is a result of matrix multiplication).
CNN can also be seen as a kind of matrix operation. This type of operation is called convolution
So, since you have a complex network, you cannot express it as a single matrix multiplication.


text:
Q: yarn cannot build node-sass with node 12.1.0 I am trying to install my packages with yarn install
I have node 12.1.0 installed, and as I understand, node-sass needs to be at least version 4.12+ to work with node 12
my package.json file is as so:
{
  "name": "redacted",
  "private": true,
  "dependencies": {
    "@rails/webpacker": "3.5",
    "babel-preset-react": "^6.24.1",
    "bootstrap": "^4.1.2",
    "font-awesome": "^4.7.0",
    "js-md5": "^0.7.3",
    "moment": "^2.22.2",
    "prop-types": "^15.6.2",
    "qrcode.react": "^0.8.0",
    "react": "^16.4.1",
    "react-big-calendar": "^0.19.2",
    "react-dom": "^16.4.1",
    "react-loading": "^2.0.3",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-transition-group": "^2.5.0",
    "urijs": "^1.19.1"
  },
  "devDependencies": {
    "webpack-dev-server": "2.11.2"
  }
}

The (truncated) error I get is:
../fsevents.cc:85:58: error: expected ';' after top level declarator
void FSEvents::Initialize(v8::Handle<v8::Object> exports) {
                                                         ^
                                                         ;
30 warnings and 14 errors generated.
make: *** [Release/obj.target/fse/fsevents.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:196:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:256:12)
gyp ERR! System Darwin 18.2.0
gyp ERR! command \"/usr/local/Cellar/node/12.1.0/bin/node\" \"/Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/node-gyp/bin/node-gyp.js\" \"build\" \"--fallback-to-build\" \"--module=/Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/fsevents/lib/binding/Release/node-v72-darwin-x64/fse.node\" \"--module_name=fse\" \"--module_path=/Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/fsevents/lib/binding/Release/node-v72-darwin-x64\" \"--napi_version=4\" \"--node_abi_napi=napi\"
gyp ERR! cwd /Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/fsevents
gyp ERR! node -v v12.1.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/Cellar/node/12.1.0/bin/node /Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/fsevents/lib/binding/Release/node-v72-darwin-x64/fse.node --module_name=fse --module_path=/Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/fsevents/lib/binding/Release/node-v72-darwin-x64 --napi_version=4 --node_abi_napi=napi' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/fsevents/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:196:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1000:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:267:5)
node-pre-gyp ERR! System Darwin 18.2.0
node-pre-gyp ERR! command \"/usr/local/Cellar/node/12.1.0/bin/node\" \"/Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/fsevents/node_modules/node-pre-gyp/bin/node-pre-gyp\" \"install\" \"--fallback-to-build\"
node-pre-gyp ERR! cwd /Users/snowflakekiller/Documents/Projects/Code/sjc_platform/node_modules/fsevents
node-pre-gyp ERR! node -v v12.1.0
node-pre-gyp ERR! node-pre-gyp -v v0.10.0
node-pre-gyp ERR! not ok

I have tried installing just node-sass alone with yarn add node-sass but it still fails with the same sort of error.
How can I get get past this?

A: I managed to solve this by deleting my lockfile and running yarn install again.


text:
Q: Fixed Space Bar Button Item places buttons outside of screen I want to implement a toolbar in my iOS app, which displays the App's logo in the center of the toolbar and shows a + button on the right side.
So, I placed a Toolbar element on the view, then two bar button items (logo and add symbol) and placed two flexible space bar button items between them.
It now looks like this:
Storyboard
While this looks exactly like the desired behavior, it does not look like this in the simulator:
Simulator Portrait Mode
When testing the app with the iPhone 6s, the logo part is a little bit more to the left, but still not in the center. I am obviously doing something wrong, because I thought the point of "flexible space bar button items" is to dynamically adapt to different resolutions. What is it?

A: You should be using a UINavigationBar instead of a UIToolbar.
UINavigationBar is for the top of the screen since it has a shadow on its bottom edge. It also supports having a title/titleView that is centred.
UIToolbar is for the bottom of the screen since it has a shadow on its top edge. It does not have properties for adding a title so you would have to do it manually. Also, flexible space lays out the elements so each flexible width item has the same width.


text:
Q: Eclipse Helios/Galileo Update sites cannot be accessed on Windows machine with IE7 When starting the update, the following error is displayed:
Network connection problems encountered during search.
  Unable to access "http://download.eclipse.org/releases/helios".
    Error accessing site stream. [Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]
    Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
    Error accessing site stream. [Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]
    Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
As described at
http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic
http://www.outofcontrol.ca/2009/02/20/w3org-dtdxhtml1-strictdtd-blocks-windows-ie-users/
w3.org blocks IE calls to http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd (as it is loading it much too frequently). I was able to load the DTD by setting a different UserAgent for IE7 using
%windir%\System32\cmd.exe /k %windir%\System32\reg.exe ADD "HKLM\Software\Microsoft\Windows\CurrentVersion\Internet Settings\5.0\User Agent" /v Version /d "Opera/9.2.1" /f
I tried to -D overrides suggested at:
Change user agent in Eclipse 3.5 for new software installations
to no avail. I think eclipse does not follow the User-Agent set by IE7 ...
Is there an other way to override the User-Agent for Eclipse?
Thanks

A: Eclipse has gone "Market", joining AppStore by Apple and Marketplace by google.
From Help Menu, try Eclipse Marketplace instead of Install New Software to install and update your required plug-in

A: This seems to be related to using the "classic updater" against Helios update site as described at
https://bugs.eclipse.org/bugs/show_bug.cgi?format=multiple&id=317957

A: I have the same problem both on Galileo and Helios and Windows 7 64 bit, and have found yet no solution (adding a '/' or removing a '/' to the end of the update sites URLs does not work).
In Helios, at least, I have found that using the "Eclipse Marketplace" for updates/addins does work.


text:
Q: Error on 'Extract raster values to CSV' in batch process in QGIS The Extract values (csv) contained a bug in the script. The below link shows how to correct the bug. Error on 'Extract raster values (CSV)' - Error executing algorithm 1 'Dataset' object has no attribute 'mapToPixel' See log for more details
However, a batch process always stops at the 8th iteration when I use the corrected extract raster values to CSV script (no matter I change the different raster inputs).
Here are the error messages at 8th iteration.
**Algorithm Extract raster values (CSV) starting...**

Prepare algorithm 0: Points from vector
Parameters: Input_raster =D:\IDD_RCP\8.5\Averaged_RCP8.5_Nan_basin\2080-2099\ta\RCP_8_5_mrc3_2080_2099_ta_mon10_RCP_8.tif, Input_vector =D:\Average_Raster_over_Vector\Nan_basin_centroid_WGS.shp
Outputs: Output_layer =C:\Users\NORASET\AppData\Local\Temp\processing\592fdd79ac8f43d4bffc01e05dc89310\Outputlayer.shp
OK. Execution took 1.145 ms (1 outputs).
Prepare algorithm 1: Extract raster values to CSV
Parameters: Input_raster =D:\IDD_RCP\8.5\Averaged_RCP8.5_Nan_basin\2080-2099\ta\RCP_8_5_mrc3_2080_2099_ta_mon10_RCP_8.tif, Input_vector =C:\Users\NORASET\AppData\Local\Temp\processing\592fdd79ac8f43d4bffc01e05dc89310\Outputlayer.shp, Transform_vector_to_raster_CRS =False
Failed

**Error executing algorithm 1 [Errno 9] Bad file descriptor See log for more details**


text:
Q: Angular 2 Library Global Styles I am creating an Angular 2 Library. I want to add global styling to unify the font. I tried to put styles in styles.css, which didn't help. It seems like styles.css is not included as part of the library. When I do ng serve and make changes to styles.css, nothing happens and the compiler doesn't even refresh.
In .angular-cli.json file, I included styles.css.

Any idea? What is the best way to add global styles to Angular 2 Library?


text:
Q: CIFS isn't using the specified username when mounting I am attempting to run a development server using Hyper-V. The goal is to do my front-end and back-end development in Windows while keeping my back-end files on the virtual server. The server is installed and running, it has an internet connection, and I can SSH into the virtual server but I can't get the shared folders to work.
I have turned on file sharing and shared the specified folder in Windows. I installed CIFS on the virtual server. I set up a static IP address for the virtual server.
I am using the following command
sudo mount.cifs //DESKTOP-PBAGEL3/Users/Leslie/Documents/Development ~/Documents/Development user=Leslie
However when cifs attempts to mount it asks for the password for:
root@//DESKTOP-PBAGEL3/Users/Leslie/Documents/Development
This of course will not work, I attempted to add uid=Leslie and forceuid but I still get the same result. I am expecting the password prompt to read:
Leslie@//DESKTOP-PBAGEL3/Users/Leslie/Documents/Development

A: man 8 mount.cifs states:

mount.cifs {service} {mount-point} [-o options]

[…]
Options to mount.cifs are specified as a comma-separated list of key=value pairs.

So instead of sole user=Leslie you need -o user=Leslie.


text:
Q: An example of unit testing in C#? What exactly is a unit test and how do I write one? I hear many times people write them before their app is even written, how can this be? I am under the impression that a unit test is some code that makes a call to a method of your app with a set value and expects a specific value to come back, if the specific value does not come back the test has failed. Am I wrong or mislead here? I read so much about unit testing but I know very little about what it actually looks like in code so a sample would be great.
Is this a unit test?
start psuedo code...
CheckForDuplicateSubdomains(){
  get all users in DB with matching subdomains
  if greater than zero, fail test
}

PS: I am using ASP.NET MVC in C#

A: You are correct about unit testing. The idea is to test all your functions, one by one, with different inputs to make sure they work like you expect (as opposed to finding out after they've been inserted into an application.. and then making the testing more complicated).
Writing the unit tests before you write the function is part of a methodology called "Test driven development". In which you write the skeleton of the function only, and all the unit tests first. So at first all your tests will fail (b/c the function is not programmed yet). After that you program the function until all the tests pass.

A:
I am under the impression that a unit test is some code that makes a call to a method of your app with a set value and expects a specific value to come back, if the specific value does not come back the test has failed. Am I wrong or mislead here?

Nope, you are exactly right.
The important thing with unit tests is to test a small a piece of code as possible.
In your example you get something from the db and then count the number of items... If your method fails, you'll never know exactly where the things went wrong because there is so much that could go wrong....
Your db-connection could be lost, sql invalid, ...
If you are using asp.net MVC, you should have an easier time writing unit tests than if you were using normal asp.net

A: A Unit Test is a test that exercises a very small portion of your code, usually a single method (a Unit to be exact).
In TDD, developers are able to write the Unit Test before coding the method because they already know what the Unit of code should do. It doesn't matter how it does the work...the test just makes sure the results are correct.
And that pseudo-code could be used as a Unit test (not sure what it would be testing, but I would have to assume you're testing a method that shouldn't return duplicate SubDomains).
The theory is Unit Testing (and Test Driven Development) should alleviate headaches further down the road by making sure each Unit of code does exactly what is expected of it.

A: Yes, your example would be a unit test. There are a few reasons to create the test first. First, it acts as living documentation for your project. It establishes behaviors and expected outcomes, which should help you actually implement your code (it's easier to write something, knowing what it needs to do and basically how it is initiated). Secondly, if you write the test afterward, you're more likely to write a test that works with the code you already wrote, which doesn't help you. Define what a unit of code needs to do, write the tests, and write/fix the code so it reflects the behaviors in the tests. This strategy translates into improved understanding and quality as your application evolves.

A: Unit testing is automated testing at the Unit level.  By unit level they mean atomic code unit such that you can't break it down further. a function or a particular part of an object.  a unit test for a square function would look something like
 assertEqual(4, square(2));
 assertEqual(4, square(-2));
 assertEqual(0, square(0));

Now you can write this as soon as you have decided on the interface of square,  for a more complicated function you could measure how close to complete the function is by how many tests pass.

A: There are very well established conventions for unit testing in the xUnit family of  frameworks, originally derived from jUnit.  In that framework, the assertion is the main vehicle for making a test.  In a test suite, the objective is to ensure that 100% of your assertions are true.
Consider your example.
CheckForDuplicateSubdomains(){
  get all users in DB with matching subdomains
  if greater than zero, fail test
}

This test would conventionally have a name starting with "test", which lets the framework's test runner know that this function is a test and not a setup method, say.   It is important to be clear that we are testing the behavior of the code, and not the state of the data.
testNoDuplicateSubdomains(){
}

Within each test, there are four phases:

*

*fixture setup,

*exercise SUT,

*result verification and

*fixture teardown.

The SUT is the "system under test", which is typically one method of a class in your production code.
testNoDuplicateSubdomains(){
  // fixture setup
  prepareDatabaseTestData()
  // exercise SUT,
  SUT = new ProductionObject()
  result = SUT.getAllUsersWithMatchingSubDomains()
  // result verification and
  assertEmpty(result) // or whatever makes sense
  // fixture teardown.
  removeDatabaseTestData()
}

As with many software development techniques, it takes a while to get experienced at writing unit tests.  A good resource for learning the best practices is xUnit Test Patterns by Gerard Meszaros.


text:
Q: What to do about this bad (really old) question with one good answer? This question with >12000 views from 2009 reads (in full!)

How to run a C program in DOS prompt
I want to run a C program in DOS prompt. Is it possible?

I'd flag it for "very low quality" in a second since the OP never answered the comments he got about clarifying his question; however I learned something from an answer which interpreted the question in a useful way, so I'm tempted to modify the question to fit that answer. However, that would render all other answers (which contain valid, but extremely basic information) not-an-answer.
What to do? Just leave it be, an example of a really bad question?
Edit
I like Adam's argument that all answers are helpful. I propose to leave a comment to the question though, referring to this meta post, along the lines

Note this question is too ambigous for a good question and would usually be deleted; but it has useful answers interpreting it in different ways, so people can still learn something here.

What do you think?

A: Why do anything? The usual problem with bad questions is the bad answers they attract; since this got a good one, that's no longer a worry.

A: I'm torn.  Generally I'd say don't hesitate to close and delete poor questions and answers, but in this case, it's not just one good answer, they are all good answers for a very, basic, simple question.
A question a lot of people who aren't programmers have.
Each answer approaches it differently, and future visitors can learn enough about their problem to find the correct solution for them.
I think it should stay, as-is.
If anything, modify each answer so it becomes better and more canonical for its approach.

A: If you see a bad question with a good answer,
  edit the question
to make it easier for people who would benefit from the answer to find that answer.
With a recent question, you should not make changes other than presentation (formatting, grammar, clarifications), out of respect for the asker. If the question should be closed if it remains in its present state, you can be more liberal in your edits in order to salvage the question.
If the question is old and abandonned, you have more latitude in changing it so that it can still be useful to future visitors. Your guideline is then to ensure that the answers will remain relevant.
If some of the answers are not really relevant to the site at large, it may be ok to invalidate them, but err on the side of caution. For example, in the specific case you mention, some answerers have interpreted the question as "how do I run a program at a command line prompt"; that would be off-topic on Stack Overflow. "I have a C program intended for DOS, how do I run it under Windows?" is a question about programmer tools, and therefore it is on-topic for Stack Overflow (if marginal). It's ok to edit the question in a way that rules out the first interpretation, and then delete the answers that no longer apply (that would not be ok if the first interpretation had been on-topic).


text:
Q: Running Angular 2 app on VS Code I just created an Angular 2 app (HighlightMeDirective) in VSCode by following this plunker link HighlightMeDirectivce
On further research I found these are the steps to be followed for starting the app

*

*Create a tasks.json file

*Creating tsconfig.json file

*Creating package.json file

Is this is the standard approach to be followed (in VSCode) or is there any simple approach to kick start the app (I don't want to use angular-seed)

A: This is the standard approach and

*

*tasks.json - this file is optional.

*tsconfig.json - this file contains the information about how your
compiler should compile your typescript into java script

*package.json - this file contains information and description
about your app and also contains the list of dependencies your
project has.


text:
Q: Duplicate block content I would like to duplicate the filters block content on layered category pages.
I'm using this code :
<referenceContainer name="category.product.list.additional">
    <action method="append">
        <argument name="block" xsi:type="string">catalog.leftnav</argument>
        <argument name="as" xsi:type="string">alias.name</argument>
    </action>
</referenceContainer>

but instead of duplicate the block it moves it to the new container and remove it from the left sidebar.
Thanks !

A: Using an additional block (whose class is Mbs\ProductList\Block\LeftNavClone in my example below) that instantiates the block catalog.leftnav like below does the effect you seem to aim for:
<referenceContainer name="category.product.list.additional">
    <block class="Mbs\ProductList\Block\LeftNavClone" name="catalog.leftnav.clone">
        <arguments>
            <argument name="originalBlock" xsi:type="string">catalog.leftnav</argument>
        </arguments>
    </block>
</referenceContainer>

the code for the block as below:
<?php
    namespace Mbs\ProductList\Block;

    class LeftNavClone extends \Magento\Framework\View\Element\Template
    {
        protected function _toHtml()
        {
            $clone = $this->getLayout()->getBlock($this->getData('originalBlock'));
            if ($clone) {
               return $clone->toHtml();
            }
        }
    }

A: I added a block to my theme by cloning the block class and adding the before and after tags to make one sit on top of the other. I needed different CCS for mine so I created some new CSS classes. In mine I wanted the new block to sit directly above the old one. See code below.
Note the first block has the before="-" tag and the second block has the after="-" tag.
<referenceContainer name="header.container">
    <container name="rd.navbar-wrap" htmlTag="div" htmlClass="rd-navbar">
        <container name="rd.navbar" htmlTag="div" htmlClass="rd-navbar-panel layout_1">
            <block class="Magento\Cms\Block\Block" name="header_info_2" before="-">
                <arguments>
                    <argument name="block_id" xsi:type="string">header_info_2</argument>
                </arguments>
            </block>
            <block class="Magento\Cms\Block\Block" name="header_info" after="-">
                <arguments>
<argument name="block_id" xsi:type="string">header_info</argument>
                </arguments>
            </block>
        </container>
    </container>
</referenceContainer>

Once I added these changes to layout.xml in my theme I created a new block in the admin panel with the block identifier "header_info_2" and it showed up correctly. There was quite a few CSS files with the original class header-info so I had to create new custom classes that corresponded to the new blocks design.
The original code block in layout.xml looked like this:
<referenceContainer name="header.container">
    <container name="rd.navbar-wrap" htmlTag="div" htmlClass="rd-navbar">
        <container name="rd.navbar" htmlTag="div" htmlClass="rd-navbar-panel layout_1">
            <block class="Magento\Cms\Block\Block" name="header_info" before="-">
                <arguments>
                    <argument name="block_id" xsi:type="string">header_info</argument>
                </arguments>
            </block>
        </container>
    </container>
</referenceContainer>

Hope this helps
Below is an image of the 2 blocks on the frontend homepage. The top one is the new one with the new CSS.


text:
Q: Confusion about django.shortcuts.render() method signature in 1.10 The Django 1.10 release notes (https://docs.djangoproject.com/en/1.10/releases/1.10/#features-removed-in-1-10) say:

*

*The dictionary and context_instance parameters for the following functions are removed:

*

*django.shortcuts.render()

*...

However, the documentation for render() in 1.10 (https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render) still lists context as an argument of type dictionary:
context
A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.

My question, to put it frankly, is what gives? Normally this would be an academic question, but the following code:
def index(request):
    context = RequestContext(request, {})
    return render(request, 'maintenance/maintenance.html', context)

yields this error:
TypeError: dict expected at most 1 arguments, got 3

and this was the best lead I could find as to what the problem might be. I should also mention that this error appeared after updating Django from 1.8 to 1.10.

A: You are confusing context and context_instance, which are two separate arguments. The context_instance argument has been removed in Django 1.10, but context remains.
As the docs say, context should be a dictionary of values. You are getting the error because you are passing a RequestContext instance instead of a dictionary. You can fix your example view by changing it to:
def index(request):
    context = {}
    return render(request, 'maintenance/maintenance.html', context)


text:
Q: 7-Zip: Any good tutorials? I'm thinking about using the 7-Zip format to pack my application files since it's a very compact and popular format. I can't find some tutorials on how to use the C++ SDK, though. I'd like some tutorials that teach me how to:

*

*Open an archive from memory (buffer) instead of directly from disk.

*Extract individual files inside the archive, to buffer, not to disk.

*Check if a certain file can be found in the archive.

A: From the LMZA SDK documentation:

ANSI-C LZMA Decoder
~~~~~~~~~~~~~~~~~~~
Please note that interfaces for ANSI-C
  code were changed in LZMA SDK 4.58. If
  you want to use old interfaces you can
  download previous version of LZMA SDK
  from sourceforge.net site.
To use ANSI-C LZMA Decoder you need
  the following files: 1) LzmaDec.h +
  LzmaDec.c + Types.h
LzmaUtil/LzmaUtil.c is example
  application that uses these files.

The example app should have everything you need, else the actual source for 7-zip will have what you need. There is also a C++ wrapper for 7-zip here which should simplify a lot of the needed ops.


text:
Q: How many operating system resources is needed for one Java Kafka Consumer? I want to use hundreds of thousands of KafkaConsumer. For example, I need 100_000 consumers for some architectural pattern. I am thinking, is it OK? Or should I to refactor my system and use few consumers for the whole system (for example, 10 consumers instead of 100_000).
So, my questions are:

*

*Is there connection pool in KafkaConsumer, or each consumer creates own connection to kafka brokers?

*Is there thread pool in KafkaConsumer, or each consumer creates own thread (I hope, it does not).

*What is average memory consumption per KafkaConsumer?

*What do you think about such architectural pattern?

A: 1,2) Consumers request metadata from one of the brokers which is the leader of the partition. Each consumer is able to handle all IO from a single thread as the Java clients are designed around an event loop which is driven by the poll(). You can also build multi-threaded consumers but you'd need take care of offset management. Refer to Confluent's documentation for more details regarding the implementation of Java Clients.
3) According to Apache Kafka and Confluent Enterprise Reference architecture,

Consumers use at least 2MB per consumer and up to 64MB in cases of
  large responses from brokers (typical for bursty traffic)

4) The number of consumers you've mentioned is huge so you'd need a very good reason to go for 100,000 consumers. It depends on the scenario though, but even Netflix should be using a lot less than that.


text:
Q: Json On Complete Run Function I'm trying to figure out how I can have a function run as soon as this json has fully completed and loaded. The problem I'm running into is that my links load before my anchors do. So it looks like everything has loaded but when you click on the links nothing loads until 3-6 seconds after you click because it is still loading the linked anchors. I'd love a way to definitively tell when this function has run and the content fully loaded. Anyone know how I might go about that?
I looked on Jquery's site and found something that might work but am unsure how to plug it in:
.complete(function() { alert("complete"); });

Is this the right path and if so how might I get it to work with my code below:

*

*IOS Phonegap app

*JQUERY 1.7.1

*Jquery-Mobile 1.1


text:
Q: Active Record Query - Has many through association I am trying to write active record queries in my model for an advanced search.
I have a Firms model and each firm has many Categories through Categorizations
I have the following built into my search method at the moment.
def find_firms
    firms = Firm.order(:name)
    firms = firms.where("name like ?", "%#{name}%") if name.present?
    firms = firms.categories.find(id: category_id) if category_id.present?
end

My category schema looks like this.
create_table "categories", :force => true do |t|
  t.text     "name"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
 end

and my categorizations
 create_table "categorizations", :force => true do |t|
   t.integer  "category_id"
   t.integer  "firm_id"
   t.datetime "created_at",  :null => false
   t.datetime "updated_at",  :null => false
 end

and my search form view

    <%= f.label :category_id, "Practice Area" %>

    <%= f.collection_select :category_id, Category.order(:name), :id, :name, include_blank: true %>

Any ideas what I am doing wrong?
As i keep getting the error:
 undefined method `categories'

Many thanks.
Ross

A: Change your find_firm function to this:
 def find_firms
    if category_id.present?
      if name.present?
        Firm.where("name like ?", "%#{name}%").joins("JOIN categorizations ON firms.id = categorizations.firm_id").where("categorizations.category_id = ?", category_id).order(:name)
      else
        Firm.joins("JOIN categorizations ON firms.id = categorizations.firm_id").where("categorizations.category_id = ?", category_id).order(:name)
    elsif name.present?
      Firm.where("name like ?", "%#{name}%").order(:name)
    else
      Firm.order(:name)
    end
  end

A: You are trying to run the categories method on the array returned by firms which will fail. I am assuming you want to return the firms with the given category id.
def find_firms
  firms = Firm.order(:name)
  firms = firms.joins(:categories).
            where(:categories =>{ id : category_id}).uniq if category_id.present?
  firms = firms.where("name like ?", "%#{name}%") if name.present?
end


text:
Q: How to set up a SlashCommand with custom options for discord I've been at this for 4h now... I'm making a discord bot that should take a user's input and define the word using an API call. I have an index.js that should call my urban.js file and define a word a user inputs. For example, if a user inputs "/urban cow," the bot should put the definition of a cow. However, right now it cannot read the option after "/urban" no matter what I try.

// THIS IS MY urban.js FILE

const {
  SlashCommandBuilder,
  SlashCommandStringOption
} = require('@discordjs/builders');
const {
  request
} = require('undici');
const {
  MessageEmbed
} = require('discord.js');
const wait = require('node:timers/promises').setTimeout;
const trim = (str, max) => (str.length > max ? `${str.slice(0, max - 3)}...` : str);

async function getJSONResponse(body) {
  let fullBody = '';

  for await (const data of body) {
    fullBody += data.toString();
  }
  return JSON.parse(fullBody);
}

module.exports = {
  data: new SlashCommandBuilder()
    .setName('urban')
    .setDescription('Replies with definition!')
    .addStringOption(option =>
      option.setName('input')
      .setDescription('word to define')
      .setRequired(true)),

  async execute(interaction) {
    const term = interaction.options.getString('input')
    console.log(term);

    const query = new URLSearchParams({
      term
    });
    const dictResult = await request(`https://api.urbandictionary.com/v0/define?${query}`);
    const {
      list
    } = await getJSONResponse(dictResult.body);

    if (!list.length) {
      return interaction.editReply(`No results found for **${term}**.`);
    }

    const [answer] = list;
    const embed = new MessageEmbed()
      .setColor('#EFFF00')
      .setTitle(answer.word)
      .setURL(answer.permalink)
      .addFields({
        name: 'Definition',
        value: trim(answer.definition, 1024)
      }, {
        name: 'Example',
        value: trim(answer.example, 1024)
      }, {
        name: 'Rating',
        value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`,
      }, );
    interaction.editReply({
      embeds: [embed]
    });

  },
};

// THIS IS THE INDEX JS FILE. It's not a filepath issue.

const {
  token
} = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
const {
  Client,
  Collection,
  Intents,
  MessageEmbed,
  DiscordAPIError
} = require('discord.js');
const wait = require('node:timers/promises').setTimeout;

const client = new Client({
  intents: [Intents.FLAGS.GUILDS]
});
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
  const filePath = path.join(eventsPath, file);
  const event = require(filePath);
  if (event.once) {
    client.once(event.name, (...args) => event.execute(...args));
  } else {
    client.on(event.name, (...args) => event.execute(...args));
  }
}

for (const file of commandFiles) {

  const filePath = path.join(commandsPath, file);
  const command = require(filePath);

  // Set a new item in the Collection
  // With the key as the command name and the value as the exported module
  client.commands.set(command.data.name, command);
}

client.once('ready', () => {
  console.log('Ready!');
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  const command = client.commands.get(interaction.commandName);
  await interaction.deferReply({
    ephemeral: true
  });
  await wait(4000);
  if (!command) return;

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);

  }
});
console.log(token)
client.login(token)

When I console.log(interaction.options.getString('input'))
it just gives me null.
when I console.log interaction it gives me a detailed account of the command and everything else like the user that sent it. But none of the information from the SlashCommand data. Please help.


text:
Q: Conditional expectation as an orthogonal projection to what subspace? Given a random variable $X$ and a sub sigma algebra $N$ of its sampling space, it is often said that $E(\dot \, \mid N)$ is an orthogonal projection, since $X-E(X\mid N)$ and $E( X\mid N)$ are uncorrelated.
I understand that to be $X-E(X\mid N)$ is orthogonal to some subspace of random variables which include $E(X\mid N)$. I wonder how to determine the subspace of random variables from $N$?
Here do we require $X$ to be $L^2$ or $L^1$?
Thanks!

A: In order to make the inner product well-defined, we talk about $L^2(\Omega,\mathcal F,\mu)$, where $(\Omega,\mathcal F,\mu)$ is the underlying probability space. But we then extend condition expectation to integrable random variables.
We use a projection over the closed subspace $L^2(\Omega,\mathcal N,\mu)$, that is, the vector subspace which consists of equivalences classes of $\mathcal N$-measurable random variables (for the relation "equal $\mu$-almost everywhere").


text:
Q: Code=-1011 "Request failed: internal server error (500) I meet this problem for 2 days,Android app works well with this background interface,but I always receive the 500 error.My code is like this.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager POST:urlString parameters:self.param.mj_keyValues  success:^(NSURLSessionDataTask *task, id responseObject) {
        ....
} failure:^(NSURLSessionDataTask *task, NSError *error) {
        ....
}];

and then,the program goes into the failure block,and I get NSError log like this.
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7fc26b49a080> { URL: https://training.duapp.com/record_data } { status code: 500, headers {
Server = openresty;
Content-Type = text/html;charset=utf-8;
Vary = Accept-Encoding;
Content-Language = en;
Date = Fri, 02 Sep 2016 03:55:00 GMT;
Content-Encoding = gzip;
Content-Length = 646;
Connection = keep-alive;
}
}, NSErrorFailingURLKey=https://training.duapp.com/record_data, com.alamofire.serialization.response.error.data=

Then I tried to convent the param from NSDictionary to NSData or NSString,and change requestSerializer with it,but all failed with error 500.The format of the param has no error,which is conformed by my background workmate.Can I get any help from you?What should I do?

A: Code=-1011 "Request failed: internal server error (500)" is server side issue. Please check with your server team to check because server is returning an error to your request.

A: NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
[params setObject:@"214" forKey:@"id"];
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/api_url"];
NSString *path = @"Path";
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager GET:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject){
       NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
       NSLog(@"Success: %@", json);
  }failure:^(NSURLSessionDataTask *task, NSError *error){
             NSLog(@"Failure: %@", error);
  }];


text:
Q: Upgrade laptop hardware (RAM is more than possible) Aida64 shows the maximum memory on my ultrabook 16 GB
4GB + 4GB on the motherboard.
I want to increase to 16 GB of memory. But the maximum is 16 GB, and 4 is already on the motherboard.
If I put 16, then the total will be 20 (which is more than specified in the processor specification)
How will the laptop behave if I install more memory than possible?
I only have one slot so I want to use the maximum potential memory.

*

*Will there be a problem with the operation of such a board with 16 GB? (in the amount of 20 GB)

*What is the priority of the main memory? Installed separately or built-in?

*Will the laptop work normally with over-memory? (cuts off excess or does it cause errors?)

My processor: https://ark.intel.com/en/products/85214/Intel-Core-i7-5500U-Processor-4M-Cache-up-to-3_00-GHz


text:
Q: Ubuntu can't mount my NTFS external hard drive with Windows installed on it I have an external hard drive with Windows 8 installed on it. Ubuntu cannot mount this drive.
Failed to mount '/dev/sdb5': Operation not permittedThe NTFS partition is in an unsafe state. Please resume and shutdown
Windows fully (no hibernation or fast restarting), or mount the volume
read-only with the 'ro' mount option.

I'm not using this Windows installation right now, so I don't mind deleting it. What can I do to fix this? Do I have to delete some partitions in the drive? If so which ones? Or is there an easier way?
Thanks.
Edit: I forgot to mention that the Windows installation is broken so I have no way of booting into it and shutting it down properly. Also, the main partition of the HDD (not the windows partition) has important data.
Final Update (Solution):
Check this tutorial.

A: if you wish to delete the windows installation, you can either delete the partition with fdisk or the like, or simply make a new filesystem with the mkfs command, like so:
mkfs -t <filesystem type> /dev/sdb5, where filesystem type can be any number of supported filesystems, including ntfs, ext{2,3,4}, fat{12,16,32}, and so fourth. But, this seems a bit overkill. You can simply boot the windows partition and properly shut it down.

A: You just have to follow the instructions in the error message.
Windows was not shut down properly, but suspended (hibernated to be exact). This is also automatically done instead of shutting down if you have enabled the FastBoot option.
So now it still has marked the drive as used somehow which prevents Ubuntu from getting full (r+w) access to the drive. You can mount it as read-only without problems, though.
The easiest solution to get full access to the drive without doing any damage is to restart your machine, boot into Windows, disable FastBoot if necessary and properly shut it down. Boot Ubuntu up and mount the drive.
Finished!