text:
Q: Netty 4 - ByteToMessageDecoder with multi-byte delimiter In my Netty 3.x FrameDecoder implementation I make use of the ChannelBufferIndexFinder to help me find the delimiter between FIX (http://www.fixtradingcommunity.org) messages.  The delimiter is defined as a series of characters.  To find the delimiter, I am utilising the ChannelBuffer.indexOf() method with my implementation of the ChannelBufferIndexFinder.
The ChannelBufferIndexFinder passes in the ChannelBuffer, so I was able to check other bytes in the buffer for the delimiter.
With Netty 4.x, the ByteBuf.indexOf() only allows me to search for a single byte.  Alternatively, there is also ByteBuf.forEachByte(ByteBufProcessor), however a ByteBufProcessor once again only gives me access to a single byte.
Is there a way to find my delimiter?  I'm guessing at the moment my only solution will be to roll my own equivalent version of ByteBuf.forEachByte() that spans multiple bytes?  Something like what the DelimiterBasedFrameDecoder.indexOf() has done?
Thanks!

A: You may use io.netty.handler.codec.DelimiterBasedFrameDecoder with a io.netty.buffer.ByteBuf containing the series of characters.
DEPRECATED
You may use your own implementation of io.netty.buffer.ByteBufIndexFinder with something similar to
@Override
public boolean find(final ByteBuf buffer, final int index) {
    boolean found;

    if (validateIndex(buffer, index)
            && sufficentBytesReadable(buffer, index)) {
        final byte byte0 = buffer.getByte(index);
        final byte byte1 = buffer.getByte(index + 1);
        found = byte0 == '\r' && byte1 == '\n';
    } else {
        found = false;
    }

    return found;
}
private boolean sufficentBytesReadable(final ByteBuf buffer,
        final int index) {
    return buffer.writerIndex() - index >= 2;
}
private boolean validateIndex(final ByteBuf buffer, final int index) {
    return index >= buffer.readerIndex() && index <= buffer.writerIndex();
}


text:
Q: Different background images jquery mobile I am trying to set different background images for each page in jquery mobile.

...

...

As you can see, each page has a different id, so my thought was that i can assign background image for that id (and another image for another id)
#pageone {background: transparent url(URL) repeat center center !important;}
#pagetwo {background: transparent url(URL) repeat center center !important;}

The image is a pattern (really small 7x10 px). But i couldn't do it. For some reason it appears when you load the page (outside the page div) but then it disappears.
Did anyone encounter the same problem and knows what can i do about it?
Ty in advance :)

A: Ended up using theme roller and importing my theme there.
Then duplicated it into swatch b c and d.
In my CSS file i changed the color to background image (for each swatch there was a different image)
In my html i put:

...

...

and that for each page i have that have their own background image.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why won't my layer animate about the Z axis? I have an image which I place in a CALayer, then add that layer as a sublayer of the main view.  When I try to animate it around its Z axis, all I see is a static image.
Why won't my layer animate?  The relevant code is as follows:
- (void)viewDidLoad {

    UIImage *myImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"about" ofType:@"png"]];
    earthLayer = [CALayer layer];
    [earthLayer setContents:(id)[myImage CGImage]];
    [earthLayer setBounds:CGRectMake(240,360, 40, 200)];
    [earthLayer setPosition:CGPointMake(280, 280)];
    [earthLayer setName:@"earth"];

    [earthLayer addAnimation:[self animationForSpinning] forKey:@"Rahul"];//here animatin is being added to the layer..

    [[self.view layer] addSublayer:earthLayer];

    //[self spinLayer:earthLayer];

}

//the animation method which returns a CAAnimation.

- (CAAnimation*)animationForSpinning {

    // Create a transform to rotate in the z-axis
    float radians = DegreeToRadian( 360 );
    CATransform3D transform;
    transform = CATransform3DMakeRotation(radians, 0, 1.0,0, 1.0);

    // Create a basic animation to animate the layer's transform
    CABasicAnimation* animation;
    animation = [CABasicAnimation animationWithKeyPath:@"transform"];

    // Now assign the transform as the animation's value. While
    // animating, CABasicAnimation will vary the transform
    // attribute of its target, which for this transform will spin
    // the target like a wheel on its z-axis.
    animation.toValue = [NSValue valueWithCATransform3D:transform];

    animation.duration = 2;  // two seconds
    animation.cumulative = YES;
    animation.repeatCount = 10000;//  "forever"
    return animation;
}

A: Your problem appears to be that you are trying to use a 360 degree transform to animate your layer.  To Core Animation, a layer transformed by 360 degrees is exactly the same as the starting layer, so no animation is performed.
What you will want to do as animate around the transform.rotation.z keypath, as described in this answer.  This is a helper keypath that Core Animation provides, and because your starting and ending values (the angles through which to rotate) are different, Core Animation doesn't do the same sort of optimization you see with transforms.

A: You need to apply a perspective transform to your layer before animating it like this, otherwise the rotation your'e doing will not look right.
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / -2000;
set the transform on the layer to that, and then animate like you are.


text:
Q: Undefined variable notice in PHP when variable is in argument I am a beginner in PHP.  I have this function.
function create_group($name, $description, $invites){
global $link;

$name = mysqli_real_escape_string($link, $name);
$description = mysqli_real_escape_string($link, $description);
$names = mysqli_query($link, "SELECT `group_name` FROM `groups` WHERE `group_name` = '$name'");

if(mysqli_num_rows($names) == 0 && mysqli_num_rows($descriptions) == 0){
mysqli_query($link, "INSERT INTO `groups` (`group_name`, `group_description`) VALUES ('$name', '$description')");
}else{
print 'Group with that name/description already exists.';
}
$result = mysqli_query($link, "SELECT `group_id` FROM `groups` WHERE `group_name` = '$name'");
foreach($result as $resul){
foreach($resul as $resu){
$group_id = $resu;
}}}
$invitesarr = explode(',', $invites);
foreach($invites as $invite){
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
if(mysqli_num_rows($idres) == 0){
exit("1 or more of the users that you entered do(es) not exist!");
}else{
foreach($idres as $idarr){
foreach($idarr as $id){
mysqli_query($link, "INSERT INTO `group_members` (`group_id`, `user_id`, `confirmed?`) VALUES ('$group_id', '$id', 0)");
}}}}

$link is an existing database connection.  I get the variables for the argument from this page:
<?php
include "function_inc.php";
if(isset($_POST['name'], $_POST['description'], $_POST['invites'])){
create_group($_POST['group_name'], $_POST['description'], $_POST['invites']);
}
?>

<form action="new_group.php" method="post">

Group Name:
<input type="text" name="group_name" id="group_name" />

Invite...
<input type="text" name="invites" id="invites" />

Description:
<textarea name="description" id="description"></textarea>

<input type="submit" value="Create" />

</form>

I don't understand why I then get the following messages:
Notice: Undefined variable: invites in /home/peter/Documents/Logarithm/function_inc.php on line 49

Notice: Undefined variable: invites in /home/peter/Documents/Logarithm/function_inc.php on line 50

Please help me; I have been looking at this for hours!
Thanks in advance.
EDIT: Thank you, Benjamin Such!  I have now solved the variable message, however I have a new problem:  Warning: Invalid argument supplied for foreach().  Any help would be much appreciated.

A: The $invites variable is only available inside the function. It looks like your may have 1 extra } in your code
$group_id = $resu;
}}}

Which means you function declaration is finished.
Try indenting your code correctly so you can easily see where all of your brackets are.
Personally I would avoid using global variables, I would pass those variables into the function as a dependency.
Also, consider using PDO instead of the mysqli_* functions, as these are a little old school.
The following code isn't right
$invitesarr = explode(',', $invites);
foreach($invites as $invite){

$invites looks like it's a string, and you are trying to iterate through the string rather than through $invitesarr

A: I would better recommend that you start echo each and every statement one by one and immediately put and exit, so that you can observe which values you really have and where doesn't. that is the best debugging method.
For example:
function create_group($name, $description, $invites) {
echo $name;
exit;
.
.
.
}

A: I reorganized the code above:
function create_group($name, $description, $invites) {

  global $link;

  $name = mysqli_real_escape_string($link, $name);
  $description = mysqli_real_escape_string($link, $description);
  $names = mysqli_query($link, "SELECT `group_name` FROM `groups` WHERE `group_name` = '$name'");

  if(mysqli_num_rows($names) == 0 && mysqli_num_rows($descriptions) == 0) {
    mysqli_query($link, "INSERT INTO `groups` (`group_name`, `group_description`) VALUES ('$name', '$description')");
  } else {
    print 'Group with that name/description already exists.';
  }

  $result = mysqli_query($link, "SELECT `group_id` FROM `groups` WHERE `group_name` = '$name'");

  foreach($result as $resul) {
    foreach($resul as $resu) {
      $group_id = $resu;
    }
  }
}
$invitesarr = explode(',', $invites);
foreach($invites as $invite) {
  $idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
  if(mysqli_num_rows($idres) == 0) {
    exit("1 or more of the users that you entered do(es) not exist!");
  } else {
    foreach($idres as $idarr) {
      foreach($idarr as $id) {
        mysqli_query($link, "INSERT INTO `group_members` (`group_id`, `user_id`, `confirmed?`) VALUES ('$group_id', '$id', 0)");
      }
    }
  }
}

The problem is the foreach($invites as $invite) after the function definition. You want to loop through $invites, but this variable does not exist in the context. $invites exists only as an argument for the function. At least from what we can see from the code you posted us.
Edit: Sorry the error occured on a line before the foreach at $invitesarr = explode(',', $invites);


text:
Q: Users database structure that allows multiple simultaneous logins to same account A feature that is currently missing from one of my web apps is that a single user can only be logged in on one machine at a time. That is, if the users logs in elsewhere, his previous session will be logged off.
This is due to my current users table having the columns:
user: id, username, hash, salt... cursession

When each user logs in, the session ID is put into the "cursession" field and on each page-load, is checked against the database. As a result, only one "session" can be active at a time.

*

*Is the current table structure and method secure and standard? This system was pretty much improvised, and I have no professional experience.

*What would be a way to allow multiple simultaneous logins? I'm simply thinking of adding a "sessions" table with more userid-cursession relations, but what's the standard method for doing this?

A: I propose that you put the current logged in userid in the user's session (as a session variable), and drop the cursession field from the table altogether. You don't need to reinvent session handling since PHP already has it built-in.
That way the user can be logged in at multiple computers at once. Session variables are safe too, since they're not manipulated by the browser. The only thing kept in the browser is a session id which identifies the current session, all other data is stored on the server-side. The only thing that will happen if the user changes his browser cookies is that he will be logged out (start an empty session), so he can't force himself to log in as someone else.


text:
Q: How to add DLL's to C++ program (to access SQL database) I'm trying to use a C++ program to access a mySQL database on my localhost.
However I'm getting an error that I think is related to either a missing dll or a missing .lib file but I don't know how to add them?
I'm using the files/libraries from the mySQL Connector C++ 8.0 download.
Specifically how do I add the .dll files to my project to stop these errors?v
See below my current code!
Any help or suggestions would be fantastic, thank you!
#include <iostream>
#include "mysql_connection.h"
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"

using namespace std;

int main(void)
{

        sql::Driver* driver;
        sql::Connection* con;
        sql::Statement* stmt;
        sql::ResultSet* res;

        /* Create a connection */
        driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "root", "password");
        /* Connect to the MySQL test database */
        con->setSchema("test");

        stmt = con->createStatement();
        res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
        while (res->next()) {
            cout << "\t... MySQL replies: ";
            /* Access column data by alias or column name */
            cout << res->getString("_message") << endl;
            cout << "\t... MySQL says it again: ";
            /* Access column data by numeric offset, 1 is the first column */
            cout << res->getString(1) << endl;
        }
        delete res;
        delete stmt;
        delete con;

    }

The errors I'm getting are:
1>------ Build started: Project: AccessSQL_v1, Configuration: Debug x64 ------
1>accessSQL.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __cdecl sql::SQLString::~SQLString(void)" (__imp_??1SQLString@sql@@QEAA@XZ) referenced in function main
1>accessSQL.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __cdecl sql::SQLString::SQLString(char const * const)" (__imp_??0SQLString@sql@@QEAA@QEBD@Z) referenced in function main
1>accessSQL.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const & __cdecl sql::SQLString::asStdString(void)const " (__imp_?asStdString@SQLString@sql@@QEBAAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) referenced in function "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl std::operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class sql::SQLString const &)" (??6std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@AEBVSQLString@sql@@@Z)
1>accessSQL.obj : error LNK2019: unresolved external symbol __imp_get_driver_instance referenced in function main
1>C:\Users\LabPC\source\repos\AccessSQL_v1\x64\Debug\AccessSQL_v1.exe : fatal error LNK1120: 4 unresolved externals
1>Done building project "AccessSQL_v1.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ```


text:
Q: PHP PDO fetch returns false I keep thinking on that "error" but can't say why it returns false.
I've already done a SELECT for this but that is in an other file..
 $result = $db->dbh->prepare("SELECT thumbs FROM skill WHERE id=? LIMIT 1");
 $result->bindParam(1, $id);
    // $id == 4 here
 $result->execute();
 $row = $result->fetch(PDO::FETCH_ASSOC);
    // $row == false > why ?
 $thumbs = $row['thumbs'];

When i'm trying to run this on PhpMyAdmin, it works well.
I execute this code on an AJAX call, and using the same config.php file for the $db conection.
Another question:
    $sql_in = $db->dbh->prepare("INSERT INTO `voted_ip` (id, ip) VALUES (:id, :ip)");
    // $id == 4
    $sql_in->bindParam(":id", $id);
    $sql_in->bindParam(":ip", $ip, PDO::PARAM_STR);
    $sql_in->execute();

it inserts "0" and my ip. Why 0 ?
Please help

A: That is becasue of the $id which is a STRING is converted at 0 by MySQL.
$id = intval($id);


text:
Q: Copying charts from Excel to PPT I have an Excel with multiple sheets,each sheet having multiple charts.
I want to copy a chart from a specific sheet of an Excel, to a particular slideno in PPT; with specific dimensions (ie height and width) and positions using VBA.
I am able to do the same.
However,when im trying to do so; other shapes in the ppt are also getting re-positioned to the same position, along with the charts.
Here is my code
wkbk.Sheets("Sheet2").Shapes("chart1").Copy
ActivePresentation.Slides(1).Shapes.Range.Height = embededpicrange.Cells(1, 3).Value
ActivePresentation.Slides(1).Shapes.Range.Width = embededpicrange.Cells(1, 4).Value

How can we change the position of charts alone with the above code.
Need some guidance on this

A: This may be help you:
Sub copyChartToPP()

'Declare the needed variables
Dim newPP As PowerPoint.Application
Dim currentSlide As PowerPoint.Slide
Dim Xchart As Excel.ChartObject
'Check if PowerPoint is activate:
On Error Resume Next
Set newPP = GetObject(, "PowerPoint.Application")
On Error GoTo 0
'Open PowerPoint if not activate
If newPP Is Nothing Then
    Set newPP = New PowerPoint.Application
End If
'Create a new presentation in powerPoint
If newPP.Presentations.Count = 0 Then
    newPP.Presentations.Add
End If
'Display the PowerPoint presentation
newPowerPoint.Visible = True
'Locate Excel charts to paste into the new PowerPoint presentation
For Each Xchart In ActiveSheet.ChartObjects
'Add a new slide in PowerPoint for each Excel chart
    newPP.ActivePresentation.Slides.Add newPP.ActivePresentation.Slides.Count + 1,
ppLayoutText
    newPP.ActiveWindow.View.GotoSlide newPP.ActivePresentation.Slides.Count
    Set currentSlide =
newPP.ActivePresentation.Slides(newPP.ActivePresentation.Slides.Count)
'Copy each Excel chart and paste it into PowerPoint as an Metafile image
    Xchart.Select
ActiveChart.ChartArea.Copy
    currentSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
'Copy and paste chart title as the slide title in PowerPoint
    currentSlide.Shapes(1).TextFrame.TextRange.Text = cht.Chart.ChartTitle.Text
'Adjust the slide position for each chart slide in PowerPoint. Note that you can
'adjust the values to position the chart on the slide to your liking
    newPP.ActiveWindow.Selection.ShapeRange.Left = 25
    newPP.ActiveWindow.Selection.ShapeRange.Top = 150
    currentSlide.Shapes(2).Width = 250
    currentSlide.Shapes(2).Left = 500
 Next
 End Sub


text:
Q: async in chrome.webRequest.onBeforeRequest? Is it possible to work with async/await in the chrome API's webRequest.onBeforeRequest?
The following does work; From "working" I mean it does block/cancel the request as I expect.
chrome.webRequest.onBeforeRequest.addListener(
  function (details) {
    console.log("URL intercepted:", {url: details.url, type: details.type,});
    let match = details.url.match(/:\/\/(www\.)?someSiteThatIWantAvoidRawIp\.org(\/)?$/); // you are accessing this url on your chorme

    if (match)
    {
      console.log("URL blocked:", { url: details.url, type: details.type, match: match, });
      return { cancel: true };
    }
  },
  {
    urls: [
      "<all_urls>"
    ],
    types: ["main_frame",]
  },
  ["blocking",]
);

However, the following does not work; It is supposed to block/cancel the request after waiting the await, but the cancel doesn't work but the page shows up without a connection error.
chrome.webRequest.onBeforeRequest.addListener(
  async function (details) {
    console.log("URL intercepted:", {url: details.url, type: details.type,});
    let match = details.url.match(/:\/\/(www\.)?someSiteThatIWantAvoidRawIp\.org(\/)?$/);

    let ip = await axios.get('https://someSiteThatChecksMyIp.org', {}) // this gets my ip
        .then(r => {
            console.log(r);
            return r.data;
        })
        .catch(e => {
            console.log(e);
        });

    if (match)
    {
        if (ip == "123.123.123.123") // assume my raw ip
        {
            console.log("URL blocked:", { url: details.url, type: details.type, match: match, });
            return { cancel: true };
        }
    }
  },
  {
    urls: [
      "<all_urls>"
    ],
    types: ["main_frame",]
  },
  ["blocking",]
);

What's incorrect with my setup? Thanks.


text:
Q: how to fix imports and format for java using tool like goimports? Is there some tool like goimports for java? so that we could fix the codes quickly not depending on IDE.
I try this tool, but it only formats the codes, and does not work for entire dir recursively:
https://github.com/google/google-java-format


text:
Q: Javascript JSON.parse does not work after copy and paste the string I try to create a fallback for a homepage which uses yahoo-weatherdata.
I normally get the yahoo weatherdata as json with the $.getJSON function of jQuery. This works fine. I`m using the following code:
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2502265&format=json'

$.getJSON(url, function(r){

        result = r.query.results.channel;

        //Do things

    }).error(function(){
        //Fehler beim HTTP-Request
        debugger;

        //Fallback
        var fallback = JSON.parse('{"query":{"count":1,"created":"2013-02-12T23:58:55Z","lang":"en-US","results":{"channel":{"title":"Yahoo! Weather - Sunnyvale, CA","link":"http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html","description":"Yahoo! Weather for Sunnyvale, CA","language":"en-us","lastBuildDate":"Tue, 12 Feb 2013 2:56 pm PST","ttl":"60","location":{"city":"Sunnyvale","country":"United States","region":"CA"},"units":{"distance":"mi","pressure":"in","speed":"mph","temperature":"F"},"wind":{"chill":"60","direction":"320","speed":"8"},"atmosphere":{"humidity":"39","pressure":"30.32","rising":"2","visibility":"10"},"astronomy":{"sunrise":"7:01 am","sunset":"5:43 pm"},"image":{"title":"Yahoo! Weather","width":"142","height":"18","link":"http://weather.yahoo.com","url":"http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"},"item":{"title":"Conditions for Sunnyvale, CA at 2:56 pm PST","lat":"37.37","long":"-122.04","link":"http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html","pubDate":"Tue, 12 Feb 2013 2:56 pm PST","condition":{"code":"34","date":"Tue, 12 Feb 2013 2:56 pm PST","temp":"60","text":"Fair"},"description":"\n
\nCurrent Conditions:
\nFair, 60 F
\n
Forecast:
\nTue - Clear. High: 60 Low: 40
\nWed - Sunny. High: 64 Low: 42
\n
\nFull Forecast at Yahoo! Weather

\n(provided by The Weather Channel)
\n","forecast":[{"code":"31","date":"12 Feb 2013","day":"Tue","high":"60","low":"40","text":"Clear"},{"code":"32","date":"13 Feb 2013","day":"Wed","high":"64","low":"42","text":"Sunny"}],"guid":{"isPermaLink":"false","content":"USCA1116_2013_02_13_7_00_PST"}}}}}}');
        result = fallback.query.result.channel;
    });

But the fallback parsing does not work.
I get the error:
SyntaxError: Unexpected token (Chrome)
The string I try to parse is just a copy and paste of the content of: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2502265&format=json
JSONLint tells me, that everything is ok:
http://jsonlint.com/?json={%22query%22:{%22count%22:1,%22created%22:%222013-02-13T00:12:44Z%22,%22lang%22:%22en-US%22,%22results%22:{%22channel%22:{%22title%22:%22Yahoo!%20Weather%20-%20Sunnyvale,%20CA%22,%22link%22:%22http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html%22,%22description%22:%22Yahoo!%20Weather%20for%20Sunnyvale,%20CA%22,%22language%22:%22en-us%22,%22lastBuildDate%22:%22Tue,%2012%20Feb%202013%202:56%20pm%20PST%22,%22ttl%22:%2260%22,%22location%22:{%22city%22:%22Sunnyvale%22,%22country%22:%22United%20States%22,%22region%22:%22CA%22},%22units%22:{%22distance%22:%22mi%22,%22pressure%22:%22in%22,%22speed%22:%22mph%22,%22temperature%22:%22F%22},%22wind%22:{%22chill%22:%2260%22,%22direction%22:%22320%22,%22speed%22:%228%22},%22atmosphere%22:{%22humidity%22:%2239%22,%22pressure%22:%2230.32%22,%22rising%22:%222%22,%22visibility%22:%2210%22},%22astronomy%22:{%22sunrise%22:%227:01%20am%22,%22sunset%22:%225:43%20pm%22},%22image%22:{%22title%22:%22Yahoo!%20Weather%22,%22width%22:%22142%22,%22height%22:%2218%22,%22link%22:%22http://weather.yahoo.com%22,%22url%22:%22http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif%22},%22item%22:{%22title%22:%22Conditions%20for%20Sunnyvale,%20CA%20at%202:56%20pm%20PST%22,%22lat%22:%2237.37%22,%22long%22:%22-122.04%22,%22link%22:%22http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html%22,%22pubDate%22:%22Tue,%2012%20Feb%202013%202:56%20pm%20PST%22,%22condition%22:{%22code%22:%2234%22,%22date%22:%22Tue,%2012%20Feb%202013%202:56%20pm%20PST%22,%22temp%22:%2260%22,%22text%22:%22Fair%22},%22description%22:%22\n%3Cimg%20src=\%22http://l.yimg.com/a/i/us/we/52/34.gif\%22/%3E%3Cbr%20/%3E\n%3Cb%3ECurrent%20Conditions:%3C/b%3E%3Cbr%20/%3E\nFair,%2060%20F%3CBR%20/%3E\n%3CBR%20/%3E%3Cb%3EForecast:%3C/b%3E%3CBR%20/%3E\nTue%20-%20Clear.%20High:%2060%20Low:%2040%3Cbr%20/%3E\nWed%20-%20Sunny.%20High:%2064%20Low:%2042%3Cbr%20/%3E\n%3Cbr%20/%3E\n%3Ca%20href=\%22http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html\%22%3EFull%20Forecast%20at%20Yahoo!%20Weather%3C/a%3E%3CBR/%3E%3CBR/%3E\n(provided%20by%20%3Ca%20href=\%22http://www.weather.com\%22%20%3EThe%20Weather%20Channel%3C/a%3E)%3Cbr/%3E\n%22,%22forecast%22:[{%22code%22:%2231%22,%22date%22:%2212%20Feb%202013%22,%22day%22:%22Tue%22,%22high%22:%2260%22,%22low%22:%2240%22,%22text%22:%22Clear%22},{%22code%22:%2232%22,%22date%22:%2213%20Feb%202013%22,%22day%22:%22Wed%22,%22high%22:%2264%22,%22low%22:%2242%22,%22text%22:%22Sunny%22}],%22guid%22:{%22isPermaLink%22:%22false%22,%22content%22:%22USCA1116_2013_02_13_7_00_PST%22}}}}}}

Does somebody have an idea what is going wrong?
Thank you!

A: You forgot to escape apostrophes (there are none) and backslashes. If you have a JS string like '{"a":"b\"c"}' it's the same as '{"a":"b"c"}' - which is obviously invalid JSON.
Instead of pasting an unescaped JSON string and calling JSON.parse on it, just paste the pure JSON as an object literal:
var fallback = {"query":{"count":1,"created":…},…};

A: take your string, and try this with it:  alert(mything.query.results.channel.title); instead of the alert(mything.query.result.channel.title); which is not defined in that string
SO
 result = fallback.query.results.channel;


text:
Q: How to get Database script for Mysql? I have Mysql database. I want to take only the skeleton of my database i.e.I want only the scripts to create Database and  tables. Not the entire database back up which comes with database structure and data.
Please Help me. I Use Mysql 5.0

A: mysqldump --all-databases --no-data

A: From MySql export schema without data:

You can do with the --no-data option with mysqldump command
mysqldump -u root -p --no-data dbname > schema.sql

Jim helpfully contributes:

consider using the --single-transaction option if you don't want or can't do table locks.

A: Here is my summary about mysql dumping commands, hope to help you
backup the entire database

mysqldump -uroot -p db_name > /home/bob/my.sql

backup single table

mysqldump -uroot -p db_name table_name > /home/bob/table.sql

backup only database structure,

mysqldump -uroot -p db_name -d > /home/bob/structure.sql

backup only database data

mysqldump -uroot -p db_name -t > /home/bob/data.sql

How to execute the exported sql file? See the following

mysql -uroot -p db_name < /home/bob/my.sql

another way,
Log into mysql, then

mysql> use db_name;
mysql> source /home/bob/my.sql;


text:
Q: regex to parse csv I'm looking for a regex that will parse a line at a time from a csv file.  basically, what string.readline() does, but it will allow line breaks if they are within double quotes.
or is there an easier way to do this?

A: Using regex to parse CSV is fine for simple applications in well-controlled CSV data, but there are often so many gotchas, such as escaping for embedded quotes and commas in quoted strings, etc.   This often makes regex tricky and risky for this task.
I recommend a well-tested CSV module for your purpose.
--Edit:-- See this excellent article, Stop Rolling Your Own CSV Parser!

A: The FileHelpers library is pretty good for this purpose.
http://www.filehelpers.net/

A: Rather than relying on error prone regular expressions, over simpified "split" logic or 3rd party components, use the .NET framework's built in functionality:
Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\MyFile.csv")

    Reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited

    Dim MyDelimeters(0 To 0) As String
    Reader.HasFieldsEnclosedInQuotes = False
    Reader.SetDelimiters(","c)

    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.ReadFields()
            Dim currentField As String
            For Each currentField In currentRow
                MsgBox(currentField)
            Next
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    End While
End Using


text:
Q: Is there a way to do symbolic links to the blob data when using Azure Storage to avoid duplicate blobs? I have a situation where a user is attaching files within an application, these files are then persisted to Azure Blob storage, there is a reasonable likelihood that there are going to be duplicates and I want to put in place a solution where duplicate blobs are avoided.
My first thought is to just name the blob as filename_hash but that only captures a subset of duplicates, then filesize_hash was then next thought.
In doing this though it seems like I am losing some of the flexibility of the blob storage to represent the position in a hierarchy of the file, see: Windows Azure: How to create sub directory in a blob container
So I was looking to see if there was a way to create a blob that referenced the blob data i.e. some for of symbolic link but couldn't find what I wanted.
Am I missing something or should I just go with filesize_hash method and store my hierarchy using an alternative method.

A: No, there's no symbolic links (source: http://social.msdn.microsoft.com/Forums/vi-VN/windowsazuredata/thread/6e5fa93a-0d09-44a8-82cf-a3403a695922).
A good solution depends on the anticipated size of the files and the number of duplicates. If there aren't going to be many duplicates, or the files are small, then it may actually be quicker and cheaper to live with it - $0.15 per gigabyte per month is not a great deal to pay, compared to the development cost! (That's the approach we're taking.)
If it was worthwhile to remove duplicates I'd use table storage to create some kind of redirection between the file name and the actual location of the data. I'd then do a client-side redirect to redirect the client's browser to download the proper version.
If you do this you'll want to preserve the file name (as that will be what's visible to the user) but you can call the "folder" location what you want.

A: Another solution to keep all structure of your files but still provide a way to do "symbolic links" could be as follows, but as in the other answer the price might be so small that its not worth the effort of implementing it.
I decided in similar setup to just store the md5 of each uploaded file in a table and then in a year go back and see how many duplicates that got uploaded and how much storage that could be saved. It will at that time make it easy to evaluate if its worth implementing a solution for symbolic links.
The downside of maintaining it all in table storage is that you get a limited query API to your blobs. Instead i would suggest to use the Metadata on blobs for creating links. (meta data turns in to normal headers on the requests when using REST API etc).
So for duplicate blobs, just keep one of them and store a link header telling where the data is.
blob.Metadata.Add("link", dataBlob.Name);
await blob.SetMetadataAsync();
await blob.UploadTextAsync("");

at this point the blob now takes up no data but is still present in storage and will be returned when listing blobs.
Then when accessing data you simply would have to check if a blob has a "link" metadata set or with rest, check if a x-ms-meta-link header is present and then read the data from there instead.
blob.Container.GetBlockBlobReference(blob.Metadata["link"]).DownloadTextAsync()

or any of the other methods for accessing the data.
Above is just the basics and I am sure you can figure out the rest if this is used.


text:
Q: Is there any way to bypass the enchantment limit on Minecraft? The maximum enchantment limit (with commands/NBT) is 256 on version 1.19.2. I was wondering if somehow I could bypass that?
I saw an answer saying you need to edit the code, how do I need to edit the code?

A: Depending on your use-case, you might get away with the /enchant command. On Java Edition, the level can be any integer between 0 and 2147483647.
The weakness of this approach is that it targets a player, who would need to be holding the item in their hand to receive the enchantment. This may or may not affect you.
If you need to use /give, you may need to create a mod and add a new command that allows greater enchantment levels. I recommend learning Forge. The Forge team maintains a good tutorial to teach you how to create basic mods. It's not a Java tutorial though, so if you don't know how to program, you may need to start elsewhere. If you have a specific question about mod creation, that would be better suited as a different question.

It looks like the changes to /give happened in 1.17. According to the history section of the format page, 1.17 was when it was clamped to 255.


text:
Q: Cors issue with node js and React Js I have tried all solutions, but doesn't work, and i don't have any idea how i can do to solve this problem

Access to XMLHttpRequest at 'https://api.bolaosolidario.com.br/afiliado/' from origin 'https://app.bolaosolidario.com.br' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried to reinstall cors, change my nginx configuration, change my cors in my api configuration, but doesn't work. The cors issue, occurs after a while that the user already has the site open, and i don't know what can cause this, my server configuration:
const express = require('express')
const routes = require('./routers')
const cors = require('cors')
const app = express();
require("dotenv").config();
require('./database')
/*const corsOptions = {
    origin: '*',
    methods: ['GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'device-remember-token', 'Access-Control-Allow-Origin', 'Origin', 'Accept', ' Access-Control-Allow-Headers' , 'Access-Control-Allow-Methods'],
    optionSuccessStatus: 200,
};*/

app.use(cors())
app.use(express.json())
app.use(routes)
app.use(express.static('public'));
app.use('/images', express.static('images'));
app.listen(process.env.PORT)

I tried with two ways, i tried to use de cors options and a tried to use just the cors, but both configurations give me the same error.
my nginx configuration
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name api.bolaosolidario.com.br;
    root /home/forge/api.bolaosolidario.com.br/dist;

     # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/api.bolaosolidario.com.br/1377016/server.crt;
    ssl_certificate_key /etc/nginx/ssl/api.bolaosolidario.com.br/1377016/server.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    ssl_dhparam /etc/nginx/dhparams.pem;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";
    #add_header Access-Control-Allow-Origin *;
    #add_header Access-Control-Allow-Headers "Authorization";
    #add_header Access-Control-Allow-Headers "content-type";
    #add_header Access-Control-Allow-Headers "Access-Control-Allow-Origin";

    index index.html index.htm index.nginx-debian.html;

    # FORGE CONFIG (DO NOT REMOVE!)
    include forge-conf/api.bolaosolidario.com.br/server/*;

    location / {
        proxy_pass http://localhost:8080; # Port number of node http server
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header 'Access-Control-Allow-Origin' '*';
        proxy_set_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, DELETE, UPDATE';
    }

    access_log off;
    error_log  /var/log/nginx/api.bolaosolidario.com.br-error.log error;

}

And i have tried to use without the cors, but return the same error, in different routers.

A: to use CORS, you can use the express direct method like this :
const express = require('express')

const app = express();

app.use((req, res, next) => {
    res.append('Access-Control-Allow-Origin', '*');
    res.append('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS');
    res.append('Access-Control-Allow-Headers', 'Content-Type, authorization');
    next();
});

It works for me, I think it could solve your problem. Nginx doesn't need any particular configuration to work with CORS, the basic one or the one generated by certbot works correctly


text:
Q: Cookie based authentication on multiple 'localhost' Asp.Net Core Sites Scenario is only an issue on a development machine.
I have multiple different and entirely independent ASP.NET Core 2.2 projects running on my dev machine under "localhost".
Once I successfully authenticate and log in on one project, I can no longer log in to the other projects.  I'm assuming it's something to do with the auth cookies.
All projects have the same identical and basic Identity authentication.
    services.AddAuthentication();

    services.ConfigureApplicationCookie(opt =>
    {
        opt.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.None;
        opt.Cookie.HttpOnly = true;
        opt.Cookie.Expiration = TimeSpan.FromHours(4);
        opt.ExpireTimeSpan = TimeSpan.FromHours(4);
    });

The sign-in call is succeeding:
result = await _signInManager.PasswordSignInAsync(portal.ID, model.Username, model.Password, model.RememberMe, true, loggedInUser);
However, once the user is redirected to the home page, which required authentication, I see the following in the debug output:
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed.
... and the user is kicked back to the login page.
Is there a way around this issue?

A: I would consider running your sites under different domains, and then mapping the domains to localhost (or rather, 127.0.0.1) in your hosts file.
This question explains the technique: Add subdomain to localhost URL
Here is an article which explains the hosts file for different operating systems: https://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/

A: Problem solved.
services.ConfigureApplicationCookie(opt =>
{
    opt.Cookie.Name = "Unique Value Per App";
});

All I have to do is post on SO and the problem solves itself!


text:
Q: How do I extract certain rows from a list based on a string of characters I have a string of characters:x
"A" "B" "C"

Also a list of two variables:y
m A
n B
n D
q D
m B

How can I get a subset of y based on x like this:
m A
n B
m B

A: You can use %in% to subset y.
y[y$b %in% x,]
#  a b
#1 m A
#2 n B
#5 m B

Data:
x <- c("A", "B", "C")
y <- data.frame(a=c("m", "n", "n", "q", "m"), b=c("A", "B", "D", "D", "B"))

A: You can use filter, if you are using a data.frame
df <- read_table2("x1 x2
m A
n B
n D
q D
s B")
df %>% filter(x2 == "A" | x2 == "B")


text:
Q: Jenkins build with parameters only calls master branch I am building a gitlab/jenkins stack, and have connected my gitlab to jenkins. Now when I want to build my test item with a parameter rather than "master", Jenkins only uses "master" branch to build and test. What am I missing? My Jenkins version is 2.150 (latest LTE) and all of the plugins are up to date.

A: OK, I found the problem:
There is an option in {Your_Project_Name} > Configure > Source Code Management > Branches to Build
It was set to "master", I deleted it and then I implemented the solution proposed here as the accepted answer, and then it worked.


text:
Q: Sharing a folder in vagrant removes guest folder contents Still learning a bit about Vagrant, but here it goes. I have a pretty standard guest vm that has some software installed. I would like to access a few directories within the guest in a read/write fashion. So I added the config for a shared folder as follows:
config.vm.share_folder "test", "/home/vagrant/test", "./test"

Keep in mind I have content in my test folder. I need to be able to view and update that from the host. However, when I 'vagrant reload' with the empty host directory called test, all of the content on my guest is removed.
Is it possible to create a shared folder in which I can access content on the guest without destroying existing content?

A: In case someone else comes by this problem, shared folders are indeed synced in both directions (from host to guest and from guest to host) but it depends on the type option.
In Linux this works out of the box without specifying the type option:

*

*Log into the virtual machine.

*Add a file in your shared folder e.g. /home/vagrant/somefile.

*Check your host folder and you will find the new file.

The problem comes in when you try to sync a folder after provisioning the virtual machine. In such case the guest folder will be sync'd to the host folder, which is empty.
Read the different types of shared folders.


text:
Q: Unit test own validation function in Angular I'm new to testing and starting out writing a own validation method for my Angular app. But I cant figure it out how to test it with Karma. What is the right way to set a value and test it against my validation method?
I get following error
Property 'valid' does not exist on type 'void'.
Please be patient with me but I don't grasp why I get this error.
The form
this.carForm = this.fb.group({
    car: this.fb.array([
        this.fb.group({
            id: car.id,
            properties: this.fb.group({
                color: 'blue',
                vinNumber: ['', ValidationService.isValidVinNumber]
            })
        })
    ]),
    registrationDate: '2011-11-12',
    howManyOwners: car.previousOwners,
    })
});
this.carForm.valueChanges.subscribe(value => {
});

The validation method
static isValidVinNumber(formControl: FormControl) {
    if (formControl && formControl.value) {
        if (formControl.value.length !== 14) {
            return false;
        }
    } else {
        return null;
    }
}

My test case not working
beforeEach(() => {
    fixture = TestBed.createComponent(CarComponent);
    component = fixture.componentInstance;
}
........
it('should be possible to post empty vin number', () => {
    const iccNumber = component.carForm.get(['car', 0, 'properties', 'vinNumber']);
    expect(iccNumber.valid).toBeTruthy();
});


text: Q: Getting 0 notifications from UNUserNotificationCenter in Notification Service Extension I am trying to read all the delivered notifications from notifications service extension but I am getting 0 notifications from UNUserNotificationCenter.current().getDeliveredNotifications. How to resolve this?


text:
Q: Reference issue with Javascript I have an array of objects cached on client side using JS array.
var scannerDictionary = new Array();            //Holds all scanners unmodified
var modifiedScannerDictionary = new Array();    //Holds all scanners with modified values

The properties of each object is set/changed using GUI and updated in the object. Each object contains list of InputParameters (array of Parameter class containing Name, Value and other members).
Please have a look on GUI.

Below is the code i used to render the controls -
function renderControls(scannerId) {
        var currentScanner = modifiedScannerDictionary[scannerId];

        //Render Input Parameters
        $("#tblInputCriteria").find('tr:gt(5)').remove();
        for(var i=0;i<currentScanner.InputParameters.length;i++) {
            var propType = currentScanner.InputParameters[i].DataType;
            var inParName = currentScanner.InputParameters[i].Name;

            switch(propType) {
                case 0: //Number
                    var eRow1 = $("#tblInputCriteria").find('#emptyNumRow').clone();
                    $(eRow1).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
                    $(eRow1).appendTo($('#tblInputCriteria'));
                    var prop1 = $(eRow1).find('#InNumPropName');
                    $(prop1).attr('id', 'InNumPropName_'+currentScanner.InputParameters[i].Name);
                    var propName1 = currentScanner.InputParameters[i].Name;
                    $(prop1).html(propName1);
                    var propVal1 = $(eRow1).find('#InNumPropValue');
                    $(propVal1).attr('id', 'InNumPropValue_'+currentScanner.InputParameters[i].Name);
                    $(propVal1).val(currentScanner.InputParameters[i].Value);
                    $(propVal1).blur(function () {
                        if(!ValidateNumber(this, propName1)) {
                            alert('Value should be numeric in ' + propName1);
                            setTimeout(function() {$(propVal1).focus();}, 100);
                        }else {
                            UpdateData(currentScanner.Id, propName1, $(propVal1).val());
                        }
                    });

                    break;
                case 1: //String
                    var eRow2 = $("#tblInputCriteria").find('#emptyStrRow').clone();
                    $(eRow2).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
                    $(eRow2).appendTo($('#tblInputCriteria'));
                    var prop2 = $(eRow2).find('#InStrPropName');
                    $(prop2).attr('id', 'InStrPropName_'+currentScanner.InputParameters[i].Name);
                    var propName2 = currentScanner.InputParameters[i].Name;
                    $(prop2).html(propName2);
                    var propVal2 = $(eRow2).find('#InStrPropValue');
                    $(propVal2).attr('id', 'InStrPropValue_'+currentScanner.InputParameters[i].Name);
                    $(propVal2).val(currentScanner.InputParameters[i].Value);
                    $(propVal2).blur(function () {
                        UpdateData(currentScanner.Id, propName2, $(propVal2).val());
                    });
                    break;
                case 2: //Boolean
                    var eRow3 = $("#tblInputCriteria").find('#emptyBoolRow').clone();
                    $(eRow3).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
                    $(eRow3).appendTo($('#tblInputCriteria'));
                    var prop3 = $(eRow3).find('#InBoolPropName');
                    $(prop3).attr('id', 'InBoolPropName_'+currentScanner.InputParameters[i].Name);
                    var propName3 = currentScanner.InputParameters[i].Name;
                    $(prop3).html(propName3);
                    var propVal3 = $(eRow3).find('#InBoolPropValue');
                    $(propVal3).attr('id', 'InBoolPropValue_'+currentScanner.InputParameters[i].Name);
                    $(propVal3).val(currentScanner.InputParameters[i].Value);
                    $(propVal3).blur(function () {
                        UpdateData(currentScanner.Id, propName3, $(propVal3).val());
                    });
                    break;
    }
}
}

PROBLEM:
The problem here is of the variables inside switch working as reference variable. So the UpdateData() function gets the last Name for similar type properties. i.e. if fields are of Number type then only the last property is updated by UpdateData() method.
Can anybody help me out solve this issue. Thanks for sharing your time and wisdom.

A: Try something like the following.  Its a tad overkill, but will bind the values of the variables to the closures.
var fnOnBlur = (function(thePropName, thePropVal) {
    return function () {
        if(!ValidateNumber(this, thePropName)) {
            alert('Value should be numeric in ' + thePropName);
            setTimeout(function() {$(thePropVal).focus();}, 100);
        }else {
            UpdateData(currentScanner.Id, thePropName, $(thePropVal).val());
        }
    };
})(propName1, propVal1);
$(propVal1).blur( fnOnBlur );

The link that Felik King supplied has much more detailed discussion.


text:
Q: Nginx safest configuration for NodeJS app in CentOS I have multiple NodeJS application running on different ports.
I needed each one of them to work through a subdomain using Nginx, for example instead of example.com:4001 the user can work on app1.example.com
I found two solutions which seem to fit, however the second solution does not work yet and even if it worked I do not know if it would be more secure than the first solution or not.
Should I stick with Solution 1 or give more effort to Solution 2 ?

Solution 1 (Works)

server {
    listen 80;
    server_name app1.example.com;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:4001";
    }
}

Solution 2 (not working yet)
404 Not Found nginx

server {
    listen 80;
    server_name app1.example.com;

    location = / {
    proxy_pass http://127.0.0.1:4001;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    }
}

Operating System: CentOS 6.9 (final)
Nginx: 1.12.2
Custom conf file: /etc/nginx/conf.d/nodeapps.conf

A: You will need one server {}block per subdomain as described in the documentation. http://nginx.org/en/docs/http/server_names.html
For example
server {
    listen 80;
    server_name app1.example.com;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:4001";
    }
}
server {
    listen 80;
    server_name app2.example.com;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:4002";
    }
}

I also strongly suggest to use the upstream module for the backends. http://nginx.org/en/docs/http/ngx_http_upstream_module.html


text:
Q: Unmarshalling with complex type I'm having trouble unmarshalling XML that represents an invoice in this form:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Body>
        <Response xmlns="Lamp">
            <Result>
                <Title>The Title</Title>
                <Lines>
                    <anyType xsi:type="InvoiceLine">
                        <Name>Name One</Name>
                        <Quantity>1.0000</Quantity>
                    </anyType>
                    <anyType xsi:type="InvoiceLine">
                        <Name>Name Two</Name>
                        <Quantity>2.0000</Quantity>
                    </anyType>
                </Lines>
            </Result>
        </Response>
    </soap:Body>
</soap:Envelope>

The Invoice class:
@XmlAccessorType(XmlAccessType.FIELD)
public class Invoice {
    public String Title;
    public List<InvoiceLine> Lines;
}

The InvoiceLine class:
@XmlAccessorType(XmlAccessType.FIELD)
public class InvoiceLine extends anyType {
    public String Name;
    public float quantity;
}

And a abstract class for anyType:
public abstract class anyType {}

This is the code I'm using to do the unmarshalling:
public static void main(String[] args) throws Exception {

    InputStream is = new FileInputStream("input.xml");

    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(is);

    xsr.nextTag();
    while(!xsr.getLocalName().equals("Result")) {
        xsr.nextTag();
    }

    JAXBContext jc = JAXBContext.newInstance(Invoice.class, InvoiceLine.class);
    javax.xml.bind.Unmarshaller unmarshaller = jc.createUnmarshaller();

    JAXBElement<Invoice> jb = unmarshaller.unmarshal(xsr, Invoice.class);
    xsr.close();

    System.out.println(jb.getValue());

}

The problem is the Lines list only contains 1 entry with Name=null and quantity=0.0.
-- Edit:
I've just tried adding XmlElement and XmlElementWrapper annotations to both classes, the only change is that the Lines list has no elements.
Modified Invoice:
@XmlAccessorType(XmlAccessType.FIELD)
public class Invoice {
    @XmlElement(name = "Title")
    public String Title;
    @XmlElement(name = "anyType")
    @XmlElementWrapper(name = "Lines")
    public List<InvoiceLine> Lines;
 }

Modified InvoiceLine:
@XmlAccessorType(XmlAccessType.FIELD)
public class InvoiceLine extends anyType {
    @XmlElement(name = "Name")
    public String Name;
    @XmlElement(name = "Quantity")
    public float Quantity;
}

-- Edit:
I've just tried making the attributes lower case, but still no luck.


text:
Q: How to remove empty column with heading? I have column headings like Material 1, Material 2,... Material 15. Below these headings if there is no data i.e. if the column is empty. Then the entire column should be deleted automatically.
Example : if the Material 5, Material 7, up to Material 15 columns are empty then they should be deleted.
I was trying the below code, however its not working till Material 15 column it stops after deleting 2 or 3 columns. Kindly help me.

Sub clearcol()
On Error Resume Next
 Dim lRealLastRow, lRealLastCol As Long
    lRealLastRow = Cells.Find("*", Range("A1"), xlValues, , xlByRows, xlPrevious).Row
    lRealLastCol = Cells.Find("*", Range("A1"), xlValues, , xlByColumns, xlPrevious).Column
    For i = 1 To lRealLastCol
        If lRealLastRow - WorksheetFunction.CountBlank(Intersect(Columns(i), ActiveSheet.UsedRange)) <= 1 Then _
            Columns(i).EntireColumn.Delete
    Next i

End Sub

A: If you delete one column, and increment the counter at the same time, you skip some columns. To fix it, reverse the order of For loop
For i = lRealLastCol To 1 Step -1

A: Consider this alternative:
Sub KolumnKiller()
    Dim N As Long, i As Long, Kount As Long
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    N = Cells(1, Columns.Count).End(xlToLeft).Column
    For i = N To 1 Step -1
        Kount = wf.CountA(Cells(1, i).EntireColumn)
        If Kount = 1 Or Kount = 0 Then
            Cells(1, i).EntireColumn.Delete
        End If
    Next i
End Sub


text:
Q: How to adjust multiple conditions in one query? See I can pass 2 parameters to the procedure to filter my search i.e. ComplainantName or ComplaintSubject or (ComplainantName AND ComplaintSubject)
So can I adjust in this query which just works with ComplainantName?
@ComplainantName varchar(100),
@ComplaitSubject varchar(MAX)

Select * from ComplaintsInfo
where ComplainantName= @ComplainantName

I am naive and trying to sort it.
NOTE: Both or one of them can be empty sometimes i.e. user choose to pass only ComplaintSubject so in that case ComplainantName would be ""

A: You could use:
DECLARE @ComplainantName varchar(100),
        @ComplaitSubject varchar(MAX);

Select *
from ComplaintsInfo
where (ComplainantName = @ComplainantName OR @ComplainantName IS NULL)
  AND (ComplaitSubject = @ComplaitSubject OR @ComplaitSubject IS NULL);

--  @ComplainantName/Subject = '' if empty string indicates missing value

When you want to search only using one parameter pass second as NULL.
This way you can filter using:
╔══════════════════╦══════════════════╦═════════════════════════════════════════════════════════════════╗
║ @ComplainantName ║ @ComplaitSubject ║                             result                              ║
╠══════════════════╬══════════════════╬═════════════════════════════════════════════════════════════════╣
║ NULL             ║ NULL             ║ all                                                             ║
║ NULL             ║ val              ║ records with ComplaitSubject='val'                              ║
║ val              ║ NULL             ║ records with ComplainantName='val'                              ║
║ val1             ║ val2             ║ records with ComplaitSubject='val1' and  ComplainantName='val2' ║
╚══════════════════╩══════════════════╩═════════════════════════════════════════════════════════════════╝

EDIT:

I also tried this and seems working for now, Is it ok ? Select * from ComplaintsInfo where ComplainantName like '%'+ @ComplainantName +'%' AND COmplaintSubejct like '%'+@ComplaintSubject+'%'

Yes you can change   ComplainantName = @ComplainantName with ComplainantName like '%'+ @ComplainantName +'%' but you should be aware that expression starting with wildcard is nonSARGable. If it is index on that column query optimizer will skip it.
Select *
from ComplaintsInfo
where (ComplainantName like '%'+@ComplainantName+'%' OR @ComplainantName IS NULL)
  AND (ComplaitSubject like '%'+@ComplaitSubject+'%' OR @ComplaitSubject IS NULL);

You could also consider using FULL-TEXT INDEX for string searching.


text:
Q: Class alias vs Variable class name I'm creating my own PHP framework (for the learning experience), and I can't decide which of these would be a better practice.

*

*Create a Registry class that has the name of every class. Other classes will call the registry to find the class name.

*Create an AliasRegistry class that will create aliases for every class.
When accessing a class name with the first design, my code will look like this:
    $delegateClass = $this->registry->delegate;
    $object = new $delegateClass;

When accessing a class with the second design, my code will look like this:
    $object = new _NI_ALIAS;

It will also allow me to dynamically extend other classes and implement interfaces
    class Template implements _NI_ALIAS

The second one makes a lot more sense to me, especially since I can just include it in the framework's namespace; but for some reason, I see people labeling this as pad practice, since it can affect things globally.
Which would you say is a better practice?


text:
Q: Use Android phone as multi-boot usb I have a usb key that I use quite often. I have loaded Yumi on it and use it to boot various live cd's and tools on the PC's that I am troubleshooting. I carry it pretty much everywhere I go. I also carry my Android phone everywhere I go, and it has a 32 GB sd card in it. I would like to be able to use the sd card and a USB cable just as I have used the USB key in the past.
Has anyone figured out how to boot from an image on an SD card?

A: Try DriveDroid https://play.google.com/store/apps/details?id=com.softwarebakery.drivedroid
I've used it to boot Live Ubuntu, Ultimate Boot CD "UBCD" and Trinity Rescue. When I used it, it didn't allow booting using UEFI. That may have changed now.


text:
Q: Play Framework Encrypting Passwords in application.conf I'm using Play 2.1.x and I'm wondering if there is a way to encrypt passwords that might be needed for database access? I have a configuration entry that stores the database server url, user credentials for accessing the database and I do not want to leave my password as plain text. How can I have my user credentials encrypted? I want to later un-encrypt when I use them within the context of my Play server. Any pointers?

A: The problem is where would you store the decryption key.  If you store it in the same (or similar) configuration file, the entire exercise is moot.
I am guessing that you do not want to put the plain text password in application.conf to avoid having it show up in version control system.  One way of mitigating that kind of leak is to have a different store for sensitive configuration files for production systems (a different repository that has fewer accessors works nicely).


text:
Q: Magento2. Use non AMD javascript scripts I am trying to load an external javascript in my Magento 2.1.x installation in this way:
    <script type="text/javascript">

        var _iub = _iub || [];
        _iub.csConfiguration = {
            siteId: xxx,
            consentOnScrollDelay : 1500,
            callback: {
                onConsentGiven: function(){
                    dataLayer.push({'event': 'iubenda_consent_given'});
                }
            },
            cookiePolicyId: xxx,
            lang: "it",
            banner: {
                fontSize: "13", applyStyles: false,
                html:"Privacy policy HTML"
            }
        };
    </script>
    <script type="text/javascript" src="//cdn.iubenda.com/cookie_solution/safemode/iubenda_cs.js" charset="UTF-8" async></script>

Including the script //cdn.iubenda.com/cookie_solution/safemode/iubenda_cs.js breaks all the other javascript requirejs functionalities.
I tried to include the script in the requirejs way, editing my theme requirejs-config.js file:
var config = {
    "map" : {
        "*" : {
            ...
            'iubenda' : '//cdn.iubenda.com/cookie_solution/safemode/iubenda_cs.js'
        }
    }
};

and changing its inclusion in this way
<script type="text/javascript">
        var _iub = _iub || [];
        _iub.csConfiguration = {
            siteId: xxx,
            consentOnScrollDelay : 1500,
            callback: {
                onConsentGiven: function(){
                    dataLayer.push({'event': 'iubenda_consent_given'});
                }
            },
            cookiePolicyId: xxx,
            lang: "it",
            banner: {
                fontSize: "13", applyStyles: false,
                html:"Privacy policy HTML"
            }
        };
    </script>

    <script>
        require(['iubenda'], function(){});
    </script>

But this does not solve the errors.
The common error thrown is
Uncaught Error: Mismatched anonymous define() module: function (){return l}

How can I add external non AMD scripts to my Magento 2.1.x without breaking the requirejs functionalities?

A: You must create the javascript as follows:
<script>
    var _iub = _iub || [];
    _iub.csConfiguration = {
        siteId: xxx,
        consentOnScrollDelay: 1500,
        callback: {
            onConsentGiven: function () {
                dataLayer.push({'event': 'iubenda_consent_given'});
            }
        },
        cookiePolicyId: xxx,
        lang: "it",
        banner: {
            fontSize: "13", applyStyles: false,
            html: "Privacy policy HTML"
        }
    };
    $.getScript("//cdn.iubenda.com/cookie_solution/safemode/iubenda_cs.js");
</script>

You must remove ... requirejs-config.js
Old:
var config = {
    "map" : {
        "*" : {
            ...
            'iubenda' : '//cdn.iubenda.com/cookie_solution/safemode/iubenda_cs.js'
        }
    }
};

New:
var config = {
    "map" : {
        "*" : {
            'iubenda' : '//cdn.iubenda.com/cookie_solution/safemode/iubenda_cs.js'
        }
    }
};


text:
Q: Browser native scroll function: how to check compatibility The function scroll in "most" browsers can be used, but it seems that it can be "overloaded". From the compatibility tab, you'll see that some browsers support
element.scroll(scrollToOptions)
whereas others only support
element.scroll(x, y)
How can I check which method is supported (despite it having the same name) in the current browser?

A: var isSmoothScrollSupported = 'scrollBehavior' in document.documentElement.style;

var scrollToOptions = {
  top: 100,
  left: 100,
  behavior: 'smooth'
};

if (isSmoothScrollSupported) {
    // Native smooth scrolling
    window.scroll(scrollToOptions);
} else {
    // Old way scrolling without effects
    window.scroll(scrollToOptions.left, scrollToOptions.top);
}


text:
Q: Terraform ternary operation I have terraform for provisioning GCP VM and it can be provision both OS (windows & Unix).
I have variable os_distro=windows.
I need windows-startup-script-ps1 = "${file("disk.ps1")}" inside metadata ONLY if os_distro is windows.
  meta_data_default = {
    google-monitoring-enable = 1
    google-logging-enable    = 1
    windows-startup-script-ps1 = var.os_distro == "windows" ? "${file("disk.ps1")}" : ""
  }

The above block works if os_distro==windows, but not require windows-startup-script-ps1 when os_distro==unix
Please guide me. Thanks

A: First, note that your interpolation syntax is deprecated. "${file("disk.ps1")}" should instead be file("disk.ps1").
Now for the main topic. Could you clarify, where is this meta_data_default block being defined? As others have noted in the comments, using null instead of "" after the ternary operator should work. But, if for some reason it doesn't, then you can do two things.
If meta_data_default is an input parameter, you can put a ternary around the entire object:
meta_data_default = var.os_distro == "windows" ? {
    google-monitoring-enable = 1
    google-logging-enable    = 1
    windows-startup-script-ps1 = file("disk.ps1")
  } : {
    google-monitoring-enable = 1
    google-logging-enable    = 1
  }

Or, if you want to keep it DRY (do not repeat yourself):
meta_data_default = merge(
  {
    google-monitoring-enable = 1
    google-logging-enable    = 1
  },
  var.os_distro == "windows" ?
    {
      windows-startup-script-ps1 = file("disk.ps1")
    } :
    {}
)

If meta_data_default is a block within a resource, you can use the dynamic statement:
resource "some_google_resource" "myresource" {
  ...

  dynamic "meta_data_default" {
    count = var.os_distro == "windows" ? 1 : 0
    content {
      google-monitoring-enable = 1
      google-logging-enable    = 1
      windows-startup-script-ps1 = file("disk.ps1")
    }
  }

  dynamic "meta_data_default" {
    count = var.os_distro == "windows" ? 0 : 1
    content {
      google-monitoring-enable = 1
      google-logging-enable    = 1
    }
  }
}

This will create the first style of meta_data_default block (with the windows-startup-script-ps1 field) if it's on Windows, or the second style (without that field) if it's on Unix.
As an aside, here's a trick I often use for automatically determining if Terraform is running on Windows or Unix:
locals {
  is_windows = dirname("/") == "\\"
}

If the OS uses a backslash as a path separator, it's windows, otherwise it's unix-based. This may or may not be useful for you, as I'm not sure if your os_distro variable is supposed to represent the OS that Terraform is running on, or the OS of a remote machine that you're creating/updating.


text:
Q: integrating hadoop, revo-scaleR and hive I have a requirement to fetch data from HIVE tables into a csv file and use it in RevoScaleR.
Currently we pull the data from HIVE and manually put it into a file and use it in unix file system for adhoc analysis, however, the requirement is to re-direct the result directly into hdfs location and use RevoScaleR from there?
How do I do that? or what sort of connection do I need to establish this.

A: If I understand your question correct, you could use RevoScaleR ODBC connection to import HIVE table and do further analysis from there.
Here is example of using Hortonworks provided ODBC driver:
OdbcConnString <- "DSN=Sample Hortonworks Hive DSN"

odbcDS <- RxOdbcData(sqlQuery = "SELECT * FROM airline",
                                connectionString=OdbcConnString,
                                stringsAsFactors=TRUE,
                                useFastRead = TRUE,
                                rowsPerRead=150000)

xdfFile <- "airlineHWS.xdf"

if(file.exists(xdfFile)) file.remove(xdfFile)

Flights<-rxImport(odbcDS, outFile=xdfFile,overwrite=TRUE)

rxGetInfo(data="airlineHWS.xdf", getVarInfo=TRUE,numRows = 10)

A: Chenwei's approach is ok but there is just one problem. The data is temporarily stored in memory as data frame in odbcDS object. If we have huge table in hive, then we are done.
I would suggested to keep everything on disk by using external tables in hive and then using the backend data directly in revolution r.
Something in these lines:

*

*Create external table from the existing hive tables in textfile(csv, tab etc) format.

CREATE EXTERNAL TABLE ext_table
LIKE your_original_table_name
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
LOCATION '/your/hdfs/location';

Here we are creating external table which is stored as csv file in hdfs.

*Next copy the original table to the external table using insert overwrite command.

insert overwrite table ext_table select * from your_original_table_name

If we want to check the backend data on hdfs type:

hadoop fs -ls /your/hdfs/location/

We can see the part files stored at the location. Go ahead and cat them to be double sure

*Now we can use RxTextData function to read the data from above step as

hive_data <- RxTextData(file='/your/hdfs/location/', delimiter = ',')

Now you can create an xdf file using hive_data as inFile argument in RxXdfData to be more efficient for further processing but above all data has never touched memory.


text:
Q: android geolocation permission promt not coming - phoonegap application I am building an HTML5 app where in I am testing the geolocation feature.
I am using the below code to access the geolocation of user.
if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(this.showPosition);
    }

When I run app with this code on android using phonegap, I don't see the permission prompt to allow or deny the geolcation of user.
However, on desktop browser the prompt displays.
I am directly loading my web page as in below code in my main activity file. I am not using the webview object.
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    super.loadUrl("file:///android_asset/Code/Test.html");
}

The permissions are given properly in the manifest file and I am getting the geolocation of user but the permissions prompt doesnt display in android.

A: I don't have a reference to confirm my answer but I believe this is the intended behavior. When you load the application in a web browser you haven't explicitly given permission to the app to know your location. Thus you're prompted to give the app access to that info. In a mobile app you give that permission when you install the app. That's why (at least in Android) you are shown a list of permissions that application wants when you install it. Then when you run the app you've already said it can have access to your location.

A: Make sure, you're calling geolocation API after device is ready -- see here for more details.


text:
Q: where does file data go in a device file? I'm writing a character device file and would like to know if there's any way to have a section of data for each instance of a device file. I've been looking at the inode and file structures for a place to store a non-volatile pointer, but have had no luck. can you do this with character device files, or should I be considering something else? i need to have custom read and write operations with data for each file instance.

A: You cannot store data in a device file. The whole point of a device file is that the data you write to it is passed to some driver.
You could theoretically store information in the file name, or in the group id field of the inode, but that would be very weird.
Your best solution is most likely to store your data separately. For example, why don't you create a regular file alongside the device file? Maybe use some naming convention to associate the two.


text:
Q: SELECT CONCAT alternative in PostgreSQL How can I write the following MySQL query in PostgreSQL syntax:
SELECT CONCAT(REPEAT("   ", (COUNT(parent.name) - 1)), cat.name) AS name

Thanks in advance!

A: The error here is that PostgreSQL doesn't allow double quotes " for literal strings (as per the SQL standard). You'll need to use single quotes '.
You also need to cast (COUNT(parent.name) - 1) to an integer, either using ::int (specific to Postgre) or CAST(... AS int).
Note that this may raise an integer out of range error if (COUNT(parent.name) - 1) is superior to 2147483647.
SELECT CONCAT(REPEAT('   ', (COUNT(parent.name) - 1)::int), cat.name) AS name

Note that you can also use || for string concatenation :
SELECT REPEAT('   ', (COUNT(parent.name) - 1)::int) || cat.name AS name

A: SELECT REPEAT("   ", (COUNT(parent.name) - 1)) || cat.name AS name

SQLFIDDLE


text:
Q: cURL call to web service not working I am trying to make a simple get call to a .NET RESTful web service at https://salesgenie.com/brandingservice/details?url=att.salesgenie.com  The test page making the cURL call is at https://test-cms.salesgenie.com/wp-content/themes/salesgenie/branding-proxy.php  The web service can be called in the browser but is timing out when called via cURL.  Here is the code from the branding-proxy.php page:
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$url = 'https://salesgenie.com/brandingservice/details?url=att.salesgenie.com';
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_SSLVERSION,3);
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
setcookie('CmsCookie', $code . '    ' . $response, 0, '/', 'salesgenie.com', 0);
echo 'Code:' . $code."<br />Response: ".$response;

A: I can see that the timeout happens while using your links, though I think the problem happens somewhere else. The reason I've come to that conclusion is that I uploaded your code to my own website. It worked fine.
Important
If you are the owner of salesgenie.com then I think you have a problem with the server, since sometimes the responses I got was either a timeout (code 0), code 200 (with result) or code 320. So the problem might be a problem within the server itself.
Tricks

*

*Try removing the setcookie to spare some processing.

*Also try using http instead of https since https requires some more processing to use.


text:
Q: Adding my own name tag to a form component in a partial view - MVC 5.0 I need to be able to show a dropdown list for some items in various different locations... I can safely assume that considering it is a dropdown, it will always be used in context with a form and thus a name tag will always be needed. However I wanted to know what's the best practice for this type of problem.
I have the following in a partial view and you can see I have explicitly set the name="Name" which at this moment in time is correctly going to map to the items Class property:
@model IEnumerable<TEST.Domain.Entities.James>

@{
    Layout = "";
}

<select name="Name" id="JamesDropdownList">
    @foreach (var item in Model)
    {
        <option value="@item.JamesID">@item.Name</option>
    }
</select>

I may then use this partial view in such a context:
        @using (Html.BeginForm("LoadInformation", "James"))
        {

                @{ Html.RenderAction("DropdownList", "James"); } // This is the partial view being used in a form

                @Html.ContinueButton("Continue") // This is a custom button html helper I have created

        }

So the question is, is this absolutely okay, to declare specifically that the name for this select field is "Name" or is there some special clever razorey way of doing this?
EDIT
In fact, don't I have to do     @Html.Hidden("JamesID", item.JamesID) or something in the select? So that when I submit that form, it pushed the JamesID to the controller which looks like this:
    [HttpPost]
    public ViewResult LoadInformation(int jamesID)
    {
        // Do something with jamesID
        return View("LoadInformation");
    }

You can see i'm a bit confused...
Maybe a better question is, how do I have a re-usable dropdown list that I can use in a form that requires the JamesID from that dropdown list as one of the receiving controller's parameters?

A: One razory way would be to do this:
@Html.DropDownList("JamesDropdownList", new SelectList(Model,"JamesID","Name"))

This will assign JamesDropdownList to both the name and id attribute of the dropdown.


text:
Q: MKMapkit constraint error when reopen project I built a custom view controller. It has 1 tableview, 2 views and 1 map. When I set the constraints for this layout it works fine. I close project and reopen the map view out of the view controller. The width and height are 1000 points. If I set the map on top of this stack, there is no problem. But when I set map in the middle of the other views, a problem happens. I must put this mapview inside another view or it affects the others, but the problem is still there.
I use Xcode 8 beta 5, and constraint is 0 0 0 0

A: I have the same issue in the latest beta. I believe the problem is in the wrong default size, that is always set to 1000x1000 by Xcode for MKMapView.
I would wait for the fix in the next Xcode version.
If you, by some reason, really need it fixed now, you can setup a UIView with constraints as required, then put MKMapView inside the UIView and use Autoresizing to scale it.


text:
Q: How to fix Opera and Google Chrome? Recently I've changed from mint 17 to linux mint 18. Unlike on mint 17, now Google Chrome border is like it is not selected (light-gray color) and returns
[WARNING:flash/platform/pepper/pep_module.cpp(63)] SANDBOXED

this error, and has some graphical problems, while playing screen sections are turning black for some seconds.
I also installed Opera, it doesn't have any visual issues, but terminal shows
[0927/131635:ERROR:object_proxy.cc(583)] Failed to call method: org.freedesktop.DBus.Properties.Get: object_path= /org/freedesktop/UPower: org.freedesktop.DBus.Error.InvalidArgs: No such interface 'org.freedesktop.UPower.Device'

[WARNING:flash/platform/pepper/pep_module.cpp(63)] SANDBOXED

Vector smash protection is enabled.

[0927/131637:ERROR:ticl-message-validator.cc(212)] registration_digest must be non-empty

[0927/131637:ERROR:ticl-message-validator.cc(319)] field registration_summary failed validation in { protocol_version: { version: { major_version: 3 minor_version: 2  }  } client_token: "NWqcVMArVrn/FjkzTOaZ4A==" registration_summary: { num_registrations: 0 registration_digest: ""  } server_time_ms: 0  }

[0927/131637:ERROR:ticl-message-validator.cc(361)] field header failed validation in { header: { protocol_version: { version: { major_version: 3 minor_version: 2  }  } client_token: "NWqcVMArVrn/FjkzTOaZ4A==" registration_summary: { num_registrations: 0 registration_digest: ""  } server_time_ms: 0  }  }

[0927/131637:ERROR:protocol-handler.cc(145)] Received invalid message: { header: { protocol_version: { version: { major_version: 3 minor_version: 2  }  } client_token: "NWqcVMArVrn/FjkzTOaZ4A==" registration_summary: { num_registrations: 0 registration_digest: ""  } server_time_ms: 0  }  }

What does this errors mean and how can they be fixed?


text:
Q: Pressure Transducer, Reverse and Shift Output of a differential amplifier I am making a custom hydraulic brake for my sim racing setup. The original brake uses a potentiometer which outputs 3.3V at no brake pressure and 0V at full brake pressure. My pressure transducer, when supplied with the same supply as the pot, outputs around 0.35V at no brake pressure and around 3V at full brake pressure. For reference, when supplied 5V, it outputs .5-4.5V.
I have setup this diff amp circuit and was able to reverse the output of the pedal.

But I am now struggling to figure out how to shift it to hit 0V and start at 3.3V. How do I "exactly" calculate the resistors to achieve that function?
I have already considered an Arduino, but I would really like this to stay as simple as possible as far as hardware goes for resale considerations. An Arduino makes this much more difficult from that perspective.

A: Here is a Maple sheet to calculate your components for that goal.
First, write equations.
Then, write your final conditions of working.
NB: one must use a rail to rail opamp.

NB line k:=1000; ..... should be deleted.


text:
Q: C# DateTime.Now to find yesterday Currently I am making the Query to find out to get the data from SQL server.
SELECT * FROM ExcelOutput WHERE ADateTime >= '2014-12-03 07:00:00' AND ADateTime < '2014-12-04 12:00:00'

I need to create one method to get two Date object as input. The second one will be the DateTime.Now() as the input data and the first ADateTime will be the Yesterday one, how I can write the command as Yesterday? DateTime.Now .... somethings to minus one day.
Edited
What I want is
function(Today 7 a.m., Yesterday 7 a.m.)
{
}
in C#.
Then I can connect with that SQL to retrieve the data.
This is the Correct Answer.
Try this snippet,
DateTime today = DateTime.Now.Date;
today = today.AddHours(7);
DateTime yesterday = today.Subtract(TimeSpan.FromHours(24));

SELECT * FROM ExcelOutput WHERE ADateTime >= 'yesterday' AND ADateTime < 'today'

Credit to: Manu Nair

A: Try this snippet,
DateTime today = DateTime.Now.Date;
today = today.AddHours(7);
DateTime yesterday = today.Subtract(TimeSpan.FromHours(24));

SELECT * FROM ExcelOutput WHERE ADateTime >= 'yesterday' AND ADateTime < 'today'

A: How to get the specific time of today (and yesterday):
var today = DateTime.Now.Date;
var todayAtSeven = DateTime.Now.Date.Add(TimeSpan.FromHours(7));
var yesterdayAtSeven = today.AddDays(-1).Add(TimeSpan.FromHours(7));

A: You can subtract one day from DateTime.Now by
DateTime yest = DateTime.Now.AddDays(-1);

You can also do this to any DateTime object.
If you want to subtract one day from your custom date, create an object of DateTime by
example
DateTime myVar = new DateTime(2014, 6, 14, 6, 32, 0);
myVar.AddDays(-1);

If you want to create a specific time,
DateTime reqTime = new DateTime(yest.Year,yest.Month,yest.Day,myCustomhour,myCustomminute,myCustomsecond);

A: I think this is possible to do with DateTime.Now.AddDays:
DateTime tomorrow = DateTime.Now.AddDays(1); //tomorow
DateTime yesterday = DateTime.Now.AddDays(-1); //yesterday

A: Yesterday at 13:00:
var yesterday = DataTime.Today.AddDays(-1).AddHours(13);

Today gives date only.

A: This is the Correct Answer.
Try this snippet,
DateTime today = DateTime.Now.Date;
today = today.AddHours(7);
DateTime yesterday = today.Subtract(TimeSpan.FromHours(24));

SELECT * FROM ExcelOutput WHERE ADateTime >= 'yesterday' AND ADateTime < 'today'

Credit to: Manu Nair


text:
Q: Error: Cannot got to specified record. Access 2007 and SQL 2005 I have inherited an Access 2007 database that has been split so the
tables are on a SQL 2005 server.
The database consists of 3 tables and 3 forms.  The main form that is
used reads and writes to all 3 tables.  Data can be edited and deleted
OK but trying to add a new record throws an error saying, "You can't
go to the specified record"
The code for the new record button is an embedded macro with the
follow parameters:
  OnError Next,
  GoToRecord ,,New,
  [MacroError]<>0 MsgBox =[MacroError].[Description],Yes,None,

Any advice would be greatly appreciated
Thanks,
Amy

A: Check whether all required fields of the record are present when you do the insert or if the constraints are met (such as having a duplicate value for a field that does not allow duplicates).


text:
Q: Format PHP date string I want to convert a date string to a specific date format
I'm currently using strtotime to convert a date, but it doesn't get the correct hour
My code
<?php
        $timestamp = 'Fri, 10 Aug 2018 11:00:00 GMT ';

    $formatted = strtotime($timestamp);

    echo date('Y-m-d H:i:s', $formatted);
?>

It gives me 01:00 pm instead of 11:00
Am i doing something wrong?

A: php.ini
date.timezone=UTC

or
.php file
echo date('Y-m-d H:i:s T', time())."\n";
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s T', time())."\n";

or
.htaccess file
php_value date.timezone UTC

--
If the timezone you are using is not UTC, check the following urls:
http://php.net/manual/en/timezones.php
https://publib.boulder.ibm.com/tividd/td/TWS/SC32-1274-02/en_US/HTML/SRF_mst273.htm


text:
Q: Can't throw error from within an async promise executor function I've been trying to get a conceptual understanding of why the following code doesn't catch the throw. If you remove the async keyword from the new Promise(async (resolve, ... part then it works fine, so it has to do with the fact that the Promise executor is an async function.
(async function() {

  try {
    await fn();
  } catch(e) {
    console.log("CAUGHT fn error -->",e)
  }

})();

function fn() {

  return new Promise(async (resolve, reject) => {
    // ...
    throw new Error("<<fn error>>");
    // ...
  });

}

The answers here, here, and here repeat that "if you're in any other asynchronous callback, you must use reject", but by "asynchronous" they're not referring to async functions, so I don't think their explanations apply here (and if they do, I don't understand how).
If instead of throw we use reject, the above code works fine. I'd like to understand, fundamentally, why throw doesn't work here. Thanks!

A: because the only way to "communicate" to the outside world from within a Promise executor is to use the resolve and reject functions. You could use the following for your example:
function fn() {
  return new Promise(async (resolve, reject) => {
    // there is no real reason to use an async executor here since there is nothing async happening
    try {
      throw new Error('<<fn error>>')
    } catch(error) {
      return reject(error);
    }
  });
}

An example would be when you want to do something that has convenient async functions, but also requires a callback. The following contrived example copies a file by reading it using the async fs.promises.readFile function with the callback based fs.writeFile function. In the real world, you would never mix fs functions like this because there is no need to. But some libraries like stylus and pug use callbacks, and I use something like this all the time in those scenarios.
const fs = require('fs');

function copyFile(infilePath, outfilePath) {
  return new Promise(async (resolve, reject) => {
    try {
      // the fs.promises library provides convenient async functions
      const data = await fs.promises.readFile(infilePath);
      // the fs library also provides methods that use callbacks
      // the following line doesn't need a return statement, because there is nothing to return the value to
      // but IMO it is useful to signal intent that the function has completed (especially in more complex functions)
      return fs.writeFile(outfilePath, data, (error) => {
        // note that if there is an error we call the reject function
        // so whether an error is thrown in the promise executor, or the callback the reject function will be called
        // so from the outside, copyFile appears to be a perfectly normal async function
        return (error) ? reject(error) : resolve();
      });
    } catch(error) {
      // this will only catch errors from the main body of the promise executor (ie. the fs.promises.readFile statement
      // it will not catch any errors from the callback to the fs.writeFile statement
      return reject(error);
      // the return statement is not necessary, but IMO communicates the intent that the function is completed
    }
  }
}

Apparently everyone says this is an anti-pattern, but I use it all the time when I want to do some async stuff before doing something that can only be done with a callback (not for copying files like my contrived example). I don't understand why people think it is an anti-pattern (to use an async promise executor), and haven't seen an example yet that has convinced me that it should be accepted as a general rule.

A: This is the async/await version of the Promise constructor antipattern!
Never ever use an async function as a Promise executor function (even when you can make it work1)!
[1: by calling resolve and reject instead of using return and throw statements]

by "asynchronous" they're not referring to async functions, so I don't think their explanations apply here

They could as well. A simple example where it cannot work is
new Promise(async function() {
    await delay(…);
    throw new Error(…);
})

which is equivalent to
new Promise(function() {
    return delay(…).then(function() {
        throw new Error(…);
    });
})

where it's clear now that the throw is inside an asynchronous callback.
The Promise constructor can only catch synchronous exceptions, and an async function never throws - it always returns a promise (which might get rejected though). And that return value is ignored, as the promise is waiting for resolve to be called.


text:
Q: Is it appropriate to identify and remove outliers because they cause problems? This all pertains to my Psychology honours thesis.
I have two groups (Autism and control) and all participants completed four tasks. It is very important to my study that the groups do not differ on reaction time in each of the tasks. However, they do. The autism group responded faster than the control group. This confounds the results for the construct we actually want to investigate.
I thought I might correct the difference by excluding outliers from the study. I tried to identify outliers at both the univariate (Boxplots, SD = +/- 2.5, for each of the four tasks) and multivariate level (Mahalanobis Dsq). No participant comes up as an outlier. Then I thought I would exclude participants that have low average reaction times ('low' being an arbitrary value), but even so the difference between the two groups was significant.

*

*Is there anything else I can do?

*And how would I report such a process in my thesis?

A: You should not exclude outliers just because they cause problems, nor should you use a subset of your data because the full data causes problems. Neither of these solved the "problem" in your case, but even if they did, it wouldn't be right.
You haven't given a lot of detail about what you are trying to do or how you are doing it, but can you add reaction time as a covariate?

A: It is very important that you consider the possibility that the categories of subject have a real difference in reaction times. If that is the case then anything that makes the difference go away will lead to potentially artifactual results. Don't assume that an inconvenient effect is a result of the presence of outliers.
Perhaps you could look for a relationship between reaction time and another outcome measure. The form of the relationship may differ between autistic subjects and normal subjects.

A: It sounds like you need to explore your data a little more.  Why don't you try some unsupervised techniques like clustering.  Outliers would show up in their own groups.  And you would think there'd be some kind of grouping of your controls.
Regardless, you can still have a thesis about not seeing an effect you expected to see.  You'd have to explain how your data/method was not flawed.  And add a section about what variables you might add to explain why your test subjects and controls are grouping together.  This work still helps future researchers.


text:
Q: List All Docs with @ibm-cloud/cloudant So recently IBM deprecated @cloudant/cloudant and have moved on to @ibm-cloud/cloudant. I was in the process of doing a todo app to learn Cloudant along with some other things and so had to migrate to the new package.

As you can see from my Cloudant dashboard, I have a database with name "todo-vue-hapi" and there are 3 docs in the db. According to the migration docs to list all the documents before you would use db.list now you should use service.postDesignDocs so I connected everything and used the following code:
const response = await db.postDesignDocs({
  db: 'todo-vue-hapi',
})

This gives back a response object with the following result property:
{result: { total_rows: 0, offset: 0, rows: []}

The 3 docs are not there! I'm wondering how I can query everything in the database "todo-vue-hapi". Help with this issue would be greatly appreciated.

A: The postDesignDocs function only returns design documents, which are special Cloudant documents containing index definitions.
To return all documents in a database you need to use the _all_docs API endpoint which is implemented as the postAllDocs function:
const response = await db.postAllDocs({
  db: 'todo-vue-hapi',
  includeDocs: true,
  limit: 10
})

This should return you all documents in the database, including regular and design documents.


text:
Q: What's the control used in Kindle for Windows Phone 7 I was wondering what kind of control Amazon has used to display text in their application for Windows Phone 7 ? It must be some kind of custom ones because if I remember correctly there's not support for FlowDocument, Run etc in WP7.

A: <Run> is supported on WindowsPhone7 - e.g. http://social.msdn.microsoft.com/Forums/en-SG/wpf/thread/ca27556a-a33b-4d4e-82b4-a0ed8596d6a1 - you can see Run used in lots of apps - e.g. the official Twitter app.
This question - Programmatically determining max fit in textbox (WP7) - analyses the Kindle UI control a little bit - it leads me to think that Amazon are using a TextBlock control for the main page, and are doing some manual calculations to work out how many words are on the current page.

A: Kindle ebooks are primarily HTML (output of conversion from multiple formats), so it would be some kind of WebBrower control.

A: They haven't detailed this publicly.
I strongly suspect that they have their own controls to wrap a canvas which they dynamically populate with the text and then animate with their own manipulation code.


text:
Q: JMeter idle Threads/Users I have a practical Challenge:
I need to validate that a server-timeout appears after 5 seconds (as in a 400/500 response-code) under a JMeter loadtest with 100 threads running constantly and requesting a url simulataniously.
Is it possible to configure JMeter to idle/delay/keep running each thread/user for a custom period of time?

A: I think what you need is Constant Timer . Read the below link to know more about it.
http://jmeter.apache.org/usermanual/component_reference.html#Constant_Timer
This will help you pause the threads for a constant amount of time before releasing it to proceed further

A: You can add Runtime Controller which actually lets you run as much as you define it :

Desired runtime in seconds


text:
Q: Make changes inside an Each block persistent I have been trying the fantabulous CsQuery library, which is basically a .NET port for jQuery allowing the use os CSS selectors and most of jQuery's functionalities.
I am using it to parse and edit a batch of HTML files (particularly, editing some attributes of different DOM elements).
The following C# snippet shows sort of what I'm doing, with the JavaScript/jQuery equivalent code in the comments.
FileStream doc = File.Open(/*some html file*/);

CQ dom = CQ.Create(doc);        // $dom = $(document);
CQ images = dom.Select("img");  // $images = $('img');
images.Attr("src","#");         // $images.attr('src','#');

dom.Save(/*Output path*/); // No jQuery equivalent, this just saves the file.

This works perfectly: if I check the output file, all the image's src values are now #.
Anyway, if I use the Each block (which seems to work nicely using C# lambda expressions to simulate javascript's function passing) the changes won't apply to the output file:
FileStream doc = File.Open(/*same html file*/);

CQ dom = CQ.Create(doc);                  // $dom = $(document);
CQ images = dom.Select("img");            // $images = $('img');
images.Each( (element) => {               // $images.each( function(){
  CQ cqElement = CQ.Create(element);      //   $element = $(this);
  cqElement.Attr("src","#");              //   $element.attr('src','#');
  Messagebox.Show(cqElement.Attr("src")); //   alert($element.attr('src'));
});                                       // });

dom.Save(/*Output path*/); // No jQuery equivalent, this just saves the file.

Despite the Messabox showing "#" for every image in my DOM (which means that the cqElement gets the change), the output file doesn't get the changes.
I think the key line causing the problem is CQ cqElement = CQ.Create(element); since it creates a brand new CsQuery object. In fact, if just after the first Messagebox I pop up another one like the following one, it will not have the changes made to the cqElement
Messagebox.Show(dom.Html()); // alert($dom.html());

Any idea on how could I solve this issue?

A: You're absolutely right: CQ cqElement = CQ.Create(element) is the problem. This is at the core of the most siginficant difference between CsQuery and jQuery. With jQuery, there's only one DOM. With CsQuery, there's no browser, so there can be any number of distinct DOMs. Each time you use Create it's a brand new DOM; whereas jQuery methods/selectors return a new CQ object bound to the same DOM.
The correct way to "wrap" a DOM element as a CQ object like  $(element) is with new and not Create, e.g.
CQ cqElement = new CQ(element);

There's also a shortcut that's a method on IDomObject:
CQ cqElement = element.Cq();

These keep the element in the same DOM. The Create methods always produce a new DOM, and when created from elements, actually clones them so the original DOM is not affected. (Elements can only belong to a single DOM; if you were to create two different DOMs and add elements from one to another using a method like Append, they would be removed from the source. Create automatically clones them.).
I am sure this could be made more clear in the documentation :)