text:
Q: Stop page load and redirect in a content script I am making a extension in Chrome and need to stop a page load (without loading the page completely) and redirect to a url if matches from ajax query.
I am using content_scripts.
And tried to use
 window.location.replace("http://facebook.com");

But the redirect occurs once the page load is completed..
Even tried to use
window.stop();

this is also not working to stop page loading.
Is there any possible way to stop a page load and redirect it before page load?

A: You're trying this with a content script.
Content scripts have a run_at parameter, which indicates when (relative to page loading) they execute.
By default, content scripts run at document_idle level: Chrome waits until the page has completely loaded before executing it.
You have two options:

*

*You can keep the content script route, but you need to indicate "run_at" : "document_start" parameter in the content script configuration.
This will execute your code as soon as possible (before the document is loaded, but after the response is started).

*If you're concerned about not loading the page at all (not sending a request to the site), you need to intercept it at a lower level. webRequest API can provide the means to do that.
If you catch the request at onBeforeRequest event, you can redirect it before it is even sent. Filtering by type is recommended. Note that you won't even need a content script in this case: webRequest events need to be listened to in a background script.
See the CatBlock example.


text:
Q: IRetryAnalyzer HELP, can't make it work I'm new on this so this isn't so obvious for me. I'm trying to implement IRetryAnalyzer from testNG, to re run the test cases that failed.
And this is what I've done, but can't make it work. Note all this code I've copied form the internet.
public class Retry implements IRetryAnalyzer {

private int retryCount = 0;
private int maxRetryCount = 2;

@Override
public boolean retry(ITestResult result) {

    if (retryCount < maxRetryCount) {
        System.out.println("Entre");
        retryCount++;
        return true;
    }
    return false;

}

Here is my test method were it should fail and re run the test.
@Parameters({ "nombrePlan", "nombreBuild", "nomTL_verificacionUIHomePageIssuer" })
@Test(retryAnalyzer = Retry.class)
  public void verificacionUIHomePageIssuer(String nombrePlan, String nombreBuild, String nomTL_verificacionUIHomePageIssuer) throws Exception {
    HomePageIssuer homePage = new HomePageIssuer(driver);
    //Assert.assertTrue(homePage.validacionLogin(), homePage.getError());
    Assert.assertTrue(false);
}

The thing is that when I run it doesn't work the driver closes and the test never starts again.
Any help would be appreciated.
Thanks in advance.

A: Based on comments, @BeforeTest was being used for driver initalization and hence Retry wasn't invoking it again.
BeforeTest will only be called once for your entire  tag. Try using @beforemethod, but then this would init after every testcase.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detected conflict - Failed to fallback - Violation of PRIMARY KEY constraint - Cannot insert duplicate key in object I have configured SymmetricDS 3.9.15 using Azure SQL for master and slave databases with bi-directional replication.
I am facing the Failed to Fallback error continuously on the reload channel. I have attached the error logs for the same.
Here is my sym_conflict configuration
        insert into sym_conflict (conflict_id, target_channel_id, source_node_group_id, target_node_group_id, detect_type, detect_expression, resolve_type,ping_back, resolve_changes_only, resolve_row_only, create_time, last_update_time)
        values ('Conflict-primary-secondary-staging_prod-us', 'matter', 'primary-staging_prod-us', 'secondary-staging_prod-us', 'USE_CHANGED_DATA', null, 'FALLBACK', 'REMAINING_ROWS', 0, 1, GetDate(), GetDate());
        insert into sym_conflict (conflict_id, target_channel_id, source_node_group_id, target_node_group_id, detect_type, detect_expression, resolve_type,ping_back, resolve_changes_only, resolve_row_only, create_time, last_update_time)
        values ('Conflict-secondary-primary-staging_prod-us', 'matter', 'secondary-staging_prod-us', 'primary-staging_prod-us', 'USE_CHANGED_DATA', null, 'FALLBACK', 'REMAINING_ROWS', 0, 1, GetDate(), GetDate());

        insert into sym_conflict (conflict_id, target_channel_id, source_node_group_id, target_node_group_id, detect_type, detect_expression, resolve_type,ping_back, resolve_changes_only, resolve_row_only, create_time, last_update_time)
        values ('Conflict-primary-secondary-staging_prod-us-reload', 'reload', 'primary-staging_prod-us', 'secondary-staging_prod-us', 'USE_CHANGED_DATA', null, 'FALLBACK', 'REMAINING_ROWS', 0, 1, GetDate(), GetDate());
        insert into sym_conflict (conflict_id, target_channel_id, source_node_group_id, target_node_group_id, detect_type, detect_expression, resolve_type,ping_back, resolve_changes_only, resolve_row_only, create_time, last_update_time)
        values ('Conflict-secondary-primary-staging_prod-us-reload', 'reload', 'secondary-staging_prod-us', 'primary-staging_prod-us', 'USE_CHANGED_DATA', null, 'FALLBACK', 'REMAINING_ROWS', 0, 1, GetDate(), GetDate());

SymmetricDS Windows Service Logs ==>
        2019-01-16 19:07:48,432 INFO [secondary-staging_prod-us-001] [IncomingBatchService] [secondary-staging_prod-us-001-dataloader-2] Retrying batch 000-10228
        2019-01-16 19:08:10,848 INFO [primary-staging_prod-us-000] [DataProcessor] [primary-staging_prod-us-000-dataloader-1] Batch '6744', for node '000', for process 'data load from stage' has been processing for 60 seconds.  The following stats have been gathered: {STATEMENTCOUNT=4890, LOADMILLIS=44514, Time_Entries UPDATECOUNT=4890, STARTTIME=1547645830799, FALLBACKUPDATECOUNT=4890, FILTERMILLIS=516, LINENUMBER=4890, UPDATECOUNT=4890}
        2019-01-16 19:08:11,820 INFO [secondary-staging_prod-us-001] [DataGapFastDetector] [secondary-staging_prod-us-001-job-1] The data gap detection has been running for 60021ms, inserted 16590 of 1 new gaps
        2019-01-16 19:08:32,801 INFO [secondary-staging_prod-us-001] [DefaultDatabaseWriter] [secondary-staging_prod-us-001-dataloader-2] Failed to process insert event in batch 000-10228 on channel 'reload'.
        Failed row data was: "308845","589832","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0.00","0","2017-08-21 05:34:27.4869412",,,"0","42"
         StackTraceKey.init [ConflictException:329112692]
        org.jumpmind.symmetric.io.data.writer.ConflictException: Detected conflict while executing INSERT on DBSYNC__STAGING_PROD_Copy.dbo.TaskTimeEntriesCaching.  The primary key data was: {ID=308845}. Failed to fallback.  The original error message was: Violation of PRIMARY KEY constraint 'PK__TaskTime__3214EC2752E46644'. Cannot insert duplicate key in object 'dbo.TaskTimeEntriesCaching'. The duplicate key value is (308845).
            at org.jumpmind.symmetric.io.data.writer.AbstractDatabaseWriterConflictResolver.performFallbackToUpdate(AbstractDatabaseWriterConflictResolver.java:256)
            at org.jumpmind.symmetric.io.data.writer.DefaultTransformWriterConflictResolver.performFallbackToUpdate(DefaultTransformWriterConflictResolver.java:110)
            at org.jumpmind.symmetric.io.data.writer.AbstractDatabaseWriterConflictResolver.needsResolved(AbstractDatabaseWriterConflictResolver.java:54)
            at org.jumpmind.symmetric.io.data.writer.AbstractDatabaseWriter.write(AbstractDatabaseWriter.java:211)
            at org.jumpmind.symmetric.io.data.writer.NestedDataWriter.write(NestedDataWriter.java:64)
            at org.jumpmind.symmetric.model.ProcessInfoDataWriter.write(ProcessInfoDataWriter.java:84)
            at org.jumpmind.symmetric.io.data.writer.NestedDataWriter.write(NestedDataWriter.java:64)
            at org.jumpmind.symmetric.io.data.writer.TransformWriter.write(TransformWriter.java:201)
            at org.jumpmind.symmetric.io.data.DataProcessor.forEachDataInTable(DataProcessor.java:210)
            at org.jumpmind.symmetric.io.data.DataProcessor.forEachTableInBatch(DataProcessor.java:177)
            at org.jumpmind.symmetric.io.data.DataProcessor.process(DataProcessor.java:123)
            at org.jumpmind.symmetric.service.impl.DataLoaderService$LoadIntoDatabaseOnArrivalListener$2.call(DataLoaderService.java:1039)
            at org.jumpmind.symmetric.service.impl.DataLoaderService$LoadIntoDatabaseOnArrivalListener$2.call(DataLoaderService.java:1016)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at java.lang.Thread.run(Thread.java:748)
        2019-01-16 19:08:33,650 ERROR [secondary-staging_prod-us-001] [ManageIncomingBatchListener] [secondary-staging_prod-us-001-dataloader-2] Failed to load batch 000-10228 StackTraceKey [ConflictException:329112692]
        2019-01-16 19:08:33,759 ERROR [primary-staging_prod-us-000] [AcknowledgeService] [qtp1552978964-13] The outgoing batch 001-10228 failed: [CONFLICT,-999] Detected conflict while executing INSERT on DBSYNC__STAGING_PROD_Copy.dbo.TaskTimeEntriesCaching.  The primary key data was: {ID=308845}. Failed to fallback.  The original error message was: Violation of PRIMARY KEY constraint 'PK__TaskTime__3214EC2752E46644'. Cannot insert duplicate key in object 'dbo.TaskTimeEntriesCaching'. The duplicate key value is (308845).

Regards
Rajat Agrawal

A: I would remove the conflicts on your reload channel.  You should not need conflict detection on the reload channel.  By default a reload will insert data and if it fails will fall back to update allowing the rest of the batch to proceed.

A: I had the following unique index on the TaskTimeEntriesCaching table which was causing the fallback to fail.
    /****** Object:  Index [UC_TaskTimeEntriesCaching_TaskID]    Script Date: 17-01-2019 12:21:57 ******/
    ALTER TABLE [dbo].[TaskTimeEntriesCaching] ADD  CONSTRAINT [UC_TaskTimeEntriesCaching_TaskID] UNIQUE NONCLUSTERED
    (
        [TaskID] ASC,
        [DeletedFlag] ASC,
        [sid] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
    GO

Also I had the SymmetricDS windows service in stopped state for a couple of days and I had a 'matter' channel parallel to the default channel.
So I had to drop this unique index for the reload channel to complete.
Regards
Rajat Agrawal


text:
Q: Button in javascript which in turn pops up a button I want to have a button in javascript which in turn pops up a button on clicking which I get to call a function. I am referring to this. In this you can see a drop down menu popping up by clicking on a button. I want a button instead. Or this menu is fine but I want to have them as buttons. Any idea how to go about this ?
The code is
Html

<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>

<input type="button" id="target" value="click"/>

Js
$( "#dialog" ).hide();
$( "#target" ).click(function() {
  $( "#dialog" ).show();
  $( "#dialog" ).dialog();
});

A: What about this:

$( "#dialog" ).hide();
$( "#target" ).click(function() {
      $( "#dialog" ).show();
    $( "#dialog" ).dialog();
});
$( "#dialogButton" ).click(function() {
    doStuff();
});

function doStuff() {
 window.open('https://www.youtube.com/watch?v=kfVsfOSbJY0', '_blank');
}
<link href="http://code.jquery.com/ui/1.9.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

<input type="button" id="dialogButton" value="wut wut?"/>

<input type="button" id="target" value="click"/>

A: Here's a minor reworking of your fiddle that accomplishes this: http://jsfiddle.net/ssschupbach/5UT5q/318/
Basically, use <button> instead of <select> and <option> and add click handlers to those new buttons.


text:
Q: Conditional select in SQL Statement I'm trying to do something like this:
SELECT UserID from Users as user
    INNER JOIN UserStatus as userStatus on u.UserID = us.UserID
WHERE
    --user.IsActive = 1
    --if user.IsActive = 0
        --userStatus.DeactivatedDate > @StartDate
        --userStatus.DeactivatedDate < @EndDate

So in general I want a query that gets me all results whose value matches the where statement without necessarily ignoring all of those results that do not. Kind of like a Venn diagram with the the left side of the circle and the middle filled in.  For the example I've shown, I want all users who are currently active and the users who are not active but were active within the given time frame (if I wanted the total number of users active at any point within a month, for instance).
I've tried doing things like
SELECT UserID from Users as user
    INNER JOIN UserStatus as userStatus on u.UserID = us.UserID
WHERE
    Case user.IsActive = 1

But that is obviously incorrect syntax.  I will also need to translate this to LINQ as well, so resources on that would be beneficial as well.

A: I believe this will give you the result you're looking for:
SELECT  UserID
FROM    Users U
JOIN    UserStatus US
    ON  U.UserID = US.UserID
WHERE
        U.IsActive = 1
        OR (
                U.IsActive = 0
            AND US.DeactivatedDate > @StartDate
            AND US.DeactivatedDate < @EndDate
        )

A: SELECT UserID from Users as user
    INNER JOIN UserStatus as userStatus on u.UserID = us.UserID
WHERE
     user.IsActive = 1 OR us.DeactvatedDate BETWEEN '2012-08-13' AND '2013-08-13'

This will do the job if you have any entry regarding date when a user got decativated.
In LINQ
var UID= from u in Users
         from s in UserStatus
         where u.UserID == s.UserID || (s.DeactivatedDate  >= @StartDate &&
         s.DeactivatedDate <= @endDate)
         select u.userID


text:
Q: how to resize iphone keyboard? I am developing a program in which I have to change the size of the keyboard according to the size of a UITextView, either increase or decrease. How can I do this?

A: it's impossible in standard SDK.


text:
Q: Express.js redirect loop - Production Only I am running an app with separated API and Front, both running on Express.js.
I have created a redirect on API to redirect '/' and missing routes to frontend URL.
Everything works on dev, however, I get a redirect loop - ERR_TOO_MANY_REDIRECTS error on production.
Production is working on https, so I am not sure if that could be the problem, and I am using Helmet package for security.
Tried to create 2 solutions and searched through SO, but none work:
-----  #1 - app.js -----
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  //log error
  logging.error(err);
  res.status(err.status || 500);

  // frontUrl is http://xx.com for dev, and https://xy.com for production
  res.redirect(frontUrl);
});

module.exports = app;

----- #2 - app.js -----
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  //log error
  logging.error(err);
  res.status(err.status || 500);

res.redirect('/');
});

module.exports = app;

-----  /routes/index.js -----
var frontUrl = require('../config.json').FrontURL;

router.get('/', function(req, res, next) {
    res.redirect(frontUrl);
});


text:
Q: Leaflet MapBox Issue of poly line which crosses the antimeridian I am using  mapbox leaflet js in my application "https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.js". Previously i was using google map,
I am facing an issue when i draw a polyline in map which crosses the international datelines, the Line which is drawn on map using MapBOx is not wrapped in one copy of world as in Google map.
I had done lot of Reaserach and found that the coordinates which are crossing the dateline add/subtract 360 from the longitude, which will draw a contineous line on map.
But as my client is habitual with google map services so he needs the polyline to be displayed as in google map.
I had attached a Zip file which contains three Screenshots
1) Original_functionality_mapBox.png : This image shows when coordinates of polyline which crosses the international date line are not changed.
2) change_360_Degree.PNG : This image shows when coordinates of polyline which crosses the international date line are changed by subtracting 360 from longitude.
3) google.PNG: when the original coordinates are passed to google map, it automatically adjust the polyline which crosses the international date line.
Please help me urjently to do the same as in google map.
                     1(Original_functionality_mapBox.png)

                     2(change_360_Degree.PNG)

                     3(google.PNG)

A: Ah, antimeridian artifacts. See https://stackoverflow.com/questions/40532496/wrapping-lines-polygons-across-the-antimeridian-in-leaflet-js for some similar problems. Let me quote two relevant bits:

Leaflet can handle longitudes outside the [-180..180] range. In Leaflet, longitudes wrap only the TileLayer's tiles and not markers or polylines.
In other words: a line from [0, 179] to [0, -179] is 358 degrees long, but a line from [0, 179] to [0, 181] is two degrees long.

You already know this, judging by your second screenshot.
Leaflet can not (currently) duplicate geometries in order to display one geometry per copy of the world (per 360-degrees-of-longitude extend). You can fake this by making more than one copy of your geometry, offset by 360 degrees each, and using the worldCopyJump option to prevent the user from panning around too much.


text:
Q: React error is not displayed on browser, only getting an empty screen
React is only showing an empty screen rather than showing an error something like this on my instructor's system:

How can I fix this?
EDIT: I can definitely see the error in the console and in IDE but to test error boundaries I want to fix this. Currently, When I use error boundary and create my own error using throw new Error(), error boundary only console.logs the error but doesn't display the UI, my screen only gets freezed.
ON USING ERROR BOUNDARIES:
App.js:
import UserFinder from './components/UserFinder';
import UsersContext from './store/user-context';
import ErrorBoundary from './components/ErrorBoundary';

const DUMMY_USERS = [
  { id: 'u1', name: 'Max' },
  { id: 'u2', name: 'Manuel' },
  { id: 'u3', name: 'Julie' },
];

function App() {
  const usersContext = {
    users: DUMMY_USERS
  }

  return (
    <UsersContext.Provider value={usersContext}>
      <ErrorBoundary>
        <UserFinder />
      </ErrorBoundary>
    </UsersContext.Provider>
  );
}

export default App;

ErrorBoundary.js:
import React, { Component } from 'react';

export class ErrorBoundary extends Component {
    constructor() {
        super();
        this.state = {
            hasError: false
        }
    }

    componentDidCatch(error){
        console.log(error);
        this.setState({hasError:true});
    }

    render() {
        if (this.state.hasError === true)
        {

Error Occured!

        }
        return this.props.children;
    }
}

export default ErrorBoundary;

Users.js(where I generated error)
import { Component } from 'react';
import User from './User';
import classes from './Users.module.css';

class Users extends Component {

  constructor() {
    super();
    this.state = {
      showUsers: true
    }
  }

  componentDidUpdate() {
    if (this.props.users.length === 0) {
      throw new Error('No user Provided');
    }
  }

  toggleUsersHandler() {
    this.setState((currState) => {
      return {
        showUsers: !currState.showUsers
      }
    });
  };

  render() {
    const usersList = (

        {this.props.users.map((user) => (
          <User key={user.id} name={user.name} />
        ))}

    );

    return (

        <button onClick={this.toggleUsersHandler.bind(this)}>
          {this.state.showUsers ? 'Hide' : 'Show'} Users
        </button>
        {this.state.showUsers && usersList}

    );
  }
}

export default Users;

SO WHEN I TYPE A NAME WHICH IS NOT IN THE USER-LIST, Users.js gets an error. I used error boundaries to display a paragraph saying "something went wrong". But on generating an error, My screen freezes, rather than showing a paragraph. Error boundary is working fine because my app doesn't crash (doesn't show blank screen like first screenshot), this time it only freezes my screen.

A: In the render method of the ErrorBoundary, you do not return the message.
render() {
  if (this.state.hasError === true) {
    return
Error Occured!
;
  }
  return this.props.children;
}


text:
Q: LUIS.AI - moving to a paid plan My chatbot has been down for the last few days (quota for free conversations has been exceeded), and I am seriously thinking of moving to a paid plan.
Please see attached the error returned when initiating a conversation from emulator.
The documentation to move to a paid plan is not clear at all.
Can someone please list the steps that I have to take or pinpoint me to the proper documentation please?
Technology : MS Botframework with nodejs (luis,qna,language detection)
I suppose I have to create a key in azure and insert it in the luis.ai app. But searching for LUIS in azure returns no result.
Grateful if you guys can help.enter image description here

A: Seems you are trying to implement LUIS on azure portal and want to know more about pricing but cannot get LUIS on azure portal.
Well,Follow the below steps to know how you would implement that.
LUIS :
Step 1:
For LUIS go to your azure portal then and click on Create a resource finally search by Language Understanding  you would get that. See the below screen shot:

Step 2:
Once you type Language Understanding you would get below Option. See the screen shot below:

Once you are done with setup you should click Keys and Endpoint to call from your application. See the screen shot below:

though correct official document reference you would get there also given here as well.
1. Luis Official Document
2. Pricing

For your information pricing varies based on Region. Usual price is:
You can do 50 transaction per second  and have to pay $1.5 per 1000
  (one thousand transaction)

QnA Maker :
For QnA maker you could also follow above steps. See the following screen shot:

*

*QnA Maker Official Document

*Pricing
Language Detection:
If you plan to detect your language you could use Text Analytics which provides advanced natural language processing and identify the language of the text with language detection See the screen shot below:

*

*Language Detection Official Document

*Pricing

Note: All the service has language support for Node.js. Hope this would help.


text:
Q: using std::conditional to choose member type based on template parameter Here is my program that attempts to use std::conditional to set the type of a member variable based on the value of an integer template parameter.
#include <stdio.h>
#include <type_traits>
using namespace std;

class cool{
public:
  cool(){ printf("Cool!\n");  }
};

class notcool{
public:
  notcool(){ printf("Not cool!\n");  }
};

template<int N>
class myclass{
public:
  typedef std::conditional<N==5,cool,notcool> thetype;
  thetype theinst;
};

int main(){
  printf("Testing\n");
  myclass<5> myc5;
  myclass<6> myc6;
  printf("Done testing\n");
  return 0;
}

I would expect my program to give the following output:

Testing
Cool!
Not cool!
Done testing

Instead, the output is

Testing
Done testing

My compiler is GCC 4.9, and the way I compiled this program was using the command g++ test -std=c++11 -o test
Can anyone tell me why the program does not give the output I expect?

A: typedef typename std::conditional<N==5,cool,notcool>::type thetype;
//      ^^^^^^^^                                    ^^^^^^

A: thetype is actually not cool, and also not notcool. But std::conditional.
Yes. std::conditional is a type, that's how most type traits are implemented. If you want to get the underlying type from the conditional, you need to access the underlying type member from std::conditional. That's also how most type traits are implemented: They all have a type member which can be used to access the actual type you want, and not the type trait type.
In C++14, you would use std::conditional_t, which is just a alias for the type member of std::conditional, but because you are using C++11, you need to access it explicitly:
typedef typename std::conditional<N == 5, cool, notcool>::type thetype;


text:
Q: C - Seg fault in valid date certificate testing I am trying to manually check wether or not a TLS certificatee is valid based on it's date but I am getting a segmentation fault.
I am trying to do this without using X509_cmp_time.
I believe I am on the right track with this (using openssl 1.0.2) but keep getting segmentation faults. Any advice on how to solve this would be much appreciated!
time_t *tnow;
int *bday, *bsec, *aday, *asec;
ASN1_TIME anow;
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *anow, time_t tnow);
ASN1_TIME *not_before = X509_get_notBefore(cert);
ASN1_TIME *not_after = X509_get_notAfter(cert);
int nbefore = ASN1_TIME_diff(bday, bsec, not_before, NULL);
int nafter = ASN1_TIME_diff(aday, asec, NULL, not_after);


text:
Q: Causality: Models, Reasoning, and Inference: Diagram Question I am self-studying Causality: Models, Reasoning, and Inference, by Judea Pearl, and there is a question I am particularly stumped on. It reads like this:
Problem Statement: Given this fragment of a Bayesian Network, add two variables to the network,
$Z$ and $W,$ such that the following three conditions hold simultaneously:

*

*$Z$ and $X$ are dependent given $W,$ and

*$Z$ and $U$ are independent given $W.$

*$Z$ and $W$ are ancestors of $Y$ but not of $X.$
My Work So Far: Because $Z$ and $W$ must be ancestors of $Y$ but not $X,$ there can be no arrows going into $X$ (from $Z$ or $W$). Because $U$ is an ancestor of $X,$ there can be no arrows going into $U,$ either. Likely, though, we will need arrows going into $Y.$ As I see it, there are essentially two possibilities: arrows going out of $U,$ or arrows going out of $X.$ As we need dependence on $X$ and not $U,$ I'm going to guess that we need arrows going out of $X.$ That means there are essentially four possibilities:

a satisfies 1 and 3, but not 2. b satisfies 2 and 3, but not 1. c satisfies 1 and 3, but not 2. And d satisfies 1 and 3, but not 2.

Do I need to look at $U?$ Or do you have other ideas?

Thanks for your time!

A: If you allow for bidirected edges, you can draw:


text:
Q: trying to make a drawn line move like a laser in javascript I made this red line in JavaScript that goes to closest target (balloon 1 to 3) to the player but I need to make it so that it moves like a laser starting from player position into the target position. I thought about multiple ways of implementing this with no luck.
function Tick() {

  // Erase the sprite from its current location.
  eraseSprite();
  for (var i = 0; i < lasers.length; i++) {
    lasers[i].x += lasers[i].direction.x * laserSpeed;
    lasers[i].y += lasers[i].direction.y * laserSpeed;
    //Hit detection here
  }

function detectCharClosest() {
  var ballon1char = {
    x: balloon1X,
    y: balloon1Y
  };
  var ballon2char = {
    x: balloon2X,
    y: balloon2Y
  };
  var ballon3char = {
    x: balloon3X,
    y: balloon3Y,
  };

  ballon1char.distanceFromPlayer = Math.sqrt((CharX - balloon1X) ** 2 + (CharY - balloon1Y) ** 2);
  ballon2char.distanceFromPlayer = Math.sqrt((CharX - balloon2X) ** 2 + (CharY - balloon2Y) ** 2);
  ballon3char.distanceFromPlayer = Math.sqrt((CharX - balloon3X) ** 2 + (CharY - balloon3Y) ** 2);

  var minDistance = Math.min(
    ballon1char.distanceFromPlayer,
    ballon2char.distanceFromPlayer,
    ballon3char.distanceFromPlayer);

  console.log(ballon1char);
  console.log(ballon2char);
  console.log(ballon3char);
  for (let i = 0; i < 3; i++) {
    if (minDistance == ballon1char.distanceFromPlayer)
      return ballon1char
    if (minDistance == ballon2char.distanceFromPlayer)
      return ballon2char
    if (minDistance == ballon3char.distanceFromPlayer)
      return ballon3char
  }
}

    function loadComplete() {
  console.log("Load is complete.");
  canvas = document.getElementById("theCanvas");
  ctx = canvas.getContext("2d");
  myInterval = self.setInterval(function () { Tick() }, INTERVAL);
  myInterval = self.setInterval(function () { laserTicker(detectCharClosest()) }, 2000);

    function laserTicker(balloon) {
  //gets the closest ballon to go to
    laserDo(balloon);
}

function laserDo(balloon) {
  ctx.beginPath();
  ctx.lineWidth = 2;
  ctx.strokeStyle = "#F44336"; // "red";
  ctx.moveTo(CharX + 16, CharY + 16);
  ctx.lineTo(balloon.x, balloon.y);
  // lasers.push({x: })
  ctx.stroke();
}

I didn't put all of my code here so If something doesn't make sense please tell me. I'm still new to JavaScript and learning it. One way I thought I could make this work was by taking the distance between the player and the target and dividing it by the speed on the x and y axis then changing having it start from the player position and keeps on adding up on both axis until it reaches the target. That didn't work out though. If you have any suggestions then please tell me.
Thanks


text:
Q: How to define HTML keywords in \listings I'm working on the implementation of a HTML5 code style for \listings.
Currently I have the problem that there are different ways to define HTML tags. In my example, I don't get /p in

 marked.
Screenshot:

My keyword definition looks like this:
otherkeywords={>,><,</p,<p,
}

If I add /p to the list, then
 is not marked anymore.
Here is my language definition:
\lstdefinelanguage{HTML5}{
  language=html,
  sensitive=true,
  alsoletter={<>=-},
  morecomment=[s]{<!-}{-->},
  tag=[s],
  otherkeywords={>,><,</p,< which leads to the wrong coloring. The line

is interpreted as the keywords
< followed by /p (which is no keyword) and then again a keyword, >.
Leaving the >< keyword out should suffice. The line the would be interpreted as the keywords
,
, which should be what you want.


text:
Q: Go Back and resubmit form with javascript I have added a back button to a search result page, with a link of:
Back to seach results!

But as this is being used with a form I am being met with a form resubmit page when using chrome, or an alert asking me to resubmit when using IE.
Is there and simple way to force the page to reload so the end user isn't met with either the screen or pop-up
Edit: I am using PHP so if there is a way of using PHP that would be okay too.

A: "No there's no way to prevent that alert. The reason is because the previous page was generated via a form submission, so to return to the page in that state the form submission has to occur again, hence the warning. The alternative would be to store the form parameters and have the back button resubmit the form manually"
Credit to Rory McCrossan

A: Yes there is a way. Add this to the page that has the 'Confirm Resubmit' popup


text:
Q: BTRFS unmountable after cold reboot (total_rw_bytes is twice too big) One of my users in research environment invoked out-of-memory on a server which mounts a 52TB btrfs partition. I had to power cycle the server.
After the reboot my btrfs partition cannot be mounted in read-write mode.

mount /mnt/storage/
mount: /mnt/storage: wrong fs type, bad option, bad superblock on /dev/mapper/fc_trunk-part3, missing codepage or helper program, or other error.

Kernel logs show a problem with device size:

Mar 19 15:10:52 mamut kernel: BTRFS error (device dm-5): open_ctree failed
Mar 19 15:10:52 mamut kernel: BTRFS info (device dm-5): use lzo compression, level 0
Mar 19 15:10:52 mamut kernel: BTRFS info (device dm-5): disk space caching is enabled
Mar 19 15:10:52 mamut kernel: BTRFS info (device dm-5): has skinny extents
Mar 19 15:10:52 mamut systemd[1]: mnt-storage.mount: Mount process exited, code=killed, status=15/TERM
Mar 19 15:10:52 mamut systemd[1]: mnt-storage.mount: Failed with result 'timeout'.
Mar 19 15:10:52 mamut systemd[1]: Failed to mount /mnt/storage.
Mar 19 15:10:52 mamut kernel: BTRFS error (device dm-5): super_total_bytes 52798547820544 mismatch with fs_devices total_rw_bytes 105597095641088
Mar 19 15:10:52 mamut kernel: BTRFS error (device dm-5): failed to read chunk tree: -22
Mar 19 15:10:52 mamut kernel: BTRFS error (device dm-5): open_ctree failed
[...]
Mar 19 15:15:52 mamut systemd-helper[9798]: IO Error (subvolume is not a btrfs subvolume).
Mar 19 15:15:52 mamut systemd-helper[9798]: number cleanup for 'storage' failed.
Mar 19 15:15:52 mamut systemd-helper[9798]: running timeline cleanup for 'storage'.
Mar 19 15:15:52 mamut systemd-helper[9798]: IO Error (subvolume is not a btrfs subvolume).
Mar 19 15:15:52 mamut systemd-helper[9798]: timeline cleanup for 'storage' failed.
Mar 19 15:15:52 mamut systemd-helper[9798]: running empty-pre-post cleanup for 'storage'.
Mar 19 15:15:52 mamut systemd-helper[9798]: IO Error (subvolume is not a btrfs subvolume).
Mar 19 15:15:52 mamut systemd-helper[9798]: empty-pre-post cleanup for storage failed.
Mar 19 15:15:52 mamut systemd[1]: snapper-cleanup.service: Main process exited, code=exited, status=1/FAILURE
Mar 19 15:15:52 mamut systemd[1]: snapper-cleanup.service: Failed with result 'exit-code'.

The super_total_bytes=52798547820544 is the correct size of the partition in bytes reported by fdisk.
fs_devices total_rw_bytes=105597095641088 is exactly twice of that.
I tried running btrfs check but got this error:

btrfs check /dev/mapper/fc_trunk-part3
Opening filesystem to check...
Checking filesystem on /dev/mapper/fc_trunk-part3
UUID: 40a2e65b-f34a-4d33-946d-055d93fe7ffa
[1/7] checking root items
ERROR: failed to repair root items: Input/output error

Now, I know about btrfs rescue fix-device-size, but I have never ran it before. The man page says:

fix-device-size
           fix device size and super block total bytes values that are do
           not match

           Kernel 4.11 starts to check the device size more strictly and
           this might mismatch the stored value of total bytes. See the
           exact error message below. Newer kernel will refuse to mount the
           filesystem where the values do not match. This error is not fatal
           and can be fixed. This command will fix the device size values if
           possible.

               BTRFS error (device sdb): super_total_bytes 92017859088384 mismatch with fs_devices total_rw_bytes 92017859094528

           The mismatch may also exhibit as a kernel warning:

               WARNING: CPU: 3 PID: 439 at fs/btrfs/ctree.h:1559 btrfs_update_device+0x1c5/0x1d0 [btrfs]

Kernel version did change after reboot, but both versions are > 4.11 and previously I had no problems mounting this partition.
The partition:

*

*is big and will take a lot of time, and space I don't have, to back up

*has critical data for my research

*has snapshots

*it is possible to mount it with -o rescue,ro

Is it safe to call  btrfs rescue fix-device-size?
Can I fix it in some other safe way?

A: "Is it safe to call btrfs rescue fix-device-size?"
It's potentially safe, and this is very likely the solution. It "shouldn't" eat your entire volume and several cats. If this BTRFS filesystem has multiple disks (for example, in a BTRFS RAID), I'm suddenly less confident in this assertion.
If you have a block based snapshot mechanism below BTRFS (it looks like you might - is that an LVM volume backing it?) then take a snapshot prior to doing this. You may need to add more physical volumes to that volume group in order to accommodate the snapshot itself depending on how this volume group (if that's what it is) is already allocated. An LVM snapshot will grow in size as data is modified, proportionate to the amount of data modified. An LVM snapshot will also incur a 2x write performance hit while active, so don't keep it around after you're done. This is just so you can roll back if things go very badly.
If it's really important data, do a block based backup to another totally unrelated volume before doing anything - especially if you're not intimately familiar with LVM snapshots or this isn't on LVM. dd is a good command for that.
dd if=/dev/disk/with-btrfs of=/large/enough/volume/backup.img bs=4M

A: I had a similar problem about the size mismatch between super_total_bytes and fs_devices total_rw_bytes with a large btrfs volume on top of a md device.  When trying to mount at boot, I got the message BTRFS error super_total_bytes XXX mismatch with fs_devices total_rw_bytes XXXXXX.  Here is a link to the site that describes the problem and the fix of running btrfs scan device
In my case, I was fortunate that it would fail on the first try at boot but would then successfully mount if I manually ran the mount command.  I guess there is a race condition between when mdadm reassembled the /dev/md127 device and when the kernel/systemd identified that there are btrfs volumes to be mounted.  The kernel sees there are two drives that belong to the volume because /dev/md127 and, say, /dev/sdb both have the same UUIDs because /dev/sdb is the leading component of /dev/md127 that contains the beginning of the btrfs volume.
I resolved this by creating a new systemd unit, btrfs-scan-device.service, that just runs btrfs scan device, and made it a dependency in /etc/fstab mount options for the md device.  That probes the devices under /dev for btrfs volumes.
/etc/systemd/system/btrfs-device-scan.service:
[Unit]
Description=run btrfs device scan before mounting so that mdadm devices are not misdetetected
Requires=local-fs.target
After=local-fs.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/btrfs device scan
StandardOutput=journal

[Install]
WantedBy=multi-user.target

/etc/fstab entry:
/dev/md127  /md127  btrfs  noatime,nofail,x-systemd.mount-timeout=1000,x-systemd.requires=btrfs-device-scan.service,x-systemd.after=btrfs-device-scan.service       0       0

Then systemctl daemon-reload and systemctl enable btrfs-device-scan and reboot.
With these changes, I no longer have the size mismatch error.  I did not have the IO Errors you are seeing.


text:
Q: TF2 map download hanging I'm not sure if anybody else has had this issue, but I've noticed lately that I seem to be having problems downloading custom maps while TF2 is loading.
Case in point, yesterday I tried to join a server that ran ctf_mach4, and when it went to download the map (straight .bsp file) it hung at 0%.
After a few minutes of non-activity, I went back to the server listing and saw that the server definitely was still active and playing that map, so it wasn't a case of the server changing.
Any thoughts?  I've also had this happen before, but never thought to document it.  I'm sure I can download it offline and just stick it in my steam directory, but I was curious if anybody else has had this problem.

A: This entirely depends on the server and its settings. Try joining another server running the same map.
You can read more on how TF2 handles custom maps here and here.

A: Some servers run cvars (or plugins) which disable clients from downloading content. Not everyone is willing to deal with the bandwidth needed to constantly feed maps to new players. This seems to be the case, yet somehow it did not disconnect you with any useful notification.
It's typically faster to just get the map from a site like:
GameBanana: http://www.gamebanana.com/maps/games/297
TF2Maps.net: http://tf2maps.net/
However servers can be configured to provide you with speeds as fast as from a website, but it takes dedication on the case of the administrator for that to happen. Not everyone knows how to do it too.


text:
Q: Java:User Enter Antilog Base issue? I'm finding anti-logarithm of enter values.Answer will be right with natural log base.But when try to find anti-log with enter base.then it doesn't give correct answer such as anti-log value 10 with base 10 = 10000000000

This is my code:
    public class A {

public static void main(String[] args) {
    Scanner s = new Scanner(System. in );
    double value, res, value2, res2;
    System.out.print("Enter Anti Log Value:");
    value = s.nextDouble();
    res = Math.exp(value);
    System.out.println("Answer Of Antilog With natural Base is: + res);
    System.out.println("-----------------------------------");
    System.out.print("Enter Your Base:");
    value2 = s.nextDouble();
    res2 = Math.exp(value) / Math.exp(value2);
    System.out.println("Answer Of Antilog With your enter Base is : " + res2);
}
}

It give answer with enter base 10 = 1.0 so how to fix this.

A: Assuming I understand your question correct you should simply replace
res2 = Math.exp(value) / Math.exp(value2);

with
res2 = Math.pow(value2, value);

If you want to avoid scientific notation when printing the value, use:
System.out.printf("Answer Of Antilog With your enter Base is : %f%n", res2 );

or (to skip the decimals):
System.out.printf("Answer Of Antilog With your enter Base is : %.0f%n", res2 );


text:
Q: Dynamic Pivot Table by Month I'm trying to create a dynamic pivot table in SQL that will report based on month and year.  I did a bunch of research and was able to come up with the below query:
declare @dynamic nvarchar(max),
@column nvarchar(max);

set @column = N'';
select @column += N'' + datename(month,incurdate) +' '+ datename(year,incurdate) + ','
from (select distinct a.incurdate from artable a) as Transpose

select @column = substring(@column,0,len(@column))

set @dynamic = 'select * from
 (
select month, incurdate, dolamount
from artable join dolentry on month = period
) b
pivot(sum(dolamount) for incurdate in (' + @column + ')) as PivotTable'

execute sp_executesql @dynamic

I am able to print the @column variable successfully, but the problems happen when I try to set it in the @dynamic variable.  The error message is 'Msg 102, Level 15, State 1, Line 6
Incorrect syntax near '1990'.'  1990 is the first year of the first pivoted column.  Any help or tips are appreciated.  Thanks!

A: You need to use QUOTENAME in the following code:
select @column += N'' + QUOTENAME(datename(month,incurdate) +' '+ datename(year,incurdate)) + ','
from (select distinct a.incurdate from artable a) as Transpose

in order to get output like this:
[col01], [col02], [col03], ... , [col04]

As you can see from the docs, the PIVOT syntax requires the pivoting columns to be wrapped in square brackets:
SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,
    ...
    [last pivoted column] AS <column name>
FROM
    (<SELECT query that produces the data>)
    AS <alias for the source query>
PIVOT
(
    <aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
    IN ( [first pivoted column], [second pivoted column],
    ... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;


text:
Q: Copy all the groups from AD user to another In the company I work there are 2 domains. The first is the main domain and there is another sub-domain with trust relationship.
I have tried to create a PowerShell script that when we create a new user, we can set a source username and copy all the groups he is a member of to a new user.
For each user there are groups from both the main and the secondary domain
I have created a script in PowerShell to copy the groups, but if the new user is in the sub-domain the only groups that will be added are the groups in the sub-domain, and if he is in the main domain, the groups he will be added to are in the main domain.
How can I make sure that all the groups will be added?
import-Module ActiveDirectory

# Collect the source and target users

$Source = Read-Host "Enter logon name of source user"
$Target = Read-Host "Enter logon name of target user"

# Set the domain for the user

$domain_Source=$null

$domainval = Read-Host -Prompt 'Enter 1 for lpnet 2 for Sub-DB for the Source
username'

if ($domainval -eq 1)
{
$domain_Source = "main.lpnet.com"
}
if ($domainval -eq 2)
{
$domain_Source = "sub-db.lpnet.com"
}

Get-ADUser -Identity $Source -Server $domain_Source -Properties memberof |
Select-Object -ExpandProperty memberof|
Add-ADGroupMember -Members $Target -PassThru |
Select-Object -Property SamAccountName


text:
Q: PDO duplicate insert loop Help.  I'm converting some code from the old mysql library to use PDO.
In several places, we attempt an INSERT knowing full well that there may be be a violation on a duplicate key.  This is fine, we look for it and continue processing.   All that works without issue.
In one place, we have to loop through and add multiple items so I'm using a prepared statement with parameter binding.  If we don't encounter any duplicates on INSERT, it works fine.  However, if there is a duplicate key violation, the following PDO->execute() fails silently, no exception, nothing.
Here is my code at present:
<?php
$db = new PDO("mysql:host=localhost;dbname=".$dbname, $mysqluser, $mysqlpwd,
                array(PDO::ATTR_EMULATE_PREPARES => false,
                      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

$stmt = $db->prepare("insert into trials (uid,name,start_date,expire_date) values (:uid,:node,FROM_UNIXTIME(:start),FROM_UNIXTIME(:end))");
$stmt->bindValue(':uid', $uid, PDO::PARAM_STR);
$stmt->bindParam(':node', $node, PDO::PARAM_STR);
$stmt->bindValue(':start', $start);
$stmt->bindValue(':end', $end);

foreach ($nodes as $node) {
    if (isfreenode($node))
        continue;

    try {
        $stmt->execute();  // <-- This is where it fails
    } catch (exception $e) {
        $errorInfo = $stmt->errorInfo();
        if ($errorInfo[1] = 1062) {
            print "Trial already exists (" . $node . ") - skipping
";
        } else {
            throw $e;
        }
        $stmt->closeCursor();
        continue;
    }
    print "Started Trial ( " . $uid . " , " . $node . " )" . "
";
    removeRevocation($uid, $node);
    $stmt->closeCursor();
}

}
Any suggestions on what I can try to at least see why it's dying?


text:
Q: Automate fetching of group id in Yammer How do you get the group id in Yammer?
I am able to post a message in all of the company as well as to a specific group but i am not able to get the group id of a particular group using Yammer APIs
Find below the code for posting in a particular group where group_id is a string variable whose value I enter manually and want to automate this process.
private void Post(string address)
    {
        System.Uri targetUri = new System.Uri(https://www.yammer.com/api/v1/messages.json?body=HelloTest&group_id=[some_number]&access_token=" + token);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
        request.Method = "POST";
        request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
    }

// STEP4 STEP4 STEP4
    private void ReadWebRequestCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
        string results;
        using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
        {
            results = httpwebStreamReader.ReadToEnd();
            //TextBlockResults.Text = results; //-- on another thread!
            SkyDriveContent test = new SkyDriveContent();
            test.Name = results;
            str_results = results;

        }
        myResponse.Close();
    }

I saw the documentation but did not find any way to get the list of groups a user is a part of?
Any help would be appreciated!

A: You should be able to get the list of groups that a user belongs to by making a GET request to https://www.yammer.com/api/v1/groups.json?mine=1. It looks like you are using HttpWebRequest for your client code. If you haven't done so I'd suggest checking out RestSharp as it'll cut down on the amount of code you have to write.


text:
Q: Can't get ant to work, trying to install Clojure I have been attempting to install Clojure on Ubuntu using the directions found here:
http://riddell.us/ClojureOnUbuntu.html
For starters, that version of Java no longer seems to be supported- so I installed the Open JDK version 7 and have been attempting to use ant with that.  Problem is, whenever I type sudo ant to begin the build in the Clojure folder, I get:
Unable to locate tools.jar. Expected to find it in /usr/lib/jvm/java-6-openjdk/lib/tools.jar
Buildfile: /home/nathan/opt/clojure/build.xml

And then eventually:
BUILD FAILED
/home/nathan/opt/clojure/build.xml:40: java.lang.UnsupportedClassVersionError: com/sun
/tools/javac/Main : Unsupported major.minor version 51.0

Note that at first it would fail because it could not locate tools.jar, but then I copied tools.jar from the jvm directory where the most recent version was located to usr/share/ant/lib to try and make it work.  Anyone have leads or advice how to get this to work?
Thank you kindly!

A: My apologies for the lingering outdated documentation from
The bad old days before leiningen, and zi (clojure maven plugin)
Nobody* installs clojure anymore in the sense that you would install any other program,
instead they install a standard java build tool (Maven2/3) and then use that tool to build their clojure programs. both leiningne and zi are built ontop of maven and you should choose between them. There is still some lingering traces of the days when people built Clojure code with Ant and if you come across one of these (and have no explicit reason to use And) ignore it and try lieningen or zi.

*

*leiningen is more widely adopted and installs as a single .sh or .bat file you download

*you get zi by adding it as a plugin in your projects pom.xml

*another very popular clojure maven plugin is available here

A: For the most part, the Clojure material on riddell.us is insanely out of date and should be completely ignored and banished from all Clojure search results. With that in mind, if you'd just like to do some Clojure development on Ubuntu, simply install Leiningen, create a new project (lein new my-project) and start hacking. Generally, you never "install" Clojure on your system. It's used as a library of your project, which is handled by Leiningen.
On the other hand, if you actually want to hack on Clojure itself, follow the build instructions in the README on the Clojure github page.


text:
Q: How do I search for a pip package by name only? By default pip searches both package names and descriptions. For some packages this results in a huge number of spurious hits and finding the one I actually want is a pain.
How I tell pip I want to search by name only?

A: Well, on Linux/OSX not to hard to do something semi-manual with a bit of grep/egrep (OSX tends to require you to use egrep for regex, Linux doesn't).
The search below returns a lot of stuff (41 actually if you pip it through to wc).
pip search psycopg
first few lines of ouput:
gevent-psycopg2 (0.0.3)              - pip-installable package for patching psycopg2 to use gevent
django-psycopg2-pool (0.1.1)         - A db backend for Django using the gevent psycopg2-pool
pg4nosql (0.4.2)                     - A simple psycopg2 based wrapper for nosql like database interaction with python.
zope.psycopgda (1.1.1)               - Psycopg Database Adapter for Zope 3
qmarkpg (0.2)                        - A psycopg2 wrapper using the qmark parameters style

But if you look at the pip output you see that the packaname field tends to terminate with version names - psycopg (1.1.21)
So, write this instead:
pip search psycopg | egrep "^.*psycopg.*\("
output:
gevent-psycopg2 (0.0.3)              - pip-installable package for patching psycopg2 to use gevent
django-psycopg2-pool (0.1.1)         - A db backend for Django using the gevent psycopg2-pool
zope.psycopgda (1.1.1)               - Psycopg Database Adapter for Zope 3
psycopg2-managed-connection (1.0.0)  - Thread-safe connection manager for psycopg2 connections.
db-psycopg2 (0.0.7)                  - psycopg2 driver for db
kr-impatient-psycopg2 (2.5.2.dev0)   - Python-PostgreSQL Database Adapter
tornado-psycopg2 (0.3.1)             - Tornado driver for support asynchronous mode for psycopg2.
psycopg2 (2.6.1)                     - psycopg2 - Python-PostgreSQL Database Adapter
psycopg2-dateutils (0.1)             - Use dateutils.relativedelta to represent PostgreSQL interval types
psycopg2ct (2.4.4)                   - An implementation of the psycopg2 module using ctypes.
psycopgwrap (1.05)                   - A wrapper around psycopg2 to make common things easier.
psycopgda (1.0)                      - Psycopg Database Adapter for Zope 3
psycopg-postgis (0.1.1)              - Pyscopg helpers to work with PostGIS.
psycopg2cffi (2.7.2)                 - .. image:: https://travis-ci.org/chtd/psycopg2cffi.svg?branch=master
psycopg2cffi-compat (1.1)            - A Simple library to enable psycopg2 compatability
little_pger (0.65)                   - A thin layer just a tad above SQL, for use with PostgreSQL and psycopg2, when you want to wrap queries in a convenient way, using plain data structures (but you don't feel like using an ORM, for some reason).
psycopg (1.1.21)                     - Python-PostgreSQL Database Adapter
psycopg2da (2.0.9)                   - Python psycopg2 database adapter for Zope

This assumes that there are no parenthesis within package name, of course.
as a reusable bash function (put in .profile or the like):
pipsearchpackagename(){
    #a bash function.
    pip search $1 | egrep "^.*"$1".*\("
}

A: It is not possible at the moment, because the current implementation (pip 8.1.1) does a name OR summary query hard-coded in pip search command, though the PyPI XML RPC supports different queries.


text:
Q: What is the purpose of Access URL Variables in AMP? Where and how are they used? Can you please provide an explanation of Access URL Variables in AMP, their purpose and how and where they are used?
For example, can you please provide a step by step example of how you integrated them into an amp-story?
the official amp-access sample for demos of first-click-free and view counting

*

*https://rocky-sierra-1919.herokuapp.com/

*https://cdn.ampproject.org/experiments.html

A: From the amp-access documentation:

When configuring the URLs for various endpoints, the Publisher can use
  substitution variables. The full list of these variables are defined
  in the AMP Var
  Spec.
  In addition, this spec adds a few access-specific variables such as
  READER_ID and AUTHDATA.

Access URL variables allow you send vital information regarding the user or the session by including them in the URL. The best example would be READER_ID, which can be used to uniquely identify each user.
For eg. consider you have set up authorization endpoint in your amp-access configuration as follows :
https://publisher.com/amp-access.json?rid=READER_ID&url=SOURCE_URL
Then authorization call from your page will go with the variables READER_ID and SOURCE_URL substituted as follows:
https://publisher.com/amp-access.json?rid=amp-s90UCBp2NixS3-wpVmKsSw&url=http%3A%2F%2Flocalhost%3A8000%2Famp.html&__amp_source_origin=http%3A%2F%2Flocalhost%3A8000
Now your backend server can identify users uniquely by checking the url parameter rid and get the source url from url parameter url. You can use all of the Access URL variables similarly. For more info refer AMP-Access Docs and AMP-Access Example


text:
Q: What is the best way to send and detect cookie in java application? When a user visits www.example.com for the first time, how can I detect if the client browser has cookies enabled and if so send the cookie to the client without resorting to sending redirect request(s) ( HTTP 302 request)? If redirect must be done then what is the best way to send cookie without doing multiple redirects or search engine bot unfriendly redirects? My java application needs to create cookie based account very quickly the very first time visitor goes to example.com. After that subsequent visits would recognize the user based on this cookie.
This solution should not be based on Javascript as it still needs to work if JavaScript is disabled.

A: First up - it's not possible to tell (definitively) if a client supports cookies or not until you've set one.  And if you're doing this server-side, since cookies are sent as part of the HTTP request, you will have to issue some kind of redirect to make this check:
   client                  server
1a. GET index.html ---->
1b.            <------------ sets a cookie, redirect to index.html?foo=bar
2. GET index.html?foo=bar -->

Using Javascript does let you get around this, as you can at least query whether the cookie was set on the client side without requiring the client to make another request - but it's Javascript, as you say.
Note that this kind of check is not exactly robust; it doesn't really validate that the cookies will stay around in any useful way (for example, an anti-spyware program may be clearing cookies every 30 minutes).  It doesn't even validate that you'll be able to set the next cookie (especially if it's on a different subdomain; or the user may have asked the UA to prompt for each cookie, so just because this cookie is accepted doesn't mean the next one will be).  And the next time the user logs in it may be from a different browser (with different settings), or they changed their security settings on this one, etc.
Really, I'd think of this in the same way as client-side form validation - it's nice to be able to warn your visitors when they're trying something that just isn't going to work, but you can't really rely on it being correct.  And in that context your last sentence is a little worrying - since you say it needs to work.  What are the consequences if this test is wrong (i.e. you think you can set cookies but you actually can't)?  I'm not saying that your site needs to work without cookies, just that you need to realise your checks may well give false positives, and you need to be aware of this.
So in that context I'd say it probably is better to do the check in Javascript; if someone has JS and cookies disabled, they aren't going to be able to interact with the majority of sites that have some kind of login.  When you receive a request without cookies, you have to send back an "Ooops, it looks like you have cookies disabled page" anyway, so it's hardly game-breaking if the initial check was skipped.


text:
Q: Capturing X,Y co-ordinates of pixel in Ti.paint titanium/android Here i am facing a little problem , i am using Ti.paint module provided by the titanium appcelerator. The question is can I have all the x and y pixel co-ordinates on some event listener?I used this
    var paintView = Paint.createPaintView({
    top : 0,
    right : 0,
    bottom : 80,
    left : 0,
    strokeColor : '#0f0',
    strokeAlpha : 255,
    strokeWidth : 10,
    eraseMode : false
});

paintView.addEventListener('touchmove', function(e) {

    Ti.API.info('listener called ' + e.x + ',' + e.y);
});

But it do not capture all the X,Y co-ordinated it skips some of them.Painting slowly will capture almost all colored pixels co-ordinates but painting rapidly, skiping some pixel co-ordinated.Please help regarding this.
Ali

A: The touch move event is throttled so that your code doesn't get overloaded.
If you absolutely need to get every point, then you need to cross over in to Java land and customize the paint module to your needs.
The module's source code is available here: https://github.com/appcelerator/titanium_modules/tree/master/paint/mobile/android


text:
Q: Move pointer in arrays with C Is there anyway I can move the pointer in the array. So, like you move where the pointer is pointing at in the array. For files, I know that you can use fseek with something like fread to only copy from a specific location.
I'm trying to copy parts of an array into different files. With fwrite, it doesn't give the option to start from a specific location, so I'll need to move the pointer to somewhere in the array, then copy a part of the array into a file.

A: sure you can move a pointer. Say we have an array of ints
int arr[50];

set p to point at the first element
int*p = &arr[0];

now move it along by 10
p += 10;

p now points at arr[10];
Addition on a pointer is defined as incrementing the pointer by n times the size of each elements. Subtraction works too. Be aware of going off either end though, C wont look out for you. Ie this
p += 500;

will compile but will lead to undefined behavior if you try to use p;


text:
Q: How to enable Bluetooth in kivy(python framework) android app I built an android app using kivy and buildozer. It is similar to obd2 apps like torque. I want to connect my app to car through Bluetooth to get live car engine data and diagnostic trouble codes. I am using python-OBD api (https://python-obd.readthedocs.io/en/latest/).
When I click on GET RPM I get none because no connection to car

I am able to connect in local computer through virtual elm emulator(https://github.com/Ircama/ELM327-emulator).
in virtual machine(ubuntu)
in one terminal I am running emulator(and I mention port number connection = obd.OBD("/dev/pts/2")
in another terminal I am running my code.
I am getting rpm responses when I click on GET RPM button every time

(But how to get in android app)
source code
import obd
import kivy
from cgitb import text
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput

connection = obd.OBD("/dev/pts/2")
# print(connection.query(obd.commands.RPM))

class obdApp(App):
    def build(self):
        self.window = GridLayout()
        #add widgets to window
        self.window.cols = 1

        # style
        self.window.size_hint = (0.6, 0.7)
        self.window.pos_hint = {"center_x": 0.5, "center_y": 0.6}
        #self.window.size_hint_y = None

        self.greeting = Label(
            text = "command lookup",
            font_size = 24,
            color = 'red'
            )
        self.window.add_widget(self.greeting)

        self.button = Button(text = "GET RPM")
        self.button.bind(on_press = self.callbackrpm)
        self.window.add_widget(self.button)

        self.button = Button(text = "GET SPEED")
        self.button.bind(on_press = self.callbackspeed)
        self.window.add_widget(self.button)

        self.button = Button(text = "GET FUEL_TYPE")
        self.button.bind(on_press = self.callbackfuel)
        self.window.add_widget(self.button)

        return self.window

    def callbackrpm(self, instance):
        self.greeting.text = str(connection.query(obd.commands.RPM))
    def callbackspeed(self, instance):
        self.greeting.text = str(connection.query(obd.commands.SPEED))
    def callbackfuel(self, instance):
        self.greeting.text = str(connection.query(obd.commands.FUEL_TYPE))

if __name__ == "__main__":
    obdApp().run()


text:
Q: Elementary proof that $a_n \to a \implies a_n^r \to a^r$ for $r \in \mathbb{Q}$ I've been looking for an elementary proof of the fact that rational exponentiation is continuous (for sequences). Let $r = p/q \in \mathbb{Q},$ with $p,q \in \mathbb{N}.$ Assuming $|a_n - a| \to 0,$ we have
$$|a_n^r - a^r| = |(a_n^{1/q})^p - (a^{1/q})^p| = \left|a_n^{1/q} - a^{1/q}\right|\left|\sum_{i=0}^{p-1} a_n^{p-1-i}a^i\right|.$$
Is there a way to bound this further in terms of $|a_n - a|$ to conclude?
Thank you.

A: We need to establish the following inequalities $$rx^{r - 1}(x - y) > x^{r} - y^{r} > ry^{r - 1}(x - y)$$ and $$sx^{s - 1}(x - y) < x^{s} - y^{s} < sy^{s - 1}(x - y)$$ where $x > y > 0$ and $r > 1, 0 < s < 1$ with $r, s \in \mathbb{Q}$. Also these inequalities need to be established via algebra. I will establish here the inequalities related to $r > 1$.
Let $\alpha > 1$ be a real number and assume $r$ is a positive integer. Then we can easily see that $$r\alpha^{r} > \alpha^{r - 1} + \alpha^{r - 2} + \cdots + 1$$ so that $$r\alpha^{r}(\alpha - 1) > \alpha^{r} - 1$$ Adding $r(\alpha^{r} - 1)$ on each side we get $$r(\alpha^{r + 1} - 1) > (r + 1)(\alpha^{r} - 1)$$ and finally $$\frac{\alpha^{r + 1} - 1}{r + 1} > \frac{\alpha^{r} - 1}{r}$$ It thus follows that the expression $\dfrac{\alpha^{r} - 1}{r}$ increases with $r$ and therefore if $r, s$ are positive integers with $r > s$ then $$\frac{\alpha^{r} - 1}{r} > \frac{\alpha^{s} - 1}{s}\,\,\,\cdots (1)$$ It follows that if $r$ is a positive integer and $r > 1$ then $$\frac{\alpha^{r} - 1}{r} > \frac{\alpha^{1} - 1}{1}$$ so that $$\alpha^{r} - 1 > r(\alpha - 1)\,\,\,\cdots (2)$$ Similarly we can show that if $0 < \beta < 1$ then $$\frac{1 - \beta^{r}}{r} < \frac{1 - \beta^{s}}{s}\,\,\,\cdots (3)$$ and $$1 - \beta^{r} < r(1 - \beta)\,\,\,\cdots (4)$$ if $r > 1$.
The inequalities above have been proved with restriction that $r, s$ be positive integers. This can be easily extended to the case when $r, s$ are rational. Let $r = a/b, s = c/d$ where $a, b, c, d$ are positive integers and then $r > s$ implies that $ad > bc$. Let $\gamma = \alpha^{1/bd}$ so that $\alpha = \gamma^{bd}$ then $\gamma > 1$ and hence by $(1)$ we get $$\frac{\gamma^{ad} - 1}{ad} > \frac{\gamma^{bc} - 1}{bc}$$ or $$\frac{\alpha^{r} - 1}{r} > \frac{\alpha^{s} - 1}{s}$$ Similarly all the inequalities $(2), (3), (4)$ can be extended to rational values of $r, s$.
Next if $\alpha > 1$ then $0 < 1/\alpha < 1$ and $0 < \beta < 1$ implies $1/\beta > 1$. Therefore writing $1/\beta$ for $\alpha$ in $(2)$ and $1/\alpha$ for $\beta$ in $(4)$ we get $$\alpha^{r} - 1 < r\alpha^{r - 1}(\alpha - 1)\,\,\,\cdots (5)$$ and $$1 - \beta^{r} > r\beta^{r - 1}(1 - \beta)\,\,\,\cdots (6)$$ If $x > y > 0$ then we can put $\alpha = x/y$ and $\beta = y/x$ in the above inequalities and get $$rx^{r - 1}(x - y) > x^{r} - y^{r} > ry^{r - 1}(x - y)$$
Using these inequalities it is possible to bound $|a_{n}^{r} - a^{r}|$ in terms of $|a_{n} - a|$ and you can complete your proof easily.
Update: This is essentially the elementary technique used to prove continuity of $f(x) = x^{r}$ for $x > 0$ and $r \in \mathbb{Q}$ and if you notice carefully it can also be used to establish the differentiation formula $(x^{r})' = rx^{r - 1}$.


text:
Q: Debug.WriteLine effecting non debug performance Running .exe the presence of the Debug.WriteLine() effects performance 8x.
How can a Debug statement effect performance not in debug?
How can I have a Debug not effect .exe performance?
counterRequals is referenced after so it cannot just skip.
This if is hit over 1 billion times.
if (innerInnerLoopCount > 1 && r == innerInnerLoopCount)
{
    counterRequals++;
    Debug.WriteLine("");
}

A: Debug members have the ConditionalAttribute assigned to them so they won't be present in Release mode. It sounds like you're running the Debug build without the debugger. If you need Debug like functionality, consider using the Trace class instead although you'll possibly hit perf issues with 1bn hits. If that's the case, you could look at EventSource which can allow for high performance logging.


text:
Q: Website Messed Up Only If Accessed In Past So my website: ropinranch.com
looks FINE on any browser (so far) if you haven't accessed the page in the past. But for any of my previous users, it looks messed up when they load it.
We've all cleared all of our cookies, and emptied our cache. I even edited a new image on the page to see if that would change and it DID.
I cannot think any other way the page would be keeping memory of it.
One of my testers said that if they had the page bookmarked in the past of it working fine, that when clicking on the bookmark it loads fine still -- but typing in a URL fails.
Any other ideas on what I'm missing here?
Update: I realized what happened -- but I'm unsure how to fix.
https://ropinranch.com WORKS
but
www.ropinranch.com does not. I know theres a setting in my c-pannel to change this but I don't know what it's called

A: Try ctrl+F5 to reload the page without caching.

A: This helped me temporarily:
By Varun: If you are just testing, could you try passing a timestamp or random number in the URL ( manually , just for testing ) and check. Eg : http://ropinranch.com?f=141414542343 (each time with a diff number )
But What I did was I had to go through the server and reroute all traffic to my SSL site rather than things of www. or http://


text:
Q: Angular 2 - Routing - CanActivate work with Observable I have an AuthGuard (used for routing) that implements CanActivate.
canActivate() {
    return this.loginService.isLoggedIn();
}

My problem is, that the CanActivate-result depends on a http-get-result - the LoginService returns an Observable.
isLoggedIn():Observable<boolean> {
    return this.http.get(ApiResources.LOGON).map(response => response.ok);
}

How can i bring those together - make CanActivate depend on a backend state?
# # # # # #
EDIT: Please note, that this question is from 2016 - a very early stage of angular/router has been used.
# # # # # #

A: Updating Kery Hu's answer for Angular 5+ and RxJS 5.5 where the catch operator is deprecated. You should now use the catchError operator in conjunction with pipe and lettable operators.
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { catchError, map} from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private loginService: LoginService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>  {
    return this.loginService.isLoggedIn().pipe(
      map(e => {
        if (e) {
          return true;
        } else {
          ...
        }
      }),
      catchError((err) => {
        this.router.navigate(['/login']);
        return of(false);
      })
    );
  }

}

A: I've done it in this way:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.userService.auth(() => this.router.navigate(['/user/sign-in']));}

As you can see I'm sending a fallback function to userService.auth what to do if http call fails.
And in userService I have:
import 'rxjs/add/observable/of';

auth(fallback): Observable<boolean> {
return this.http.get(environment.API_URL + '/user/profile', { withCredentials: true })
  .map(() => true).catch(() => {
    fallback();
    return Observable.of(false);
  });}

A: This may help you
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { map, take } from 'rxjs/operators';
import { AuthState } from 'src/app/shared/state';

export const ROLE_SUPER = 'ROLE_SUPER';

@Injectable()
export class AdminGuard implements CanActivate {

    @Select(AuthState.userRole)
    private userRoles$: Observable<string[]>;

    constructor(private router: Router) {}

    /**
     * @description Checks the user role and navigate based on it
     */

    canActivate(): Observable<boolean> {
    return this.userRoles$.pipe(
        take(1),
        map(userRole => {
        console.log(userRole);
        if (!userRole) {
            return false;
        }
        if (userRole.indexOf(ROLE_SUPER) > -1) {
            return true;
        } else {
            this.router.navigate(['/login']);
        }
        return false;
        })
    );
    } // canActivate()
} // class

A: You should upgrade  "@angular/router" to the latest . e.g."3.0.0-alpha.8"
modify AuthGuard.ts
@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private loginService: LoginService, private router: Router) {}

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return this.loginService
            .isLoggedIn()
            .map((e) => {
                if (e) {
                    return true;
                }
            })
            .catch(() => {
                this.router.navigate(['/login']);
                return Observable.of(false);
            });
    }
}

If you have any questions, ask me!

A: canActivate() accepts Observable<boolean> as returned value. The guard will wait for the Observable to resolve and look at the value. If 'true' it will pass the check, else ( any other data or thrown error ) will reject the route.
You can use the .map operator to transform the Observable<Response> to Observable<boolean> like so:
canActivate(){
    return this.http.login().map((res: Response)=>{
       if ( res.status === 200 ) return true;
       return false;
    });
}

A: in canActivate(), you can return a local boolean property (default to false in your case).
private _canActivate: boolean = false;
canActivate() {
  return this._canActivate;
}

And then in the result of the LoginService, you can modify the value of that property.
//...
this.loginService.login().subscribe(success => this._canActivate = true);

A: CanActivate does work with Observable but fails when 2 calls are made like CanActivate:[Guard1, Guard2].
Here if you return an Observable of false from Guard1 then too it will check in Guard2 and allow access to route if Guard2 returns true.
In order to avoid that, Guard1 should return a boolean instead of Observable of boolean.


text:
Q: How to send JSON data from C++ DLL to Delphi I want to send a dynamic size JSON data from the C++ DLL function to Delphi.
So wrote the following C++ DLL function
extern "C" __declspec(dllexport) char* getJSON();
char* getJSON()
{
    char jsonArrray[] = "{\"id\":\"1\",\"language\":\"español\"}";
    return jsonArrray;
}

Here is the Delphi code:
function  getJSON: PChar; cdecl;  external "testCPP.dll";

var
    pVal:  Pchar;
    A: array[0..100] of wideChar;
begin
    pVal := A;
    pVal := getJSON;
    Writeln(pVal);
end


text:
Q: Strange enough! http://laravel6.com is pointing to local host 127.0.0.1 - Every system in my office
Nothing related to this found anywhere on web.

This is the only place I found something about this.
https://www.robtex.com/dns-lookup/laravel6.com
Is it something to worry about?

A: Yes! Offcource no need to worrry!
we can change apache default IP address http://127.0.0.1/ to any example.com like this
this domain definately not working globally on internet


text:
Q: Cannot convert lambda expression to type because it is not a delegate I'm trying to create an Index of List. But, for some reason  I keep getting the following error:

Cannot convert lambda expression to type 'TEntity' because it is not a
  delegate

I have tried searching quite a bit on the issue, but everything I've tried doesn't seem to work. I've tried everything from creating a cast to assuring I have the correct Using statements
This is the line that is specifically throwing the error
int index = items.IndexOf(x => ID(x) == id.Value);

Which is calling this method
protected Int32? ID(TEntity entity)
{
    return entity.As<dynamic>().__id;
}

For reference, the rest of what's applicable is here.
[Element("<div/>"), Editor, IdProperty("__id")]
public abstract class GridEditorBase<TEntity> : EntityGrid<TEntity>, ISetEditValue, IGetEditValue
    where TEntity : class, new()
{
    private int nextId = 1;

    public GridEditorBase(jQueryObject container)
        : base(container)
    {
    }

    protected Int32? ID(TEntity entity)
    {
        return entity.As<dynamic>().__id;
    }

    protected virtual void Save(ServiceCallOptions opt, Action<ServiceResponse> callback)
    {
        SaveRequest<TEntity> request = opt.Request.As<SaveRequest<TEntity>>();
        TEntity row = Q.DeepClone(request.Entity);
        int? id = row.As<dynamic>().__id;
        if (id == null)
            row.As<dynamic>().__id = nextId++;

        if (!ValidateEntity(row, id))
            return;

        List<TEntity> items = view.GetItems().Clone();

        if (id == null)
            items.Add(row);
        else
        {
            int index = items.IndexOf(x => ID(x) == id.Value);
            items[index] = Q.DeepExtend<TEntity>(new TEntity(), items[index], row);
        }

        SetEntities(items);
        callback(new ServiceResponse());
    }

A: You need to pass an item to IndexOf, which you could do like this:
int index = items.IndexOf(items.FirstOrDefault(x => ID(x) == id.Value));

A: Maybe you are missing one these references, Try adding them
using System.Linq;
using System.Data.Entity;


text:
Q: HDD + SSD = hybrid storage. Pro and contra?
Possible Duplicate:
Making SSD & HDD work together like a hybrid?

Solutions like RocketHybrid 1220 or SilverStone HDDBOOST. They allow to combine HDD and SSD, so SSD stores only frequently used data and HDD is for the rest. The idea is to get better drive performance for less money. Do you think this idea has any perspectives? If not - why?

A: Well, I'd recommend looking at some benchmarks, such as this, for example:
http://www.tomshardware.com/reviews/rockethybrid-1220-ssd-caching,2936-6.html
Of course, real world usage is the ultimate test, as the SSD caching might not always come into play in synthetic tests (or might come into play more than usual) and the caching performance increase might change as the drive fills up with data.
I have a Seagate Momentus XT (500GB 7200rpm hybrid drive with 4GB of SLC flash). Its a native hybrid drive. Its a bit different from these options where you pick the SSD and HDD yourself (since obviously nobody is going to buy this and use only a 4GB SSD), but it works on similar principles.
Pros

*

*You get the benefit of SSD's low seek times for most data, and the high capacity of a conventional drive

*MUCH Simpler and easier than using the drives seperately and deciding what to put on them

*(hopefully) less wear and tear on the SSD, so it gains a longer working life - Although this depends on how the caching works

Cons

*

*Not everything will gain a performance boost, and you won't get full SSD speed all of the time

*Synthetic Benchmarks don't necessarily show the true performance benefit, it can be much more (or less) in real world usage

*The caching algorithm won't cache data until after you've needed it a few times, so it won't be fast from day 1, it'll get faster over time

*The controller is more complex, so it might add to latency if the controller isn't very good

*Depending on the interface they use, it might not be possible to use these as a boot drive, so make sure to double check if you want to use it as a boot drive

I see the hybrid model as the easy "fire and forget" option, when compared to having the two drives seperate and deciding what to put on each drive. The thing to remember about hybrids is that they usually feel more like a fast hard drive, not a true SSD.
Consider that you might gain more benefit by installing your OS and performance-critical apps onto an SSD, and then putting less important data on a regular HDD. And don't expect true SSD speed - My hybrid drive does make my laptop a lot more responsive, especially during bootup, but its still way behind an SSD. Of course, what you're looking at may be different, it depends on the ratio of SSD capacity to HDD capacity. I have 4GB to 500GB, with a product like this you'd probably be putting in an SSD that is much larger than that.


text:
Q: Is it always possible to arrange $n$ nodes in dimenson $n-1$ with equidistance between each other? I want to construct a graph with $n$ nodes and with equal distance between each node. I was wondering if this is always possible in dimension $n-1$.
Take for instance a graph with three nodes. We can arrange them in the $\mathbb R^2$ as an equilateral triangle. Four nodes can be arranged as a tetrahedron in the $\mathbb R^3$ and so forth.

*

*Is this relationship always true?


text:
Q: Html.EnumDropDownListFor not showing property value as selected In using the new Html.EnumDropDownListFor extension method in MVC 5.1, I'm running into a problem where the selected value isn't updating in the drop down based on the route attribute I'm passing to my controller action.
View
@model MemberReconWebDemo.Models.EnvironmentsModel
@{
    ViewBag.Title = "Environments";
}

Environments

        @Html.EnumDropDownListFor(p => p.Environment)
        @Model.Environment.ToString()

Controller Action
[Route("environments/{environment?}")]
public ActionResult Environments(string environment)
{
    Domain.Environment env;
    Enum.TryParse(environment, true, out env);

    return View(new EnvironmentsModel{Environment = env});
}

If I navigate to the route without the optional attribute and I have the Model.Environment property set to a static value in the controller action, that selected value shows without issue.
If I pass in a valid route attribute value, assign that to the Model.Environment property, the drop down isn't updated to the property value upon rendering--even though I've confirmed that the property does have a value other than the default enum value.

A: I too encountered this problem today. Renaming the routes parameter to a name different from the models property worked for me.
Controller Action
[Route("environments/{envparm?}")]
public ActionResult Environments(string envparam)
{
    Domain.Environment env;
    Enum.TryParse(envparam, true, out env);

    return View(new EnvironmentsModel{Environment = env});
}

A: You Should have to try this:
use Html.DropdownlistFor
     @Html.DropDownListFor(m => m.Environment, Enum.GetValues(typeof(YourEnumType)).Cast<YourEnumType>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))

A: I have experienced similar error. In my case I need to pass enum value through action link as below (not working):
enum GroupByDate {
    Day, Month
}
class IndexViewModel {
    GroupByDate GroupByDate;
}

...

Because controller bind enum to int you need to pass it as integer, so I changed view to next (working):
 ...

Notice, that route values not anymore a typed ViewModel, but an anonymous type.


text:
Q: Como automatizar testes? É comum a cada vez que ocorre o deploy um bug ir junto, muitas vezes percebido somente meses depois daquela alteração. Para solucionar isso,  quero saber se é possível testar TODAS as funcionalidades principais de forma automatizada? Digo, antes de ir para a produção o teste de integração executará e se falhar não irá subir.  Além disso,  há outra opção a não ser criar vários testes JUnit?

A: Um software muito utilizado é o Jenkis que através dele, é possível agilizar tarefas demoradas como a compilação de um projeto e a execução dos seus testes automatizados. Com um servidor de integração contínua bem configurado, essas tarefas são executadas a cada mudança no repositório de código e, em caso de erros de compilação ou falhas nos testes automatizados, todos os desenvolvedores são alertados rapidamente. Dessa forma, se o servidor de integração não aponta problemas no projeto, a equipe tem a segurança de que as mudanças no código estão de acordo com a bateria de testes. É também um passo na direção do deploy contínuo.
Muitas pessoas que são adeptas ao Open Source, já que esse tem suporte e é provido pela comunidade diretamente. Se integra com repositórios Git, SVN, CVS, e builds com Maven, Ant, Gradle etc. Roda num Servlet Container, o que facilita no caso de você já ter um servidor de aplicação rodando num servidor de testes, por exemplo. Mas se você não tiver, tudo bem: ele tem uma versão "executável", que não é standalone, mas que faz o serviço de auto-deploy dele mesmo pra você. Configurado o repositório do controle de versão para o seu projeto, está feito: é só executar os builds pelo dashboard, que te dá as informações resumidas do build e acesso ao console. Executa os testes unitários como no seu caso JUnit, inclusive integrados ao Selenium e outras ferramentas de testes de aceitação. Deu erro? Envia e-mail e até SMS.


text:
Q: Managing database connections in Node.js, best practices? I'm building an Node application which will query simple and more complex (multiple joins) queries. I'm looking for suggestions on how I should manage the mySQL connections.
I have the following elements:

*

*server.js : Express

*router1.js (fictive name) : Express Router middleware

*router2.js (fictive name) : Express Router middleware

    //this is router1

    router.get('/', function (req, res){

    connection.connect(function(Err){...});

      connection.query('SELECT* FROM table WHERE id = "blah"', function(err,results,fields){
        console.log(results);
      });
      ...
    connection.end();
    })

Should I connect to mysql everytime '/router1/' is requested, like in this example, or it's better to leave one connection open one at start up? As: connection.connect(); outside of:  router.get('/',function(req,res){
...
}); ?

A: I am using mysql2 for this, it is basicly mysql but with promises. If you use mysql you can also do this.
Create a seperate file called connection.js or something.
const mysql = require('mysql2');

const connection = mysql.createPool({
    host: "localhost",
    user: "",
    password: "",
    database: ""
    // here you can set connection limits and so on
});

module.exports = connection;

Then it is probaly better you create some models and call these from within your controllers, within your router.get('/', (req, res) => {here});
A model would look like this:
const connection = require('../util/connection');

async function getAll() {
    const sql = "SELECT * FROM tableName";
    const [rows] = await connection.promise().query(sql);
    return rows;
}
exports.getAll = getAll;

You can do this with or without promises, it doesn't matter.
Your connection to the pool is automatically released when the query is finished.
Then you should call getAll from your router or app.
I hope this helped, sorry if not.

A: Connection pooling is how it should be done. Opening a new connection for every request slows down the application and it can sooner or later become a bottleneck, as node does not automatically closes the connections unlike PHP. Thus connection pool ensures that a fixed number of connections are always available and it handles the closing of unnecessary connections as and when required.
This is how I start my express app using Sequelize. For Mongoose, it is more or less simlar except the library API.
const sequelize = new Sequelize('database', 'username', 'password', {
    host: 'localhost',
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
});

sequelize.authenticate()
    .then(
        // On successfull connection, open a port
        // and listen to requests. This is where the application
        // starts listening to requests.
        () => {
            const server = http.createServer(app);
            server.listen(port);
        },
    )
    .catch(err => {
        console.error('Unable to connect to the database:', err);
        console.error('Cancelling app server launch');
    });

The app is started only after a database connection has been established. This ensures that the server won't be active without any database connection. Connection pool will keep the connections open by default, and use a connection out of the pool for all queries.

A: If you use createPool mysql will manage opening and closing connections and you will have better performance. It doesn't matter if you use mysql or mysql2 or sequlize. use a separate file for createPool and export it. You can use it everywhere. Don't use classes and just do it functionally for better performance in nodejs.

A: > npm install mysql

mysql is a great module which makes working with MySQL very easy and it provides all the capabilities you might need.
Once you have mysql installed, all you have to do to connect to your database is
var mysql = require('mysql')

var conn = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database'
})

conn.connect(function(err) {
  if (err) throw err
  console.log('connected')
})

Now you are ready to begin writing and reading from your database.


text:
Q: Can I combine meta name "description" and property "og:description" in same tag? Can I combine name="description" and property="og:description" in same meta tag?

A: You should not combine these two properties because the nature of these two things is different.
name="description" is the description that search engines use and property="og:description" is the property that is used by your social media sites to show specific descriptions to your viewers on social platforms. But if it's not present some times it picks either some paragraph from your content or the name="description".

A: TL;DR No.
In your code, sure, you can do anything. ;)
But it doesn't grant that it will be working and interpreted well by other systems.
As mentioned in the HTML standard:

description - The value must be a free-form string that describes the page. The value must be appropriate for use in a directory of pages, e.g. in a search engine. There must not be more than one meta element where the name attribute value is an ASCII case-insensitive match for description per document.

As mentioned in One Graph description:

While many different technologies and schemas exist and could be combined together, there isn't a single technology which provides enough information to richly represent any web page within the social graph. The Open Graph protocol builds on these existing technologies and gives developers one thing to implement.

optional metadata, og:description - A one to two sentence description of your object

Historically, HTML standards were much earlier and widely used - for search engines (SE - Google, Bing, Yahoo!, ...), than OG protocol (preview cards for URL sharing - chats, messengers, Facebook, ...).
SEs take a look at "description" but I'm not sure about "og:description". From the opposite side, a chatbot crawler for sure checks "og:description" and I'm not sure about "description". Both of these elements could contain the same text. Or different.
Usually, "description" is a rare updateable, its content is mostly "for machines". "og:description" could be changed more often to reflect a page's current state, this one is mostly "for humans". For example, a product page can have its general "description" for SEs and their results, current marketing text is better to be placed in "og:description".
Yes, they have close semantic values but technically they are from different mechanisms and for different purposes.
Use them to achieve your goals.


text:
Q: How to mark a task to not execute in a Flow? I have a flow in SAS Enterprise Guide but for debug reasons I want some tasks to run and others don't.
Is there a way to tell the flow to not execute some tasks? F.E. an export task.

A: http://support.sas.com/documentation/onlinedoc/guide/sasegforprogrammersGoodies.htm
Most of the way down, under How do you make sure a task (or program) has completed successfully before performing the next one?:

In SAS Enterprise Guide 4.2 and later, you can add one or more
  conditions to a task that control whether the task (and any items that
  follow it) will run.  A condition can be based upon a prompt value,
  date/time conditions, a value in SAS data set, or macro variable.
  It's these last two type that can be very powerful, since you can add
  almost any value that you want to a SAS data set or macro variable and
  check for it within a condition.
      To ensure that a particular task has what it needs before continuing, use a Query Builder or SAS program step in the project to
  populate a value into a SAS data set. Then create a condition
  (right-click on the task and select Condition->Add), and create a
  condition based upon the expected value within the data set you
  created.

In your case, you should have a macro variable or a value in a sas dataset defined for debug, like %let debug=0; or %let debug=1; and then use that value for your condition.

A: If this is not something you plan to repeat frequently, a quick solution would be to select the processes you'd like to execute (Ctrl+click) and  choose "Run Selected" as your run option.


text:
Q: How to get a scanner to loop until it reads a desired string?         Scanner one = new Scanner(System.in);
        System.out.print("Enter Name: ");
        name = one.nextLine();
        System.out.print("Enter Date of Birth: ");
        dateofbirth = one.nextLine();
        System.out.print("Enter Address: ");
        address = one.nextLine();
        System.out.print("Enter Gender: ");
        gender = //not sure what to do now

Hi I've tried to figure this out myself but I can't quite get it from looking at other examples, most are either only accepting certain characters or A-Z+a-z
I'm trying to make the program only accept input of male or female ignoring the case and if the input is wrong to repeat the "Enter Gender:" until a correct value is entered.

A: You can put the piece of code in a while and validate each time. for instance:
String gender;
do
{
  System.out.print("Enter Gender ('male' or 'female'): ");
  gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))

A: do {
    System.out.print("Enter Gender (M/F): ");
    gender = one.nextLine();
} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));

You can add an if check after gender assignment to display a invalid message

A: One way to do this is to use infinite loop and a label to break out.
Like this:
//Start
Scanner one = new Scanner(System.in);
here:
while (true){
System.out.print("Enter Gender: ");
    String str = one.nextLine();
        switch (str.toUpperCase()){
            case "MALE":
                System.out.println("Cool");
                break here;
            case "FEMALE":
                System.out.println("Nice");
                break here;
            default:
                System.out.println("Genders variants: Male/Female");
      }
}

A: public class Main {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter Name: ");
    String name = readValue(scanner, null);
    System.out.print("Enter Date of Birth: ");
    String dateofbirth = readValue(scanner, null);
    System.out.print("Enter Address: ");
    String address = readValue(scanner, null);
    System.out.print("Enter Gender: ");
    String gender = readValue(scanner, createGenderMatcher());
}

private static IMatcher createGenderMatcher() {
    return new IMatcher() {
        @Override
        public boolean isMatch(String value) {
            return "male".equalsIgnoreCase(value) || "female".equalsIgnoreCase(value);
        }
    };
}

private static String readValue(Scanner scanner, IMatcher matcher) {
    String value = null;
    do {
        value = scanner.nextLine();
    } while (matcher != null && !matcher.isMatch(value));
    return value;
}

private interface IMatcher {
    public boolean isMatch(String value);
}