text:
Q: "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" in Swift. (for boolean value) I looked at other questions but could not solve my problem.
Also, this code line crash in firebase crashlytics.
How can I fix? Thanks.
if AUserDefaults.read(key: UDKeys.local_token.rawValue) != nil {
    if !BTSingleton.sharedInstance.isContractVersionCheckRequired {
        getMyShipments()
    }
}

Error screenshot

A: Just need to make sure you have a bool before you read it. I would write it like this because I feel its cleaner:
// this approach compares the optional to false so if it is tru or nil it doesn't get executed
    if BTSingleton.sharedInstance.isContractVersionCheckRequired == false {
                getMyShipments()
            }

But you could write it like this it may be easier to understand:
// this approach safely unwraps the optional and then checks the value
    if let versionCheckRequired = BTSingleton.sharedInstance.isContractVersionCheckRequired, versionCheckRequired == false {
        getMyShipments()
    }


text:
Q: Can I make Starcraft 2 portable? If I were to install Starcraft 2 in a external hard drive (changing the install folder during installation), could I run it on another computer without installing? For example, if I installed starcraft 2 on a usb, and then plugged the usb into ANOTHER computer, would it run properly? I'm fine with just offline single player mode.
Thanks

A: I'm inclined to say it is (having played both Starcraft II and Diablo III off of an external hard drive in the past), but... do you have a large enough USB drive?
My Starcraft II folder is currently sitting at 13.5 gigs. If you can get all of that onto the flash drive, you should be good to go.

A: In one of the past Intel Extreme Masters tournaments, each player was given an SSD so that they could fully customize everything (settings, OS, etc.  For every match, they would just pop that SSD into which ever computer they needed to play on.  You could do the same but with an external SSD like @AtlasEU suggested.

A: If I recall correctly, Starcraft 2 should run just fine if you just copy its folder.

A: Yes you can. Just copy the folder and it will run fine. Just be aware the configuration file which contains audio / graphics will remain the ones you had when installed.

A: It works fine if you just copy the folder, but you can't update.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Vector Ruggedness Measure (VRM) tool from ArcScripts at latest version of ArcGIS for Desktop? I need to use the Vector ruggedness measure (VRM) tool available from http://arcscripts.esri.com/details.asp?dbid=15423. However, I am using ArcGIS 10.2 for Desktop and these tools are made for 9.0, 9.1 and 9.3 only. I have tried to run this tool regardless and get the error:

Traceback (most recent call last):   File
  "C:\Users\jc221340\Documents\project\Processed
  data\My_tools\Downloaded\ruggedness.py", line 20, in
      gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
  RuntimeError: Object: Toolbox C:/Program
  Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx does not
  exist
Failed to execute (Ruggedness(VRM)).

How can I use this tool?

A: Since you are using v10.2 it is looking for the path of the Spatial Analyst toolbox which has changed directory locations slightly from v9:
To update, open the ruggedness.py file using Notepad or some other text editor and change line 20 path to something like this:
C:\Program Files (x86)\ArcGIS\Desktop10.2\ArcToolbox\Toolboxes\Spatial Analyst Tools.tbx

A: I also met problem when executing VRM on ArcGIS 10.1. The answer above was helpful but not enough. The VRM tool generated aspect, slope, x, y, z...etc files, and then showed the completion of process. The following methods such as generation of ruggedness layer and deletion of intermediate files were skipped and ignored.
The problem was solved by using "Benthic Terrain Modeler" instead to calculate VRM.

A: I had the same problem. I emailed the tool's creator, Mark Sappington, he has updated this tool for newer versions of ArcGIS and the new Python script and ArcGIS toolbox can be downloaded here: http://www.arcgis.com/home/item.html?id=9e4210b3ee7b413bbb1f98fb9c5b22d4
This has worked with my version 10.2.
Good luck!

A: You can easily replicate this metric using raster algebra. This example is written in in raster algebra pseudo code and should be easy to adapt to any GIS software supporting raster analysis.
Calculate slope and aspect using a constant to convert to radians
slope = slope(dem, units = degrees) * 0.0175
aspect = aspect(dem) * 0.0175

Apply cosine and sine function. For aspect, commonly GIS software assigns a -1 to flat areas. Because of this, you may need to use a con statement to deal with converting negative values to zero.
sin.slp = cos(slope)
cos.slp = sin(slope)

sin.asp = con(aspect == -1, 0, sin(aspect) * sin.asp)
cos.asp <- con(aspect == -1, 0, cos(aspect) * sin.asp)

Apply focal sum function for the desired scale (focal neighborhood)
scale = 5
x.sum = focal(sin.asp, window = scale, function = sum)
y.sum = focal(cos.asp, window = scale, function = sum)
z.sum = focal(cos.slp, window = scale, function = sum)

The Vector Ruggedness Measure (VRM) is 1 - the square root of the squared sums of the focal rasters divided by the squared scale.
vrm = 1 - ( sqrt( sqr(x.sum) + sqr(y.sum) + sqr(z.sum)) / sqr(scale) )


text:
Q: Can we use .Net Native as an alternative for developing Universal C# Application? We are developing cross platform applications using C# and Xamarin. We are more interested to use a complete Microsoft based solution for developing our Universal Applications. Can .Net Native be that solution?
Thanks, Ravi

A: You've got a few things confused here.
.Net Native is about producing a file that is natively executable on the target real machine - an Intel CPU, for instance. All of the bits that make up the .Net VM in that executable file are packed into it and natively compiled.
However, all that gets you is the ability to run native machine code.
Second is how to interface with the operating system and userland environment of the machine you're running on. At the bottom something has to implement, say, the Socket class. On Windows, the Microsoft .Net framework uses Win32 to implement the Socket class. On Linux/Mac/*BSD, the .Net framework implemented in Mono etc use the posix socket API provided by the operating system.
How do you draw to the screen in Windows? GDI, GDI+, Direct2d, etc.
How do you draw to the screen in Linux/? X Windows. In OS X? Quartz. No amount of .Net compiler magic is going to automatically make that work for you.
.Net Native makes it so that you can have statically linked executables. But you still need an implementation of the .Net framework for the platform that you're running on. This is where Mono, Xamarin, etc, step in.


text:
Q: IOS/Objective-C: Autolayout constraints interfere with reusing tableviewcell I have a tableview with a custom cell containing images that vary by item.  Some items have images.  For items without images, rather than use a placeholder I would like to shrink the cell and have no images at all.
Before I introduced autolayout and using a placeholder image, the images loaded properly.  However, since I have introduced autolayout and used autolayout to shrink cells that lack an image, I have run into problems with images appearing in rows where they don't belong.  I think this is because dequeuing is not working
Has anyone encountered this before?  Happy to share more code but it is just boilerplate.  The problem arises when I add the autolayout constraints.
To accomplish self-sizing I have placed
_tableView.estimatedRowHeight = 400;
_tableView.rowHeight = UITableViewAutomaticDimension;

at bottom of viewdidload.
My cellforrowatindexpath is as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     NSString *CellIdentifier = @"Cell";
    IDFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    Feed* feed = [self.fetchedResultsController objectAtIndexPath:indexPath];
    if (!cell) {
        cell = [[IDFeedCell alloc] initWithStyle:UITableViewCellStyleDefault
                                        reuseIdentifier:@"Cell"];
    }
if (self.feed.picname.length>=1) {
cell.messageImage.image = [self loadImageNamed:itempicname];
}
else {
cell.messageImage.image = nil;
}
        return cell;
}


text:
Q: What is the best PySpark practice to load config from external file I would like to initialize config once, and then use it in many modules of my PySpark project.
I see 2 ways to do it.

*

*load it in entry point and pass as an argument to each function

main.py:
with open(sys.argv[1]) as f:
    config = json.load(f)
df = load_df(config)
df = parse(df, config)
df = validate(df, config, strict=True)
dump(df, config)

But it seems unbeauty to pass one external argument to each function.

*Load config in config.py and import this object in each module

config.py
import sys
import json
with open(sys.argv[1]) as f:
    config = json.load(f)

main.py
from config import config
df = load_df()
df = parse(df)
df = validate(df, strict=True)
dump(df)

and in each module add row
from config import config

It seems more beauty because config is not, strictly speaking, an argument of function. It is general context where they execute.
Unfortunately, PySpark pickle config.py and tries to execute it on server, but doesn't pass sys.argv to them!
So, I see error when run it
  File "/PycharmProjects/spark_test/config.py", line 6, in <module>
    CONFIG_PATH = sys.argv[1]
IndexError: list index out of range

What is the best practice to work with general config, loaded from file, in PySpark?

A: Your program starts execution on master and passes main bulk of its work to executors by invoking some functions on them. The executors are different processes that are typically run on different physical machines.
Thus anything that the master would want to reference on executors needs to be either a standard library function (to which the executors have access) or a pickelable object that can be sent over.
You typically don't want to load and parse any external resources on the executors, since you would always have to copy them over and make sure you load them properly... Passing a pickelable object as an argument of the function (e.g. for a UDF) works much better, since there is only one place in your code where you need to load it.
I would suggest creating a config.py file and add it as an argument to your spark-submit command:
spark-submit --py-files /path/to/config.py main_program.py

Then you can create spark context like this:
spark_context = SparkContext(pyFiles=['/path/to/config.py'])

and simply use import config wherever you need.
You can even include whole python packages in a tree packaged as a single zip file instead of just a single config.py file, but then be sure to include __init__.py in every folder that needs to be referenced as python module.


text:
Q: How 'vadd' + 1 works in case of iterating over String to print every char i'am learning about assembly code. There is a snippet of program converted to byte code. Simply its printing out HelloWorld to the screen. Thing i do not understand is shifting to next char in loop. Why we add 1 to data from register (r4) to shift to the next char? How it`s done?
    data: db "Hello World", 0xa, 0
    vset r4, data
    vxor r0, r0
    vset r1, 1
    print_loop:
      vldb r2, r4
      vcmp r2, r0
      vjz .end
      voutb 0x20, r2
      vadd r4, r1
      vjmp print_loop
    .end:


text:
Q: Cannot extract names of subnodes under a node I have a XML file like this:
<book>
    <chapter name="chap1">

            <paragraph name="title1">sample</paragraph>

            <paragraph name="title2">sample1</paragraph>

    </chapter>
    <chapter name="chap2">

            <paragraph name="title3">sample2</paragraph>

    </chapter>
    <chapter name="chap3">

            <paragraph name="title4">sample3</paragraph>

    </chapter>
</book>

I want to extract the sections from specific chapters. Suppose from "chap1", the output should be like this:
c1sec1
c1sec2

I have written the following piece of code to achieve this:
NodeList nodeList = doc.getElementsByTagName("chapter");
for (int i = 0; i < nodeList.getLength(); i++) {
    Node n = nodeList.item(i);
    NamedNodeMap m = n.getAttributes();
    if(m.getNamedItem("name").getTextContent() == "chap1")
    {
        System.out.println(n.getFirstChild().getNodeValue());
    }
}

Where am I going wrong?

A: The root cause of your problem is using == to compare strings instead of equals

A: I would suggest using the simpler getAttribute() method:
NodeList nodeList = doc.getElementsByTagName("chapter");
for (int i = 0; i < nodeList.getLength(); i++) {
    Element el = (Element)nodeList.item(i);
    if (el.getAttribute("name").equals("chap1"))
    {
        System.out.println("Found chap1");
    }
}

You'll then need similar code to extract the section names from the chapter.

A: Try m.getNamedItem("name").getNodeValue() instead of m.getNamedItem("name").getTextContent()


text:
Q: How to use Reachability Objective-C class in Swift I need to get notified when connectivity changes during app usage. I have imported Reachability.h .m files to my Swift project, and bridged it by adding #include "Reachability.h".
In Apple's Reachability example project an observer is set up to get notified when connectivity changes. How can I set it up in Swift?
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

There is no equivalent observer in Swift. Swift has property observers like willSet and didSet.

A: Please referred following link for Reachability in swift https://github.com/ashleymills/Reachability.swift
For your add observer please use it like this
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)


text:
Q: MS SQL 2008 - update record with a value if the grouped total meets a condition I am trying to figure out how to update record with a value only in case that the grouped total of a particular type of transactions type is over zero.
In other words, I group my transactions by payment type. If the grouped payment type total is greater than zero, I would like to update each of the transaction in the group with a value.
I cannot figure out that correct statement. Could anyone help please?
UPDATE
    T
SET
    T.col1 = OT.col1,
    T.col2 = OT.col2
FROM
    Some_Table T
INNER JOIN
    Other_Table OT ON T.id = OT.id
WHERE
    T.col3 = 'xyz'
-- GROUP BY T.col1
-- HAVING SUM(amount) > 0

A: You can use a CTE together with a SUM() OVER():
;WITH ToUpdate AS (
   SELECT T.col1 AS tcol1, OT.col1 AS otcol1, T.col2 AS tcol2, OT.col2 AS otcol2,
          SUM(amount) OVER (PARTITION BY T.col1) AS sumAmount
   FROM Some_Table T
   INNER JOIN Other_Table OT ON T.id = OT.id
)
UPDATE ToUpdate
SET
    tcol1 = otcol1,
    tcol2 = otcol2
WHERE sumAmount > 0

The above query will update every row of Some_Table that belongs to a col1 partition with SUM(amount) > 0.


text:
Q: pass field value to a function .extra() After trying for hours, I am coming here. I have the following model:
class Items(models.Model):
     date=models.DateField()
     giver=models.IntegerField()

Class Givers(models.Model):
     name=models.CharField(max_length=25)

Basically, an item could be given by donators from Givers model or it could be bought by user. If given, giver field stores id from Givers model. Else, it is 0. Now I want a query that will list out my items. If giver>0, I need to show the name of the giver. I can't create relationships here. This query has brought me so close and works like a charm on literal values but I want to provide the 'giver' field instead:
   data=Items.objects.all().extra(select={'giver_name':giver_name(1,False)}).values('giver_name','id','date')

It works like a charm even if given any number (exists or not exists). But I want to do something like this but it fails cos field is not found or undefined:
   data=Items.objects.all().extra(select={'giver_name':giver_name(giver,False)}).values('giver_name','id','date')

giver_name is a function that accepts id of a giver and a boolean value and returns a name.


text:
Q: Using get_post_type with a custom URL format? I have a custom post type with rewritten URLs.
Slug is: top-news
Rewrite is: top/news
I have a function that updates the last modified date whenever a comment is posted that works correctly (found here), however I want this to apply only to this custom post type.
I tried wrapping the function in:
if ( is_singular( 'top-news' ) ) {
}

and also with:
if( get_post_type() == 'top-news' ) {
}

However these don't seem to work, any help would be greatly appreciated.

A: If you're doing something in the wp_insert_comment hook, then you should use the 2nd argument, $comment_object, if you want to know anything about the post the comment was for. $comment_object is a WP_Comment object that has a $comment_post_ID property that has the ID of the post the comments is for. You can use that to determine its post type. The URL structure is completely irrelevant.
function wpse_304105_update_time( $comment_id, $comment_object ) {
    $post_id = $comment_object->comment_post_ID;

    if ( get_post_type( $post_id ) === 'top-news' ) {
        // Update post time.
    }
}
add_action( 'wp_insert_comment', 'wpse_304105_update_time', 99, 2 );


text:
Q: Scrollable label using PyQt5 for Python gui How to make scrollable label in Pyqt5 for Python gui?
I have label that display retrieved text from a file, and it sometimes has several lines , I need this text to be shown in a fixed label area with vertical scroll bar

A: A possible solution is to use a QScrollArea with a QLabel, we set the WordWrap property to True to have several lines:
class ScrollLabel(QScrollArea):
    def __init__(self, *args, **kwargs):
        QScrollArea.__init__(self,*args, **kwargs)
        self.setWidgetResizable(True)
        content = QWidget(self)
        self.setWidget(content)
        lay = QVBoxLayout(content)
        self.label = QLabel(content)
        self.label.setAlignment(Qt.AlignLeft|Qt.AlignTop)
        self.label.setWordWrap(True)
        lay.addWidget(self.label)

    def setText(self, text):
        self.label.setText(text)

Example:
text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
"""
if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    w = ScrollLabel()
    w.setText(text)
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())

Output:

Another option is to use QPlainTextEdit:
text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
"""

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    w = QPlainTextEdit()
    w.setReadOnly(True)
    pal = w.viewport().palette()
    pal.setColor(QPalette.Base, pal.color(QPalette.Background))
    w.viewport().setPalette(pal)
    w.appendPlainText(text)
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())

Or QTextEdit:
text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
"""

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    w = QTextEdit()
    w.setReadOnly(True)
    pal = w.viewport().palette()
    pal.setColor(QPalette.Base, pal.color(QPalette.Background))
    w.viewport().setPalette(pal)
    w.append(text)
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())


text:
Q: How can one achieve an arbitrary frequency and duty cycle PWM-ed IR transmission in an xBee3 using MicroPython? I am researching a way to send out a PWM-ed IR pulse from an xBee3 device. I couldn't find any IR related libs, so I guess I'll have to "brute" force it by "waiting" X many microseconds and setting digital I/O pins ON and OFF.
Any ideas/pointers/references would be much appreciated!

A: MicroPython on the XBee3 RF products won't be capable of the microsecond timing you're looking for, and the PWM output only allows for setting the duty cycle, not the frequency.
You would need to add extra hardware to convert (for example) the I2C interface to IR transmission.  The XBee3 RF products don't support a secondary UART like the XBee Cellular products do, but if they add that feature you would could have a UART->IR interface via a secondary microprocessor.


text:
Q: OpenGL projects crashing Screenshot
This code compiles without errors or warning, but it can't run it, application crashing instantly.
#include <GL/glut.h>

int WinWidth  = 640,
 WinHeight = 480;
int WinFar   = 10;

void DrawPoint(float x, float y)
{
 glColor3f(1.0, 1.0, 1.0);
 glBegin(GL_POINTS);
  glVertex2f(x, y);
 glEnd();
}

void display()
{
 glClear(GL_COLOR_BUFFER_BIT);
 //Draws
 DrawPoint(0, 0);
 //
 glFlush();
}

int main(int argc, char** argv)
{
 glutInit(&argc, argv);
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
 glutInitWindowSize(WinWidth, WinHeight);
 glutInitWindowPosition(150, 150);
 glutCreateWindow("Lesson 01");
 glClearColor(0, 0, 0, 1.0);

 glOrtho(-WinWidth/2, WinWidth/2, WinHeight/2, -WinHeight/2, -WinFar/2, WinFar/2);
 glutDisplayFunc(display);

 glutMainLoop();
 return 0;
}

It's crashing with return value 3221225477. What I'm doing wrong?

Program received signal SIGEGV, Segmentation fault
when I run it in debug mode


text:
Q: Cruise Control .net Changing Log File appereance i would like to change the apperance of the log file, generated by ccnet. It is useful, if the error messages are separated from the original Log Messages, but in order to debug, it is a bit tricky to see, when the error really happened. Our powershell skript runs for 6-8 hours and creates about 38k lines in the log file, so i would really apprechiate a solution, how i could list the errors with the other lines in the log files. Additionally it would be cool, if all the errors would still appear separatedly.
So far i have not found a lot documentary that explained how to change the log file output...
Simon

A: Not sure how this is logged, but in the end, logs produced during the build are put into the build-log file, that you will find in artifacts folder.
Then this logs are transposed into html output using xsl transforms. If none of the built-in reports is useful to you, you can create a custom xsl and plug it in, see the dashboard.config file, the following section allows for adding additional xsl transforms:
<buildReportBuildPlugin>
      <xslReportBuildPlugin description="MSBuild Log" actionName="MSBuildBuildReport" xslFileName="xsl\MSBuild4Log.xsl"/>
...

A: If you know what the error messages are going to be you can parse them with an xsl file and generate some html that will show up in the build emails. The following goes in ccservice.exe.config.
    <xslFiles>
        <file name="c:\path\to\custom_errors.xsl"/>
    </xslFiles>

custom_errors.xsl is an xsl file that finds the error messages in the raw build log xml and then generates html from them. This html will show up in the build emails. You have to create custom_errors.xsl. It's a significant amount of work to get working the first time especially if you're new to xml/xsl/html/css. If you undertake this I suggest doing all the testing outside of ccnet using a xsl transformer and inputting a sample ccnet build log. ccnet uses a css file to style the html so be aware of that. You can edit this too.
Note you have to restart the ccnet service after editing ccservice.exe.config.


text:
Q: JSON.parse issue with redux state Using React and Redux, I'm making the call getNoteById which returns some string inside of note.
I want to JSON.parse the note variable but if it's undefined then setValue to initialValue where I know it will parse properly.
The issue I'm having is when I check to see if JSON.parse(note) is undefined or not, I always get the same error of undefined index at 0.
Not sure how to fix this. When the component loads and getNotesById() is called, notes or initialValue should be displayed when i call setValue.
const TextEditor = ({ note, getNoteById, clearValues }) => {
  const paramId = match.params.notes;
  const [value, setValue] = useState();

  useEffect(() => {
    getNoteById(paramId);

    if (JSON.parse(note) == undefined) {
      setValue(initialValue);
    } else {
      setValue(JSON.parse(note));
    }

    return () => {
      clearValues();
    };
  }, [paramId, value]);

  return (

 {value}

  );
};

A: Your effect has missing dependencies: clearValues, getNoteById and note. You should skip the setValue to initialValue and do const [value, setValue] = useState(initialValue); because an effect runs after the render and note will be undefined on first render. Check if note is undefined with if(note!==undefined){setValue(JSON.parse(note))}.
Your code should look something like this:
const TextEditor = ({ note, getNoteById, clearValues }) => {
  const paramId = match.params.notes;
  const [value, setValue] = useState(initialValue);

  useEffect(() => {
    getNoteById(paramId);

    if(note!==undefined) {
      setValue(JSON.parse(note));
    }

    return () => {
      clearValues();
    };
  }, [clearValues, getNoteById, note, paramId, value]);

  return (

 {value}

  );
};

My guess is that you don't want to dispatch getNoteById again when the note is loaded and set in the redux state. Maybe create 2 effects:
const TextEditor = ({ note, getNoteById, clearValues }) => {
  const paramId = match.params.notes;
  const [value, setValue] = useState(initialValue);
  //dispatch getNoteById when param id changes
  useEffect(() => {
    getNoteById(paramId);
    return () => {
      //dispatch a cleanup action
      clearValues();
    };
  }, [clearValues, getNoteById, paramId]);
  //set the note to it's parsed json when it changes
  //  and is not undefined
  useEffect(() => {
    if (note !== undefined) {
      setValue(JSON.parse(note));
    }
  }, [note]);
  return (

 {value}

  );
};


text:
Q: How to use org.eclipse.jetty.server.Request in a webapp? In my ServletFilter, I want to use specific jetty API exposed in the HttpServletRequest implementation.
I launched it like that:
final Request jettyRequest = Request.getBaseRequest(request)

If I want to avoid ClassNotFoundException, I must add the jetty-server artifact to my maven dependencies. But if I do that, getBaseRequest returns null because 'request instanceof Request' returns false instead of true.
This is certainly due to conflict between jetty and application classloaders because both of them have loaded 'org.eclipse.jetty.server.Request' class. I tried several configurations, but I was not able to make the Request class exposed to my webapp without adding the dependency in WEB-INF/lib, which causes the classpath issue.
My application is launched with "mvn jetty:run-forked" and configured like this:
    <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>${jetty-version}</version>
        <configuration>
            <webAppSourceDirectory>${project.build.directory}/${project.name}</webAppSourceDirectory>
            <systemProperties>
                <force>true</force>
            </systemProperties>
            <scanIntervalSeconds>10</scanIntervalSeconds>
            <webAppConfig>
                <contextPath>/</contextPath>
            </webAppConfig>
            <jettyXml>../jetty.xml,../jetty-ssl.xml,../jetty-https.xml</jettyXml>
            <jvmArgs>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn-version}/alpn-boot-${alpn-version}.jar</jvmArgs>
        </configuration>
    </plugin>

Any help will be appreciated!

A: I fixed the issue by adding a WebAppContext configuration file that contains:
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <Set name="parentLoaderPriority">true</Set>
</Configure>

The file must be referenced in jetty-maven-plugin like that:
<contextXml>../jetty-context.xml</contextXml>


text:
Q: Better approach to do this How we can approach this function in a better way
or
How can we make it more efficient
or
Optimize the code :
def is_interesting(tt):
    return tt['target_type'] == 670 and tt.get('script') is not None and tt.get('script') in ('abc','syz','mno')

A: The tt.get('script') is not None part is redundant, because None is not in the next tuple either.
Your test is otherwise plenty efficient; Python will not evaluate the second expression if the first is False already.
def is_interesting(tt):
    return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno')

Demo:
>>> def is_interesting(tt):
...     return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno')
...
>>> is_interesting({'target_type': 42})
False
>>> is_interesting({'target_type': 670})
False
>>> is_interesting({'target_type': 670, 'script': ''})
False
>>> is_interesting({'target_type': 670, 'script': 'abc'})
True

A: My answer is exactly same as Martijin.
def is_interesting(tt):
    return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno')

I just want to answer this:

" return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno') TypeError: 'in ' requires string as left operand " Hence I added this statement to cope up with empty value of tt.get('script')

Example:
>>> {'foo':'bar'}.get('notexist') in ('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not NoneType

>>> {'foo':'bar'}.get('notexist') in ('foo',)
False

>>> {'foo':'bar'}.get('notexist') in ['foo']
False

Explanation: the first example, there's only one element in the (), so ('foo') actually returns you 'foo' -- a string; the 2nd and 3rd can ensure you get a tuple/list. Put a comma after the single element inside parentheses is the way to get a way with one element. I guess this's what you encountered.


text:
Q: how to swap two max elements in the same array? I was thinking of how can i swap this two elements from an given array,for example if i find two maximums in one array and i want to swap them how can i do that without using another array ?
#include <stdio.h>

int main()
{
int n,i;
int arr[100];

scanf("%d",&n);
for(i = 0;i < n;i++){
    scanf("%d",&arr[i]);
}

//1 2 3 4 5

for example this array should be 1 2 3 5 4

int max1 = arr[0],max2 = arr[0];
for(i = 0;i < n;i++){
    if(max1 < arr[i]){
        max2 = max1;
        max1 = arr[i];

    }
    else if(max2 < arr[i]){
        max2 = arr[i];
    }

}
printf("%d %d",max1,max2);
return 0;
}

A: Instead of defining max1 and max2 as array values define them as indices. For example
int max1 = 0, max2 = 0;
for ( i = 1;i < n; i++ ){
    if( arr[max1] < arr[i] ){
        max2 = max1;
        max1 = i;

    }
    else if( arr[max2] < arr[i]){
        max2 = i;
    }
}

if ( max1 != max2 && arr[max1] != arr[max2] )
{
    int tmp = arr[max1];
    arr[max1] = arr[max2];
    arr[max2] = tmp;
}

printf("%d %d",arr[max1],arr[max2]);

Or you may swap the elements unconditionally.
int tmp = arr[max1];
arr[max1] = arr[max2];
arr[max2] = tmp;


text:
Q: emacs CUA-mode OK in X but not working console I have been struggling to get emacs CUA-mode working in the console where it works fine in X (in an xterm using emacs -nw).
The main features I want are shift-movement selection and ^C,^V,^X but any more would be helpful.  So far I am using a local keyboard and monitor but ultimate goal is to get all this working over ssh using something like putty.
So far I have been working on getting my terminal to output the same control sequences that emacs expects to see for shift-movement (specifically S-<down> or <S-down>) and this works in the console when shift-select-mode is set in .emacs.  So far so good, so I can shift select text from any emacs invocation type: X-windows, terminal ($TERM=linux or $TERM=xterm).  This site has been very useful.
Shift-<down> displays as follows using cat -v and emacs happily maps <S-down> to this control sequence.
cat -v            (then type shift-down)
^[O2B

Here's the problem, switch on cua-mode and the shift-selection stops working but ^C,^V and ^X starts working !?  So I can either have shift-selection or ^C,^V,^X but not both at the same time.
-------
Setup:
emacs 23
Raspberry Pi
Raspian (similar to Debian)

A: You might like to try a more recent version of Emacs, since cua-mode has been slowly changed to use the same code as shift-select-mode.  In Emacs-24.4, cua-mode actually uses shift-select-mode directly.


text:
Q: Keys defined in dev.env.js are not accessible with webpack in vuejs The template is based on vuejs-webpack, and the build, config files are here, I have not modified any of these files.
Based on Environment Variables the keys defined in dev.env.js file must be accessible when running npm run dev in the app.
This is the content of my dev.env.js:
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  SAMPLE: '"XX"',
  AUTH_URL: '"http://localhost:3030"'
})

And when I try to access AUTH_URL in App.vue like this process.env.AUTH_URL, I receive undefined.
It seems to me whatever is defined in dev.env.js file will never become accessible when running npm run dev

A: Use the webpack.DefinePlugin to define the variables you wish to share with your front end. Webpack its self does not expose process to the browser as this is a node js function.
const dev_env = require('dev.env.js)

plugins: [
  new webpack.DefinePlugin({
    'process.env' : {
      NODE_ENV: JSON.stringify(dev_env.NODE_ENV)
    }
  })
]

Some variation of the above should work for you.

A: If your run "npm run dev", then your new environment variable is only available after a restart of npm (Ctrl + C and again 'npm run dev').


text:
Q: How to read parquet files from Azure Blobs into Pandas DataFrame? I need to read .parquet files into a Pandas DataFrame in Python on my local machine without downloading the files. The parquet files are stored on Azure blobs with hierarchical directory structure.
I am doing something like following and I am not sure how to proceed :
from azure.storage.blob import BlobServiceClient
blob_service_client = BlobServiceClient.from_connection_string(connection_string)

blob_client = blob_service_client.get_blob_client(container="abc", blob="/xyz/pqr/folder_with_parquet_files")

I have used dummy names here for privacy concerns. Assuming the directory "folder_with_parquet_files" contains 'n' no. of parquet files, how can I read them into a single Pandas DataFrame?

A: Hi you could use pandas and read parquet from stream. It colud be very helpful for small data set, sprak session is not required here. It could be the fastest way especially for testing purposes.
import pandas as pd
from io import BytesIO
from azure.storage.blob import ContainerClient

path = '/path_to_blob/..'
conn_string = <conn_string>
blob_name = f'{path}.parquet'

container = ContainerClient.from_connection_string(conn_str=conn_string, container_name=<name_of_container>)

blob_client = container.get_blob_client(blob=blob_name)
stream_downloader = blob_client.download_blob()
stream = BytesIO()
stream_downloader.readinto(stream)
processed_df = pd.read_parquet(stream, engine='pyarrow')

A: Here is a very similar solution, but slightly different using the new method azure.storage.blob._download.StorageStreamDownloader.readall:
from io import BytesIO
from azure.storage.blob import BlobServiceClient

blob_service_client = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service_client.get_container_client(container="parquet")

downloaded_blob = container_client.download_blob(upload_name)
bytes_io = BytesIO(downloaded_blob.readall())
df = pd.read_parquet(bytes_io)

print(df.head())

A: get_blob_to_bytes method can be used
Here the file is fetched from blob storage and held in memory. Pandas can then read this byte array as parquet format.
from azure.storage.blob import BlockBlobService
import pandas as pd
from io import BytesIO

#Source account and key
source_account_name = 'testdata'
source_account_key ='****************'

SOURCE_CONTAINER = 'my-data'
eachFile = 'test/2021/oct/myfile.parq'

source_block_blob_service = BlockBlobService(account_name=source_account_name, account_key=source_account_key)

f = source_block_blob_service.get_blob_to_bytes(SOURCE_CONTAINER, eachFile)
df = pd.read_parquet(BytesIO(f.content))
print(df.shape)


text:
Q: "Toggle" query in MongoDB
Possible Duplicate:
In MongoDB, How to toggle a boolean field in one document with atomic operation?

I need to update a document value, "toggling" it:
The collection is "Comment" which has boolean flag "isAdmin".
I'm going to update a given comment id, setting isAdmin false if it's true and viceversa.
However this does not work:
db.comments.update( { "id": "xxx" }, { $set: { isAdmin: $not isAdmin } } );

What's the right syntax?

A: You can't reference the document you find in an update like that. You'll need to do a query to find the document, and then do an update after you know what the value is. Two step process:
var doc = db.comments.findOne({id:"xxx"});
db.comments.update({id:"xxx"}, {$set: {isAdmin: !doc.isAdmin}});

Update:
This answer has been out of date for a while (since 2.5.2):
https://jira.mongodb.org/browse/SERVER-4362
It is now possible via the $bit operator xor, and using findOneAndUpdate to avoid two separate commands.


text:
Q: Show error around radio buttons The Jquery Validation plugin docs say you can validate that at least one radio button is selected.  However, when trying to do so with some extra layout, I am not getting the error highlighting.

My code looks like this.

    Please select a recovery method

                    <input id="factorSelect_email" name="factorSelect" type="radio" value="EMAIL" />Send me an email

                    <input id="factorSelect_sms" name="factorSelect" type="radio" value="SMS" />Send an SMS to my phone

$("#forgotPasswordForm").validate({
    rules: {
        fpUsername: {
            required: true,
            minlength: 3
        },
        factorSelect: {
            required: true
        }
    },
    messages: {
        fpUsername: {
            required: "Please enter your username or email",
            minlength: "Your username must be at least {0} characters"
        },
        factorSelect: {
            required: "You must select a recovery method"
        },
    },
    highlight: function (element, errorClass, validClass) {
        $(element).parents(".form-group").addClass("has-error").removeClass("has-success");
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).parents(".form-group").addClass("has-success").removeClass("has-error");
    },
});

The has-error class never gets applied to the radio button group.

A: I reproduced the error you have in this CodePen...
The error message produced by jQuery Validate is positionned right after the invalid element... Which is the default.
Now you can position that error message elsewhere, using errorPlacement.
In this Solution, I just placed it right after the parent .input-group. I'm sure that is the puzzle piece you where looking for.
;)
errorPlacement: function(errorLabel, invalidElement){
  if( $(invalidElement).is("[type='radio']") ){
    var inputGroup = $(invalidElement).closest(".input-group");
    inputGroup.after(errorLabel);
  }
},

EDIT
With your full code, that is easier to work...
;)
The default behavior of a button in a form is to submit (Reference, see "type").
So if the type is omitted, that is what it does.
And the .validate() function isn't triggered by a button type="button".
So...
You have to prevent the default submit in order to validate first.
Then, submit if the form is valid.
This is achieved by .preventDault() and submitHandler
$("#forgotPasswordForm").on("submit",function(e){
  e.preventDefault(); // Prevents the default form submit (Have to validate first!)
})
  .validate({

    // Skipping some lines here...

    submitHandler: function(form) {
    form.submit();  // Submits only if the form is valid
  }
});

Updated CodePen

A: Ok, fixed it.  Thank you for the help above with the placement of the error message.  That was not my initial issue but did come up once I got the error to display at all.  Your fix works great.
My primary issue turned out to be a CSS conflict with some styles that turn the radio buttons into pretty font-awesome icons.  The little snippet that hides the default radio buttons causes the validation to fail as it must only look for visible fields.  I set the height to zero instead and so far it seems to work.
.checkbox label input[type="checkbox"],
.radio label input[type="radio"] {
    /*display: none;*/
    height:0;
}


text:
Q: Apache Spark cannot start due to a NoSuchMethodError I have brew installed apache-spark 1.6.1 on OSX El Capitan. Upon spark-shell, I receive:
Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.spi.LocationAwareLogger.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/Object;Ljava/lang/Throwable;)V
    at org.apache.commons.logging.impl.SLF4JLocationAwareLog.debug(SLF4JLocationAwareLog.java:133)
    at org.apache.hadoop.metrics2.lib.MutableMetricsFactory.newForField(MutableMetricsFactory.java:42)
    at org.apache.hadoop.metrics2.lib.MetricsSourceBuilder.add(MetricsSourceBuilder.java:133)
    at org.apache.hadoop.metrics2.lib.MetricsSourceBuilder.<init>(MetricsSourceBuilder.java:59)
    at org.apache.hadoop.metrics2.lib.MetricsAnnotations.newSourceBuilder(MetricsAnnotations.java:42)
    at org.apache.hadoop.metrics2.impl.MetricsSystemImpl.register(MetricsSystemImpl.java:223)
    at org.apache.hadoop.metrics2.MetricsSystem.register(MetricsSystem.java:60)
    at org.apache.hadoop.security.UserGroupInformation$UgiMetrics.create(UserGroupInformation.java:108)
    at org.apache.hadoop.security.UserGroupInformation.<clinit>(UserGroupInformation.java:224)
    at org.apache.spark.util.Utils$$anonfun$getCurrentUserName$1.apply(Utils.scala:2160)
    at org.apache.spark.util.Utils$$anonfun$getCurrentUserName$1.apply(Utils.scala:2160)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.util.Utils$.getCurrentUserName(Utils.scala:2160)
    at org.apache.spark.SecurityManager.<init>(SecurityManager.scala:214)
    at org.apache.spark.repl.SparkIMain.<init>(SparkIMain.scala:118)
    at org.apache.spark.repl.SparkILoop$SparkILoopInterpreter.<init>(SparkILoop.scala:187)
    at org.apache.spark.repl.SparkILoop.createInterpreter(SparkILoop.scala:217)
    at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply$mcZ$sp(SparkILoop.scala:949)
    at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
    at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
    at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
    at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$process(SparkILoop.scala:945)
    at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:1059)
    at org.apache.spark.repl.Main$.main(Main.scala:31)
    at org.apache.spark.repl.Main.main(Main.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:731)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
14:17:50.398 [Thread-0] INFO  o.a.spark.util.ShutdownHookManager - Shutdown hook called
14:17:50.401 [Thread-0] INFO  o.a.spark.util.ShutdownHookManager - Deleting directory /private/var/folders/pc/wx3xk3sx7_35n6v1qj9knv9c0000gq/T/spark-0a979df4-f61f-4805-a942-8e62350331db

I installed Jave SE already, and I suspect this same problem is preventing my pyspark (with a similar error).


text:
Q: text() not showing/rendered on iOS jQuery Currently, I am making scanning function in my website. And there is different time between last scan time and current time.
My script work normally in desktop browser and android browser, but it not showing same in iOS
Here is my code.
Example output in desktop and android devices

1 Hr 2 mins 1 sec ago

Example output in iOS ( chrome, Firefox and safari give same output )

ago

Only ago text show in iOS. anyone know what's wrong with my code?

d = 74;
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var hDisplay = h > 0 ? h + (h == 1 ? " hr" : " hrs") + (m > 0 || s > 0 ? ", " : "") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " min" : " mins") + (s > 0 ? ", " : "") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " sec" : " secs") : "";

differentTime = "last scan " + hDisplay + mDisplay + sDisplay + " ago "

console.log(differentTime)
$("#last-scan").text(differentTime);

 by Scanner_19022


text:
Q: is anyone solved animation error in javascript Error in my code is, I add condition to run a JavaScript function only one time but when I add if else logic web page can open all sections
here is my code logic:

let count = 0;
window.addEventListener('scroll', fade);
function fade()
{
  if (count < 1)
  {
    let animation=document.querySelectorAll('.fade');
    for (let i=0; i<animation.length; i++)
    {
      let windowheight=window.innerHeight;
      let top=animation[i].getBoundingClientRect().top;
      if (top < windowheight)
      {
      animation[i].classList.add('visible');
      }
      else
      {
      animation[i].classList.remove('visible');
      }
    }
  }
  else
  {
    return ;
  }
  count++;
}

A: Since you only need to handle the event once,
window.addEventListener('scroll', fade, {once: true});
You can safely remove count variable and if...else.


text:
Q: Python yield with no argument in try block I was reading this article and it was showing this interesting bit of code:
class Car(object):
   def _factory_error_handler(self):
      try:
         yield
      except FactoryColorError, err:
         stacktrace = sys.exc_info()[2]
         raise ValidationError(err.message), None, stacktrace

   def _create_customizer_error_handler(self, vin):
      try:
         yield
      except CustomizerError, err:
         self._factory.remove_car(vin)
         stacktrace = sys.exc_info()[2]
         raise ValidationError(err.message), None, stacktrace

   def _update_customizer_error_handler(self, vin):
      try:
         yield
      except CustomizerError, err:
         stacktrace = sys.exc_info()[2]
         raise ValidationError(err.message), None, stacktrace

   def create(self, color, stereo):
      with self._factory_error_handler():
         vin = self._factory.make_car(color)

      with self._create_customizer_error_handler(vin):
         self._customizer.update_car(vin, stereo)

      return vin

   def update(self, vin, color, stereo):
      with self._factory_error_handler():
         self._factory.update_car_color(vin, color)

      with self._update_customizer_error_handler(vin):
         self._customizer.update_car(vin, stereo)

      return

Here, they are yielding with no argument in a try block. And then using it within a with block. Can someone please explain what is going on here?

A: The code in the post appears to be wrong.  It would make sense if the various error handlers were decorated with contextmanager.  Note that, in the post, the code imports contextmanager but doesn't use it.  This makes me think the person just made a mistake in creating the post and left contextmanager out of that example.  (The later examples in the post do use contextmanager.)  I think the code as posted will cause an AttributeError, because the various _error_handler functions aren't context managers and don't have the right __enter__ and __exit__ methods.
With contextmanager, the code makes sense based on the documentation:

At the point where the generator yields, the block nested in the with statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred.


text:
Q: How to set unselected Text Color for TabLayout.Tab - Android How do you set text-color for a tab that's not selected?  I know you can set the text-color for the TabLayout by doing: setTabTextColors

A: Use app:tabTextColor for default tab color and app:tabSelectedTextColor for selected tab color.
        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="#000000"
            app:tabSelectedTextColor="#FFFFFF"/>

A: You can use style:
Add in styles.xml:
<style name="CustomTabLayout" parent="Widget.Design.TabLayout">
     <item name="tabTextColor">@color/default_text_color</item>
</style>

use in xml
<android.support.design.widget.TabLayout
    style="@style/CustomTabLayout"
 />


text:
Q: Fileupload inside repeater of updatepanel not working To avoid auto post back I have used update panel covering my asp webpage which is having multiple repeater in it.
Each repeater having file upload control in it. Each file upload is showing me empty file when I am trying to save.

A: File Upload control faces issues working with updatepanel
so to solve it
define a postback trigger for your control in the updatepanel,
or
if that doesn't work then use AsyncFileUpload control from Ajax toolkit


text:
Q: Requirement in order to discuss derivative and terminology for $x\in E\cap E'$. There are some people defined the hypothesis of discussing derivative of a function $f:E\rightarrow\mathbb{R}$ at $c$ to be that $c$ must in $E$ and be a limit(cluster) point of $E$, namely $c\in E\cap E'$, rather than simply put $E$ is an open interval containing $c$. I think there should be some terminology just describe this kind of the point. (e.g. $c$ is a XX point of $E$.) I have several analysis books, but didn't find one.
Another question, due to the difference of the definition of the derivative in terms of difference requirement on $c$. There are really some different description of the consequent theorems may occur. For example, if one takes the definition that $c\in E\cap E'$ in order to discuss the derivative of a function, than $f:[0,1]\rightarrow\mathbb{R}$ defined by $f(x)=x$ is differentiable at $1$, but if adopting the definition just like in the introductory calculus book(open interval containing $c$), then he should have slightly change the definition, or give another new definition(e.g. defining a one-sided derivative) in order to make the function be differentiable at $1$. And also, if one adapts the former, a common theorem in calculus that "if $f$ is differentiable at $c$ and $f$ has a relative extremum at $c$, then $f'(c)=0$" should be rewrite, since $f:[0,1]\rightarrow\mathbb{R}$ defined by $f(x)=x$ suits the antecedent, but $f'(1)\neq 0$. I haven't learned PDE or functional analysis or other advanced courses yet, so I don't have the whole picture and view to figure out which is better.

A: Here's a general approach which I think might prove helpful.
First, we define what we mean by a limit:
Let $(M,d)$ and $(N,\rho)$ be metric spaces.  Let $A \subseteq M$, let $f: A \to N$, let $a \in M$ be an accumulation point of $A$, and let $b \in N$.  If given any $\epsilon \in \mathbf R^+$ there exists some $\delta \in \mathbf R^+$ such that for all $x \in A$ we have the following:$$0 \lt d(x,a) \lt \delta \Rightarrow \rho(f(x),b) \lt \epsilon$$then we say that the limit of $f(x)$ as $x$ approaches $a$ is equal to $b$, and we write $$\lim_{x \to a}f(x)=b$$
Note that when $M=\mathbf R$ (using the usual Euclidean metric), this definition naturally handles limits at the endpoints of $A$.  We can force consideration of one-sided limits by restricting the domain appropriately and using the subspace metric, so no additional definitions should be needed for those cases.
Next, we define what it means for a function to be continuous:
Let $(M,d)$ and $(N,\rho)$ be metric spaces.  Let $A \subseteq M$, let $f: A \to N$, and let $a \in A$.  We say that $f$ is continuous at $a$ if either of the following holds:$$1)\; a\, \text{is not an accumulation point of} \,A$$ $$\text{or}\; 2)\; \lim_{x \to a}f(x)=f(a)$$
Note that the first option ($a$ is not an accumulation point of $A$) gives us continuity for "free" at isolated points of the domain.  It can be shown that this definition of continuity is equivalent to characterizations involving sequences, pre-images of open sets, and pre-images of closed sets.
Finally, we can define differentiability:
Let $\mathbf K$ be either $\mathbf R$ or $\mathbf C$.  Let $X \subseteq \mathbf K$ and let $a \in X$ be an accumulation point of $X$.  Let $E$ be a normed vector space over $\mathbf K$.  A function $f: X \to E$ is called differentiable at $a$ if the limit$$\lim_{x \to a}\frac{f(x)-f(a)}{x-a}$$exists in $E$.
Again, when $\mathbf K = \mathbf R$, we can handle one-sided derivatives by restricting the domain appropriately and using the subspace metric.
So, to answer the first part of your question: yes, we need to have a point be an accumulation point (i.e., a cluster point or a limit point) before we can talk about differentiability there.
As for the second part of your question, you're referring to this theorem attributed to Fermat, but you missed a critical part of hypothesis:
Suppose that $X \subseteq \mathbf R$ and $f: X \to \mathbf R$ has a local extremum at $a \in \text{int}(X)$.  If $f$ is differentiable at $a$, then $f'(a)=0$.
To answer the second part of your question: the fact that $a$ is an interior point of $X$ is a critical part of the hypothesis.  The theorem simply doesn't hold without it.  So your example, which has $X = [0,1]$ and $a=1$, a boundary point, doesn't contradict the theorem.
I hope this helps.


text:
Q: Opening Jquery fancybox from a function I can't seem to find the answer to this question anywhere so I ask here.
I already use successfully fancybox like this:
$("#editor").fancybox({
            'width' : 1000,
            'height' : 600,
            'autoDimensions' : false,
            'autoScale' : false,
            'ajax' : {
                type : "POST",
                data : varstring
            }
        })

Now the problem is that due to new necessities the varstring must contain unique data for each of the link that should open the fancybox window.
Tha way I was picturing it is like this:
function openEditor(elementid,sid,pid,gid){
    $("#"+elementid).fancybox({
            'width' : 1000,
            'height' : 600,
            'autoDimensions' : false,
            'autoScale' : false,
            'ajax' : {
                type : "POST",
                data : 'varstringnotimplemented'
            }
        });
    //$("#"+elementid).trigger('click');
    return false;
}

It doesn't work, if I uncomment the trigger I get a:
uncaught exception: Syntax error, unrecognized expression: #

Even if I manage to get this thing working is pretty ugly, is there a better way to do this?
Thank you

A: It would be better to pass the actual object instead of an id.
function openEditor(element,sid,pid,gid){
    var $element = $(element);
    var dataString = '??';
    var ajaxSettings = {
                type : "POST",
                data : dataString
            };

    $element.fancybox({
            'width' : 1000,
            'height' : 600,
            'autoDimensions' : false,
            'autoScale' : false,
            'ajax' : ajaxSettings
        });
    $element.trigger('click');
    return false;
}

link would be
text

you cannot pass the actual object if you send it trough the href, you can send it through the onclick


text:
Q: Rails partial not rendering with JavaScript I'm trying to render a partial in my app, but for some reason it will not render. I think it has to do with my asset pipeline and the fact that I am not correctly implementing the JavaScript I want to use in my partial. A test partial with a simple sentence works just fine. Can someone direct me in the proper use of JavaScript in my app?
Here is a jsFiddle of what I am trying to show: http://jsfiddle.net/yZQg4/
Problematic partial:
<%= javascript_include_tag "highcharts", "exporting", "jquery-1.4.2.min", "rails" %>

Working test partial:

 hello world

Thanks!

A: Add before the javascript code this:

P.S. Besides it's better move javascript inclusion out of partial or using a content_for

A: I just recreated the file in TextEdit, and it worked. For some reason TextMate was secretly adding this to the file: .


text:
Q: Category defined by a finite commutative diagram What is the name for a category defined by a finite commutative diagram?
Maybe category "induced" by a commutative diagram? or category "defined" by a commutative diagram?
Also, what is the exact definition of this intuitively clean concept?

A: It is usually called the free category on (over) the diagram, but the term 'induced by' is also clear.
We can formalize abstract diagrams as directed graphs (i.e. quivers) with a set of commutativity conditions, which are just pairs of parallel paths.
Then we have the usual free-forgetful adjunction between these abstract diagrams and categories.


text:
Q: Pytorch cross entropy input dimensions I'm trying to develop a binary classifier with Huggingface's BertModel and Pytorch.
The classifier module is something like this:
class SSTClassifierModel(nn.Module):

  def __init__(self, num_classes = 2, hidden_size = 768):
    super(SSTClassifierModel, self).__init__()
    self.number_of_classes = num_classes
    self.dropout = nn.Dropout(0.01)
    self.hidden_size = hidden_size
    self.bert = BertModel.from_pretrained('bert-base-uncased')
    self.classifier = nn.Linear(hidden_size, num_classes)

  def forward(self, input_ids, att_masks,token_type_ids,  labels):
    _, embedding = self.bert(input_ids, token_type_ids, att_masks)
    output = self.classifier(self.dropout(embedding))
    return output

The way I train the model is as follows:
loss_function = BCELoss()
model.train()
for epoch in range(NO_OF_EPOCHS):
  for step, batch in enumerate(train_dataloader):
        input_ids = batch[0].to(device)
        input_mask = batch[1].to(device)
        token_type_ids = batch[2].to(device)
        labels = batch[3].to(device)
        # assuming batch size = 3, labels is something like:
        # tensor([[0],[1],[1]])
        model.zero_grad()
        model_output = model(input_ids,
                             input_mask,
                             token_type_ids,
                             labels)
        # model output is something like: (with batch size = 3)
        # tensor([[ 0.3566, -0.0333],
                 #[ 0.1154,  0.2842],
                 #[-0.0016,  0.3767]], grad_fn=<AddmmBackward>)

        loss = loss_function(model_output.view(-1,2) , labels.view(-1))

I'm doing the .view()s because of the Huggingface's source code for BertForSequenceClassification here which uses the exact same way to compute the loss. But I get this error:
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in binary_cross_entropy(input, target, weight, size_average, reduce, reduction)
   2068     if input.numel() != target.numel():
   2069         raise ValueError("Target and input must have the same number of elements. target nelement ({}) "
-> 2070                          "!= input nelement ({})".format(target.numel(), input.numel()))
   2071
   2072     if weight is not None:

ValueError: Target and input must have the same number of elements. target nelement (3) != input nelement (6)

Is there something wrong with my labels? or my model's output? I'm really stuck here. The documentation for Pytorch's BCELoss says:
Input: (N,∗) where ∗ means, any number of additional dimensions
Target: (N,∗), same shape as the input
How should I make my labels the same shape as the model output? I feel like there's something huge that I'm missing but I can't find it.

A: Few observations:

*

*The code that you refer to uses CrossEntropyLoss but you are using BCELoss.

*CrossEntropyLoss takes prediction logits (size: (N,D)) and target labels (size: (N,)) whereas BCELoss takes p(y=1|x) (size: (N,)) and target labels (size: (N,)) as p(y=0|x) can be computed from p(y=1|x)

*CrossEntropyLoss expects logits i.e whereas BCELoss expects probability value

Solution:
Since you pass an (N,2) tensor, it gives an error. You only need to pass p(y=1|x), therefore you can do
loss = loss_function(model_output.view(-1,2)[:,1] , labels.view(-1))
above I assumed that the second value is p(y=1|x).
A cleaner way would be to make model output only one value i.e p(y=1|x) and pass it to the loss function. It seems from the code that you are passing logit values and not probability values, so you may also need to compute sigmoid (model_output) if you want to use BCELoss or alternatively you can use BCEWithLogitsLoss.
Another alternative is to change the loss to CrossEntropyLoss that should work too as it can work for binary labels too.


text:
Q: How to force a Chrome extension to load after inline install I have a website which includes an inline installation of Chrome extension.
The problem is that once the extension is installed it doesn't act on the my website until the user refresh the page. Is there a way to load the extension on the existing page without refresh?

A: I think you can not load you extension without reload exsiting page after install.
so I think, try to use chrome.webstore.install(url, successCallback, failureCallback)
and call location.reload() in suncessCallback function.


text:
Q: Can I get the value from a typeahead.js field? I'm using typeahead.js for an autocomplete field. I need to get the value in the input regardless if is in the autocomplete list or not.
Is this possible?
How can I make this?
Could this be a new issue?

A: Try
$(".typeahead").typeahead({/* typeahead options */})
.on("input", function(e) {
  // do stuff with current `typeahead` `value`
  var myVal = e.target.value; // `$(e.target).typeahead("val")
  console.log(myVal)
});

jsfiddle http://jsfiddle.net/2reurafk/1/
See jQuery#typeahead('val')

A: my solution for my code, wasnt easy to figure it out but thanks to @guest271314
$('form#prefetch').bind("keypress", function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        var query = $(e.target).typeahead("val").split(" ").join("-").toLowerCase();
        return window.location = baseurl+'search/'+query;
    }
});


text:
Q: Can't get authentication to work with devise-jwt I am trying to get devise and devise-jwt gems to work so I can implement Authorization into my API only Rails app.
I have installed both devise and devise-jwt gems.
I followed the instructions on this blog post:
https://medium.com/@mazik.wyry/rails-5-api-jwt-setup-in-minutes-using-devise-71670fd4ed03
I implemented the requests specs the author included in his post, and I can't get them to pass. If I put a byebug into the session controller, I see that it's saying the "User needs to sign in or sign up before continuing."
Any thoughts on what I'm doing incorrectly?
Here are the relevant files:

  routes.rb
Rails.application.routes.draw do

  namespace :api, path: '', defaults: {format: :json} do
      namespace :v1 do
        devise_for :users,
                   path: '',
                   path_names: {
                     sign_in: 'signin',
                     sign_out: 'signout',
                     registration: 'signup'
                   }
        ...
      end
  end

  controllers/api/v1/sessions_controller.rb
  class API::V1::SessionsController < Devise::SessionsController
    respond_to :json

    private

    def respond_with(resource, _opts = {})
      render json: resource
    end

    def respond_to_on_destroy
      head :no_content
    end
  end

  models/user.rb
class User < ApplicationRecord
      devise  :confirmable, :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :jwt_authenticatable, jwt_revocation_strategy: JwtBlacklist

      ...
  end

  models/jwt_blacklist.rb
  class JwtBlacklist < ApplicationRecord
    include Devise::JWT::RevocationStrategies::Blacklist

    self.table_name = 'jwt_blacklist'
  end

  config/initializers/devise.rb
  Devise.setup do |config|

    # Setup for devise JWT token authentication
    config.jwt do |jwt|
      jwt.secret = Rails.application.secret_key_base
      jwt.dispatch_requests = [
        ['POST', %r{^*/signin$}]
      ]
      jwt.revocation_requests = [
        ['DELETE', %r{^*/signout$}]
      ]
      jwt.expiration_time = 1.day.to_i
    end

    config.navigational_formats = []

    ...

  end

  spec/request/authentication_spec.rb
  require 'rails_helper'

  describe 'POST /v1/signin', type: :request do
    let(:user) { create(:user) }
    let(:url) { '/v1/signin' }
    let(:params) do
      {
        user: {
          email: user.email,
          password: user.password
        }
      }
    end

    context 'when params are correct' do
      before do
        post url, params: params
      end

      it 'returns 200' do
        expect(response).to have_http_status(200)
      end

      it 'returns JTW token in authorization header' do
        expect(response.headers['Authorization']).to be_present
      end

      it 'returns valid JWT token' do
        decoded_token = decoded_jwt_token_from_response(response)
        expect(decoded_token.first['sub']).to be_present
      end
    end

    context 'when login params are incorrect' do
      before { post url }

      it 'returns unathorized status' do
        expect(response.status).to eq 401
      end
    end
  end

  describe 'DELETE /v1/signout', type: :request do
    let(:url) { '/v1/signout' }

    it 'returns 204, no content' do
      delete url
      expect(response).to have_http_status(204)
    end
  end

I would expect the tests to pass, but I get the following errors:

  Test Failures
  Failures:

    1) POST /v1/signin when params are correct returns 200
       Failure/Error: expect(response).to have_http_status(200)
         expected the response to have status code 200 but it was 401
       # ./spec/request/authentication_spec.rb:21:in `block (3 levels) in <top (required)>'

    2) POST /v1/signin when params are correct returns JTW token in authorization header
       Failure/Error: expect(response.headers['Authorization']).to be_present
         expected `nil.present?` to return true, got false
       # ./spec/request/authentication_spec.rb:25:in `block (3 levels) in <top (required)>'

    3) POST /v1/signin when params are correct returns valid JWT token
       Failure/Error: decoded_token = decoded_jwt_token_from_response(response)

       NoMethodError:
         undefined method `decoded_jwt_token_from_response' for #<RSpec::ExampleGroups::POSTV1Signin::WhenParamsAreCorrect:0x00007fec3d3ae158>
       # ./spec/request/authentication_spec.rb:29:in `block (3 levels) in <top (required)>'

  Finished in 0.76386 seconds (files took 3.31 seconds to load)
  5 examples, 3 failures

  Failed examples:

  rspec ./spec/request/authentication_spec.rb:20 # POST /v1/signin when params are correct returns 200
  rspec ./spec/request/authentication_spec.rb:24 # POST /v1/signin when params are correct returns JTW token in authorization header
  rspec ./spec/request/authentication_spec.rb:28 # POST /v1/signin when params are correct returns valid JWT token

A: I don't know if you found a solution; but I leave an approach I've made; It might helpfull.
Taking special attetion to the problem, The solution was to change:
decoded_token = decoded_jwt_token_from_response(response)

To:
decoded_token = JWT.decode(response.headers['authorization'].split(' ').last, Rails.application.credentials.jwt_secret, true)

Beacuse I din't find any in the documentation or other place and I chose to decode with method provided by JWT.
Also if you see I handle the requests in a different way, but I think that is not a problem at all.
require 'rails_helper'
require "json"

RSpec.describe "POST /login", type: :request do

  let(:user) { User.create!(  username: 'usertest',
                              email: 'usertest@email.com',
                              password: 'passwordtest123',
                              password_confirmation: 'passwordtest123') }

  let(:url) { '/users/login' }
  let(:params) do
    {
      user: {
        login: user.email,
        password: user.password
      }
    }
  end

  context 'when params are correct' do
    before do
      post url, params: params.to_json, headers: { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }
    end

    it 'returns 200' do
      expect(response).to have_http_status(200)
    end

    it 'returns JTW token in authorization header' do
      expect(response.headers['authorization']).to be_present
    end

    it 'returns valid JWT token' do
      token_from_request = response.headers['Authorization'].split(' ').last
      decoded_token = JWT.decode(token_from_request, Rails.application.credentials.jwt_secret, true)
      expect(decoded_token.first['sub']).to be_present
    end
  end

  context 'when login params are incorrect' do
    before { post url }

    it 'returns unathorized status' do
      expect(response.status).to eq 401
    end
  end
end

RSpec.describe 'DELETE /logout', type: :request do
  let(:url) { '/users/logout' }

  it 'returns 204, no content' do
    delete url
    expect(response).to have_http_status(204)
  end
end

RSpec.describe 'POST /signup', type: :request do
  let(:url) { '/users/signup' }
  let(:params) do
    {
      user: {
        username: 'usertest2',
        email: 'usertest2@email.com',
        password: 'passwordtest123',
        password_confirmation: 'passwordtest123'
      }
    }
  end

  context 'when user is unauthenticated' do
    before  {
              post url,
              params: params.to_json,
              headers: { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }
            }

    it 'returns 201' do
      expect(response.status).to eq 201
    end

    it 'returns a new user' do
      expect(response).to have_http_status :created
    end
  end

  context 'when user already exists' do
    before do
      post url,
      params: params.to_json,
      headers: { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }

      post url,
      params: params.to_json,
      headers: { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }
    end

    it 'returns bad request status' do
      expect(response.status).to eq 400
    end

    it 'returns validation errors' do
      expect(response_body['errors'].first['title']).to eq('Bad Request')
    end
  end
end

PD: I leave the spec code for register, with a couple differences (requests, url, username params in User model (that's is why I use the login param y the login request), I made all in a sigle spec.rb file, ...) to https://medium.com/@mazik.wyry/rails-5-api-jwt-setup-in-minutes-using-devise-71670fd4ed03. Kepp that in mind.

A: I believe you need to use the helper sign_in user before making the request for it to be authorized. Check https://github.com/heartcombo/devise, Controller tests


text:
Q: Help identifying a varistor (on a shredder PCB)? I am trying to identify what I think is a varistor. The markings are : "9 / MVG" and "10K431".
I think "10" is the diameter, "K" is the tolerance and "431" is voltage. Am I correct?
What does "9 / MVG" mean?
In reference to the the following sample part, how do I find out the "Clamping voltage", "Amperage" and "Capacitance" for the varistor I need to replace?
A sample part from RS:

Vishay VDRS - E Series Metal Oxide Varistor
140pF 10A, Clamping 710V, Varistor 430V RS Stock No.178-071 Mfr. Part
No.VDRS07H275BSE

The PCB I am trying to fix comes from a Fellowes 225i shredder.

A: Your Varistor is a MYG-10K431.
The nomenclature that comes before the 'MYG', refers to the manufacturer, if I'm not mistaken.
The MYG-10K431 datasheet expose that:
Part Number Code: MYG-XXKXXX, wherein

*

*MYG : Product Type [9/MYG]

*XX  : Diameter     [05= 5mm; 07= 7mm; 10=10mm; 14=14mm; 20=20mm]

*K   : Tolerance    [K: (+ or -) 10%]

*XXXX: Voltage

So, I guess 9/MYG means the varistor type. Check the datasheet in the link bellow.
Source [DATASHEET]: https://datasheetspdf.com/pdf-file/1213341/ETC/MYG-10K431/1


text:
Q: Can someone show me how to prove that $f:X \rightarrow Y$ is onto if and only if it has a right inverse? $f:X \rightarrow Y$ is onto if and only if it has a right inverse: that is, a function $g:Y \rightarrow X$ such that $f \circ g = 1_y$

A: You probably mean the map of sets. If $f: X\to Y$ is onto then for any $y\in Y$ there exists $x\in X$ such that $f(x) = y$. Choose for every $y\in Y$ such an $x$ and call it $x_y$. Define $g:Y\to X$ as $g(y) = x_y$. It obviously follows that $(f\circ g) (y) = y$.
If there exists a right inverse $g:Y\to X$ then for any $y\in Y$ take $x = g(y)\in X$. Since $f\circ g = 1_Y$ $f(x) = f(g(y)) = y$ and hence $f$ is onto.


text:
Q: iCloud Drive / UIDocumentPicker confusions I'm trying to add iCloud Drive functionality to my iPhone app, by providing 2 features:

*

*import a document which is stored on iCloud Drive to my local app

*export a document from local store to iCloud Drive

The first part is done, and it was pretty easy. I used UIDocumentPicker with UIDocumentPickerModeImport to obtain a file url, which I just read to use the document in my app.
The second part, however, kind of confuses me. If I understand it correctly, all I have to do is instantiate a UIDocumentPicker with the file url of some document from the app local store, and the UIDocumentPicker will do all the rest (= saving to iCloud Drive, in case the user picks a location there).
Is this correct? Because this is what I've implemented. And while the files show up in the folder from picker selection, they will not sync neither to my Mac nor to www.icloud.com. So it seems like they are somehow stored in "the document picker on my phone", whatever this means.
Am I doing something wrong? The file I copied to the iCloud Drive folder on my mac perfectly showed up in the import-picker on the iPhone.

A: Actually, the files just turned up in finder (and also www.icloud.com). So it must have been some sync issue, or it just takes a while for it to sync.
Question answered/closed :)


text:
Q: Fetch & show item details I'm currently learning Flutter and developing a Shopping List.
In the backend, there's a Laravel instance providing the following Endpoints:

*

*/lists -> A list of all shopping lists

*/lists/{listId}/items -> All items in the list

For the Flutter side, I've created a provider which fetches all lists from the server.
Future<void> init() async {
  this.lists = await this.service.getLists();
  notifyListeners();
}

This data (<List<ListModel>>) is retreived by my widget and displayed through ListView.builder. The RefreshIndicator just refreshes the provider data by run the init method again.
Widget build(BuildContext context) {
  final provider = Provider.of<ShoppingListProvider>(context);
  List<ListModel> lists = provider.lists;

...
child: RefreshIndicator(
    onRefresh: () => provider.init(),

Now, if I click on the ListTile, I'd like to display all items. They should be fetched from the API as well, and I'd like to refresh the item list too. Unfortunately, I don't manage to get this data provided through the provider, as it requires the "listId".
Maybe someone can give me a hint on this?
Fetched from inside the widget, which works, but then I can't refresh the data. It somehow should be provided through the provider


text:
Q: VS Code false positive errors in Angular html templates I am using VS Code with the Angular Language Service extension.  VS Code frequently falsely reports errors in my Angular HTML templates.  I can run the Angular application successfully, run my unit tests successfully and build the application successfully without ever seeing the errors being reported by VS Code.  I have seen multiple types of errors reported but the one I see most often is below.  I do not always see these false positives but it does happen quite often.  Is there a fix for this?
'xyz' is not a known element:
1. If 'xyz' is an Angular component, then verify that it is part of this module.
2. If 'xyz' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

A: May be you are using the selector of your component wrongly. Check your selector of your component that if it is used as the html tag properly somewhere in html files.


text:
Q: FileInfo finds file, but File.Copy cannot find the file I am trying to find a file with the last write date and copy it to a different location. It finds the file correctly, but when I try to copy it, it can't find the file it just found. This is in a SSIS script task.
DirectoryInfo directory = new DirectoryInfo(@"path");
FileInfo[] files = directory.GetFiles();

//files that have been written to in the last 3 days
DateTime lastWrite = DateTime.Now.AddDays(-3);

foreach (FileInfo latestFile in files)
{
    // if its the correct name
    if (latestFile.Name.StartsWith("OMC"))
    {
        // if its in the last 3 days
        if (latestFile.LastWriteTime > lastWrite)
        {
            lastWrite = latestFile.LastWriteTime;

            // this correctly find the file and puts it into the file variable.
            file = latestFile.ToString();

            // this errors out saying it cannot find the file.
            // (Does not even go to the outputFile)
            File.Copy(file, outputFile, true); // <- error

            //backs the file up
            File.Copy(file, backupfile, true);
        }
    }
}

A: FileInfo.ToString() returns the name of the file, but in order to copy it, you need the full path. Change
file = latestFile.ToString();

To
file = latestFile.FullName;

And give it a shot.

A: What does latestFile.ToString() evaluate to? That is a strange way to obtain the path.
Use FileInfo.FullName like the docs indicate.
You can use the debugger to find such bugs yourself.

A: You may need to construct the full path instead of using Fileinfo.ToString():
file = latestFile.FullName;

From MSDN:

there are cases where the string returned by the ToString method does not represent the fully qualified path. For example, when you create a FileInfo object using the GetFiles method, the ToString method does not represent the fully qualified path.


text:
Q: How to know if the current Servlet request is the result of a redirect? Is there a way to know if the request has been redirected or forwarded in the doGet method of a Servlet?
In my application, when a user (whose session has timed out) clicks on a file download link, they're shown the login page, which is good. When they login, they are immediately sent the file they requested, without updating the page they see, which is bad. Basically, they get stuck on the login screen (a refresh is required).
What I want to do is interrupt this and simply redirect to the page with the link, when a file is requested as a result of a redirect.
Perhaps there are better ways to solve this?

A: The redirect happens client-side. The browser is instructed by the previous request to send a new request, so to the server it does not make a difference. The Referer header might contain some useful information, but it's not certain.
When redirecting you can append some parameter, like ?targetPage=dowloadpage and then check if the parameter exists. You may have to put this in a hidden field on the login page if you want it to be transferred through multiple pages.

A: If you're using container managed authentication, then I don't believe you can detect this since the server will only involve your resource once authentication has been completed successfully.
If you're managing authentication differently, please explain.


text:
Q: How can I implement nested boost::mpl::fold How can I implement nested boost::mpl::fold ?
namespace mpl=boost::mpl;

typedef mpl::vector_c<int,1,1,1> vec1;
typedef mpl::vector_c<int,2,2,2> vec2;
typedef mpl::vector_c<int,3,3,3> vec3;
typedef mpl::vector<vec1,vec2,vec3> vvec;

typedef typename mpl::lambda
    <mpl::fold
        <mpl::_1
        ,mpl::int_<0>
        ,typename mpl::lambda<mpl::plus<mpl::_1,mpl::_2>>::type
        >
    >::type lam;

typedef typename mpl::fold
    <vvec
    ,mpl::int_<0>
    ,mpl::plus<mpl::_1,typename lam::template apply<mpl::_2>::type>
    >::type result;

BOOST_MPL_ASSERT((mpl::equal_to<result,mpl::int_<18>>));

I want result to be 18, but above equals to 0.

A: Nested binds always invite collisions between placeholders: the lambda uses the same placeholders as the outer fold does, and the substitution will do the wrong thing.
Boost Lambda, Boost Bind and yes, even Boost Mpl implement the protect/unprotect combo so you can fix this:
Live On Coliru
#include <boost/mpl/vector.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/lambda.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/protect.hpp>
#include <boost/mpl/equal_to.hpp>

namespace mpl = boost::mpl;

typedef mpl::vector_c<int, 1, 1, 1> vec1;
typedef mpl::vector_c<int, 2, 2, 2> vec2;
typedef mpl::vector_c<int, 3, 3, 3> vec3;
typedef mpl::vector<vec1, vec2, vec3> vvec;

typedef typename mpl::lambda<
        mpl::fold<
            mpl::_1,
            mpl::int_<0>,
            typename mpl::lambda<mpl::plus<mpl::_1, mpl::_2> >::type
        >
    >::type lam;

typedef typename mpl::fold<
        vvec,
        mpl::int_<0>,
        mpl::plus<mpl::_1, mpl::protect<lam>::type::apply<mpl::_2> >
    >::type result;

static_assert(mpl::equal_to<result, mpl::int_<18>>::value, "should be 18");

int main() {}


text:
Q: Mono for android : using Facebook binding I'm trying to use the Facebook sdk api binding (https://github.com/xamarin/monodroid-samples/tree/master/Facebook)
The bindings works only if I set the package name in the manifest to Com.Facebook.Android.
If I don't do this, I get an exception when I launch the login dialog (NoClassDefFoundError: com.facebook.android.R$drawable). The dialog tries to load a resource from the com.facebook.android package.
Is there a way to workaround this? My application cannot use Com.Facebook.Android as the package name, because it must be unique.

A: I had the same issue, I resolved it a bit differently. After importing the project, go to Project Properties > Android > and Scroll Down to "Library" the package "com.facebook.android" should be listed there, select it and click on "Apply" and "OK". This will build the R.java for the facebook api, as the API generates a dialog the R.java is required.
If you dont see the package as said above, then the project was added as an External Jar. This will list it under "Referenced Libraries" in your Explorer.
Just import it as a project and follow as mentioned above.


text:
Q: How to surround an overlayed (z-indexed) image with a surrounding ring of transparency? I am trying to create image icons that have a status dot which emulates Slack member-icons (left).
How can I use CSS to add a transparent ring around the dot?

.memberIconRow {
    display: flex;
    .memberIconArea {
        position: relative;
        img {
            width: 30px;
            margin: 0 6px 0 0;
            border-radius: 5px;
        }
        .statusDot {
            background: #f00;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            position: absolute;
            z-index: 2;
            top: 21px;
            left: 23px;
        }
    }
}

A: Some dirty trick what I think of is add border to your dot with the same background as your photo, in this case - a light yellow.
Like this -
.statusDot {
    ...
    border:4px solid yellow; /* same color as you profile photo background */
}

In multiple background colours case, use css var() like;
:root {
  --blue: #1e90ff;
}
.member-bg {
    background-color: var(--blue);
}
. statusDot {
    border: 4px solid var(--blue);
}


text:
Q: Записать в одну строку, если ID одинаковы Есть скрипт, который делаем выгрузку, но есть проблема, когда к примеру у товара один и тот же ID, но разные опции, он выгружает их отдельно. Вот пример:
[0]
GoodID=112
Price=152.0000
Count=1
[1]
GoodID=111
Price=152.0000
Count=1
[2]
GoodID=111
Price=152.0000
Count=1

Это я выбрал так (один и тот же товар):
- Телефон (Красный)
- Телефон (Синий)
- Телефон (Зеленый)
Нужно, чтобы эти три телефона были в одной выдаче. Может можно поставить на игнорирование типы опций: 'image', 'checkbox'.
        $result_for_base_a = $this->db->query("SELECT * FROM oc_order_option WHERE order_id = '$id' AND type = 'select';");
        for($j = 0; $j<count($result_for_base_a->rows); $j++) {
            $product_option_value_id=$result_for_base_a->rows[$j]['product_option_value_id'];
            $product_option_id=$result_for_base_a->rows[$j]['product_option_id'];

            $result_for_base_c = $this->db->query("SELECT * FROM oc_product_option WHERE product_option_id = '$product_option_id'");
            $product_id=$result_for_base_c->row['product_id'];
            $result_for_base_b = $this->db->query("SELECT * FROM oc_product_option_value WHERE product_option_value_id = '$product_option_value_id' AND product_id='$product_id'");
            $points = $result_for_base_b->row['points'];

            $price = $result_for_base_b->row['price'];
            $counts = $result_for_base_a->rows[$j]['quantity'];

$str .= <<<EOD
\n[$j]
GoodID=$points
Price=$price
Count=$counts
EOD;

A: Можно извлекать такие товары группируя результат при помощи GROUP BY, а различающиеся столбцы получать в виде строки через запятую, воспользовавшись функцией GROUP_CONCAT()
SELECT
  product_id,
  GROUP_CONCAT(product_option_value_id) AS ids
FROM
  oc_product_option_value
WHERE
  product_id='$product_id'

Полученный таким образом список можно использовать для формирования более сложных вложенных запросов, например, с использованием конструкции IN().


text:
Q: CUDA syntax highlighting in Qt Creator Is someone aware of a method to highlight CUDA code while using Qt Creator? I could do so in vim and kate, but not in Qt Creator and I have to use it.

A: If you could highlight CUDA code in Kate then you can do it in Qt Creator as well because in Qt Creator generic highlighting is based on highlight definition files that are provided by the Kate Editor.
Although Qt Creator helps you download highlight definition files (see the documentation), unfortunately I can not see CUDA in the Download Definitions dialog so you have to copy the CUDA highlight definition file you use with Kate manually to the location where Qt Creator expects them (see Location and Fallback location in the documentation mentioned).

A:
A quick workaround is to add .cu and .cuh in cpp.xml in qt creator's generic-highlighter folder like above.


text:
Q: Play Json Single Field Reads Validator I'm trying to add simple validation to incoming Json in Play. Based on this question, I tried writing:
case class ApiData(data: String)

def maxLengthValidator = Reads.StringReads.filter(ValidationError("Error"))(_.length < 100)

implicit val ApiDataReads: Reads[ApiData] = (
  (JsPath \ "data").read[String](maxLengthValidator)
)(ApiData.apply _)

This does not compile, producing the error:
type mismatch;
[error]  found   : String => ApiData
[error]  required: play.api.libs.json.Reads[?]
[error]     )(ApiData.apply _)
[error]                        ^
[error] one error found

But if I add a second field, it does compile:
case class ApiData(data: String, __doNotUse: Option[Int])

implicit val ApiDataReads: Reads[ApiData] = (
  (JsPath \ "data").read[String](maxLengthValidator) and
  (JsPath \ "__doNotUse").readNullable[Int]
)(ApiData.apply _)

What do I need to do to get this working with just a single field?

A: Since you only have a single field, you don't need the combinator syntax to create a reads, you can just use the functions already defined on Reads to build the one you want.
def maxLengthValidator = Reads.of[String].filter(ValidationError("Error"))(_.length < 100)

case class ApiData(data: String)

object ApiData {

  implicit val reads: Reads[ApiData] = (__ \ "data").read(maxLengthValidator).map(ApiData.apply _)

}

You start with a Reads[String], add some validation (filter) and then transform valid results to your own rich type (map).


text:
Q: Poor Coverage for Bootstrap Confidence Interval on Mean Based on a highly skewed population, I was hoping to obtain good coverage with bootstrap (vs standard) confidence intervals.  I'm not having much luck.
I specify my population in R as a Gamma distribution with shape = 0.3 and scale = 0.5.  I think it's easiest to see the skew of this population with a graph of its CDF:
plot(1:1000/1000, pgamma(1:1000/1000, shape = 0.3, scale = 0.5),
     type = "l", yaxs = "i", xaxs = "i", xlim = c(0, 1), ylim = c(0, 1), col = "red",
     xlab = "Value", ylab = "CDF", main = "Population CDF")

Note that the true mean for this gamma distribution is a function of its parameters: $0.3\times0.5 = 0.15$.
In each of 10,000 simulations, I sample 24 values from this distribution.  In each simulation, I calculate the sample mean.  I also calculate a standard confidence interval (based on assumed normality) and three bootstrap confidence intervals (using the boot package in R).  For each simulation, I determine whether the true mean is within the confidence interval for each method.  Note that these simulations took my computer about 25 minutes to run.
library(boot)
set.seed(1776)
(trueMean <- 0.3*0.5)

mean.boot <- function(x, i) mean(x[i]) #To be used with boot package for bootstrapping

sampSize <- 24
numSims <- 10000
bootstrapIterations <- 10000
resultsDF <- data.frame(sampMean = numeric(numSims), withinStandard = logical(numSims),
                        withinNorm = logical(numSims), withinPerc = logical(numSims),
                        withinBca = logical(numSims))

for (i in 1:numSims) {
  temp1 <- rgamma(sampSize, shape = 0.3, scale = 0.5)
  sampMean <- mean(temp1)
  sampVariance <- var(temp1)/sampSize
  standard_low <- sampMean - qt(0.95, sampSize - 1)*sqrt(sampVariance)
  standard_high <- sampMean + qt(0.95, sampSize - 1)*sqrt(sampVariance)

  boot1 <- boot(temp1, mean.boot, bootstrapIterations)
  bootCI1 <- boot.ci(boot1, conf = 0.9, type = c("norm", "perc", "bca"))
  normal_low <- bootCI1[[4]][2]
  normal_high <- bootCI1[[4]][3]
  perc_low <- bootCI1[[5]][4]
  perc_high <- bootCI1[[5]][5]
  bca_low <- bootCI1[[6]][4]
  bca_high <- bootCI1[[6]][5]

  resultsDF$sampMean[i] <- sampMean
  resultsDF$withinStandard[i] <- standard_low <= trueMean & standard_high >= trueMean
  resultsDF$withinNorm[i] <- normal_low <= trueMean & normal_high >= trueMean
  resultsDF$withinPerc[i] <- perc_low <= trueMean & perc_high >= trueMean
  resultsDF$withinBca[i] <- bca_low <= trueMean & bca_high >= trueMean
  if (i %% 100 == 0) print(paste0("Simulation: ", i))
}

Based on the simulations, the following histogram approximates the sampling distribution of the mean.
hist(resultsDF$sampMean, breaks = 39, xlim = c(0, 0.4), main = "Approximation of Sampling Distribution",
     xlab = "Sample Mean")

The histogram's shape is far from normal, so it's not surprising that the coverage for the standard confidence interval is poor.  Unfortunately, the bootstrap intervals also have poor coverage.
mean(resultsDF$withinStandard)
mean(resultsDF$withinNorm)
mean(resultsDF$withinPerc)
mean(resultsDF$withinBca)

Specifically, I'm estimating the following coverages for my 90% confidence intervals:
Standard: 0.8314,
Bootstrap Normal: 0.8128,
Bootstrap Percentile: 0.8219,
Bootstrap BCA: 0.8452.
I'm wondering if I'm doing something wrong, or if my data are just too skewed for a sample size of 24?  Was there something I should have known about bootstrapping that would have made it obvious that my results would be poor?  I figured that my results, even if imperfect, would be notably better than the standard results, which actually require a normal sampling distribution.  Also, any guidance on what I can do to improve my results would be greatly appreciated.


text:
Q: WebView onShowFileChooser not working in some device When I click the select pictures button on webView, it works and can choose pictures
but when I use vivo, it nothing happened.
How to solve it.
Any help will be appreciate.
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val webView = findViewById<WebView>(R.id.webView)
        val settings = webView.settings
        settings.javaScriptEnabled = true

        webView.loadUrl("XXX")// a webLink

        webView.webChromeClient = object : WebChromeClient() {

            override fun onShowFileChooser(view: WebView, filePath: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
                if (filePathCallback != null) {
                    filePathCallback!!.onReceiveValue(null)
                }
                filePathCallback = filePath
                val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)
                contentSelectionIntent.type = "image/*"
                val chooserIntent = Intent(Intent.ACTION_CHOOSER)
                chooserIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOfNulls<Intent>(0))
                resultLauncher.launch(chooserIntent)
                return true
            }

            override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message): Boolean {
                return false
            }
        }
    }