text:
Q: embed lua runtime error: Symbol not found: _luaL_newstate my code
inline int DOFILE(string& filename) {

  printf("lua_open\n");
  /* initialize Lua */
  lua_State* L = lua_open();

  printf("lua_openlibs\n");
  /* load Lua base libraries */
  luaL_openlibs(L);

  printf("lua_dofile\n");
  /* run the script */
  int ret = luaL_dofile(L, filename.c_str());

  printf("lua_close\n");
  /* cleanup Lua */
  lua_close(L);

  return ret;
}

compile options:
obj.cxxflags = ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE", "-Wall", "-llua-5.1"]

also tried '-llua', '-llualib', all of them report warning
i686-apple-darwin11-llvm-g++-4.2: -llua-5.1: linker input file unused because linking not done

When I run, it report:
lua_open
dyld: lazy symbol binding failed: Symbol not found: _luaL_newstate
  Referenced from: /Users/gl/workspace/node-lua/build/Release/node_lua.node
  Expected in: flat namespace

dyld: Symbol not found: _luaL_newstate
  Referenced from: /Users/gl/workspace/node-lua/build/Release/node_lua.node
  Expected in: flat namespace

A: You should be using the obj.ldflags parameter for libraries.
The build tool you are using produces its binaries in two steps:

*

*compile

*link

The compile step uses the obj.cxxflags compiler flags. Libraries are not needed to compile, so passing linker flags (-lfoo) in there is no useful - the compiler doesn't use them at all (hence the warnings).
The link step should use both obj.cxxflags and obj.ldflags. (ld is the name of the linker.)
(It is not uncommon for very simple code to do both compiling and linking at the same time, e.g. with g++ -o thing thing.cpp -lpthread. But for larger builds, separating compiling and linking is usual.)


text:
Q: jquery and javascript not work on prettyphoto loaded html form prettyphoto shows my form in a modal box. I inserted a link in form and set onclick="$('#formid').submit()". when i clicked it, page navigate to form action but without any posted data. when i replace link with a input <input type="submit" value="ok"> it send form data correctly.
I test jquery element access with calling a function. result, showed that jquery cant access elements value.
I put some html in form by jquery but noting happend also after reloading modal box it shown.
is there any solution to access prettyphoto loaded html form by  jquery and javascript?

A: submit() in jquery works on <form> element, so that best way to do it to put a submit button in the form but do it such a way that it is hidden from view like:
<input id='dummy' type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/>

And in your jquery when the anchor link is clicked you simulate a submitting of the submit button by clicking it like this one below:
$('a').click(function(){
  $('#dummy').trigger('click');
  });

Here is my fiddle for you to check. Be aware though that I used a real website to simulate it but it will not receive the posted data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: drag and drop div element work well on element one, but element 2 not well I've created a simple code to drag and drop two div elements but work well on div 1 but div 2 not work well.
The mouse cursor not Standing on div 2 correctly.
Please check the online demo link in the bottom of the question.
HTML

CSS
div.draggable {
  background-color:yellowgreen;
  width:150px;
  height:100px;
  border:1px solid #ffff66;
  position:relative;
}

JavaScript
var element = null;
var elemPosL = 0;
var elemPosT = 0;
var isMouseDown = false;

document.onmousedown = function(e) {
    element = e.target;
    if (element.className === "draggable") {
        elemPosL = e.clientX - element.offsetLeft;
        elemPosT = e.clientY - element.offsetTop;
        isMouseDown = true;
    }
};

document.onmousemove = function(e) {
    if (isMouseDown) {
        element.style.left = e.clientX - elemPosL + "px";
        element.style.top = e.clientY - elemPosT + "px";
    }
};

document.onmouseup = function() {
    isMouseDown = false;
    element = null;
};

You can see online

A: Using position: absolute; fixes it.
If you want relative, check Implementing drag and drop on relatively positioned elements in JavaScript


text:
Q: T-SQL How to create function that compares string, checks difference, and do special function First - sorry for my english. Second - i'm learning t-SQL.

Goal:
I want to get difference between two strings, then check in which column is this difference. If the difference is in first column, do something, if in second column - do something else.

What I'm actually doing
Column 'messages' is a string which contains list of ID. So i am replacing all '#' with ',' and deleting last ',' what gives to me ActualID and BeforeID column. See below:
DECLARE @string VARCHAR(512);
DECLARE @string2 VARCHAR(512);
DECLARE @string3 VARCHAR(512);

SET @string = '41#42#43#44#45#46#47#48#49#50#51#52#53#54#55#56#57#58#59#';
SET @string2 = REPLACE((SELECT messages FROM USERS WHERE userid = 4), '#', ', ' )
SET @string3 = left(@string2, len(@string2) - 1);
SET @string2 = REPLACE(@string, '#', ', ' )
SET @string = left(@string2, len(@string2) - 1);
SELECT @string3 as ActualID, @string as BeforeID

So now, I want compare BeforeID with ActualID. For example:
In BeforeID we have 1, 2, 3 / In ActualID 1, 2, 3, 4
In example above 4 was added. So, if it was added I want to add it to @AddedElements.
If 4, 5, 7 were added then SELECT @AddedElements as AddedElements should return 4, 5, 7 (With comas)
But, that's not all.
If BeforeID = 1, 5, 10, 14 and ActualID = 1, 5, 14 I want, that element which is in BeforeID, but not in AcutalID will be added to @DeletedElements.
So SELECT @DeletedElements as DeletedElements should return 10
Added elements/Deleted elements should be returned once. I mean, full result what I want to Earn should be
SELECT @AddedElements as AddedElements, @DeletedElements as DeletedElements

Is it possible? If, then how to do it?

A: First of all, I have to start by saying that this is just poor design; but having said that, I've also found myself in all kinds of situations where I couldn't change the way things worked, only try to make them work better in the current configuration.  Therefore, I recommend something like this:
1: Create a UDF (User-Defined Function) that can handle splitting the strings and returning them in table-formed data that you can work with:
CREATE FUNCTION [dbo].[UDF_StringDelimiter]
/*********************************************************
**  Takes Parameter "LIST" and transforms it for use    **
**  to select individual values or ranges of values.    **
**                                                      **
**  EX: 'This,is,a,test' = 'This' 'Is' 'A' 'Test'       **
*********************************************************/
    (
          @LIST             VARCHAR(8000)
         ,@DELIMITER        VARCHAR(255)
    )

RETURNS @TABLE TABLE
    (
         [RowID] INT IDENTITY
        ,[Value] VARCHAR(255)
    )
WITH SCHEMABINDING
AS
BEGIN
    DECLARE
         @LISTLENGTH AS SMALLINT
        ,@LISTCURSOR AS SMALLINT
        ,@VALUE AS VARCHAR(255)
    ;
    SELECT
         @LISTLENGTH = LEN(@LIST) - LEN(REPLACE(@LIST,@DELIMITER,'')) + 1
        ,@LISTCURSOR = 1
        ,@VALUE = ''
    ;
    WHILE @LISTCURSOR <= @LISTLENGTH
    BEGIN

        INSERT INTO @TABLE (Value)
        SELECT
            CASE
                WHEN @LISTCURSOR < @LISTLENGTH
                    THEN SUBSTRING(@LIST,1,PATINDEX('%' + @DELIMITER + '%',@LIST) - 1)
                ELSE SUBSTRING(@LIST,1,LEN(@LIST))
            END
        ;
        SET @LIST = STUFF(@LIST,1,PATINDEX('%' + @DELIMITER + '%',@LIST),'')
        ;
        SET @LISTCURSOR = @LISTCURSOR + 1
        ;
    END
    ;
    RETURN
    ;
END
;

2: Consider dropping the whole "Switching out commas" thing, because it's pointless - the function I've written here takes two arguments: The string itself, and the delimiter (the mini-string that separates the individual strings within the big string, in your case '#') Then you just have to do a couple of quick comparisons to find out what was added and what was deleted.
DECLARE
     @AddedElements VARCHAR(255) = ''
    ,@DeletedElements VARCHAR(255) = ''
    ,@ActualID VARCHAR(255) = '41#42#43#44#45#46#47#48#49#50#51#52#53#54#55#56#57#58#59#'
    ,@BeforeID VARCHAR(255) = '41#42#43#44#45#46#47#48#50#51#52#53#54#55#56#57#58#59#60#'
;

SET @AddedElements = @AddedElements +
    SUBSTRING(
        (
        SELECT ', ' + Value
        FROM dbo.UDF_StringDelimiter(@ActualID,'#')
        WHERE Value NOT IN
            (
            SELECT Value
            FROM dbo.UDF_StringDelimiter(@BeforeID,'#')
            )
        GROUP BY ', ' + Value
        FOR XML PATH('')
        )
    ,3,255)
;

SET @DeletedElements = @DeletedElements +
    SUBSTRING(
        (
        SELECT ', ' + Value
        FROM dbo.UDF_StringDelimiter(@BeforeID,'#')
        WHERE Value NOT IN
            (
            SELECT Value
            FROM dbo.UDF_StringDelimiter(@ActualID,'#')
            )
        GROUP BY ', ' + Value
        FOR XML PATH('')
        )
    ,3,255)
;

SELECT @AddedElements AS AddedElements,@DeletedElements AS DeletedElements
;

Using this method, if you add a value to @ActualID that does not exist in @BeforeID, it will show up in @AddedElements.
Likewise , if you remove an element from @ActualID that had previously existed in @BeforeID, it will show up in @DeletedElements.
All of this is, of course, assuming that the dynamic string (the one really being compared here) is the @ActualID.  I operated with the understanding that @BeforeID is actually a stored value in the DB, and @ActualID is a dynamic string being passed in from...somewhere.  If this is wrong, update me and I'll change the tactic appropriately.
Quick note: It's important to me to point out that this is just one way of dealing with a situation like this, and I'm sure there are better ways; but with the information I have, it's the best I could come up with without spending too much time and energy on it.


text:
Q: Persisting jQuery Cookies Across Pages I'm using the jQuery Cookie plugin (https://github.com/carhartl/jquery-cookie) and I'm having issues persisting my cookies across different pages on my website.
I have a piece of content that displays on each page and once hidden it sets the cookie like so (Apologies for all of the variables, they are not at all relevent :
// Binds the close event to the button.
$alert.on('click', function(e) {
    $alertWrap.fadeOut();

    // Sets the breaking-delete cookie to yes.
    $.cookie('breaking-bar-delete', 'yes', {expires: 7 });
});

When the initial script fires it checks to see if the cookie exists:
// If the current bar is not supressed and they are not in the editor, and they do not have a closed cookie it will setup the bar.
if ($.cookie('breaking-bar-delete') == undefined) {
  $alert.css("display","block");
}

// If there's no news, or they have the closed cookie for the current bar it hides it by default.
if ($.cookie('breaking-bar-delete') == 'yes') {
  $alert.parent().css("display","none");
}

Now this works for the path that you hide the bar on so it doesn't re-display if you refresh. But if you go to a part of the site with a different path it doesn't detect the cookie and displays the content.
Is there some sort of configuration I can set when I initially serve the cookie so it persists throughout all of the pages on my site?

A: Path:-

path
path: '/' Define the path where the cookie is valid.
By default the path of the cookie is the path of the page where the cookie was
created (standard browser behavior).
If you want to make it available
for instance across the entire domain use path: '/'.
Default: path of page where the cookie was created.

So, for your cookie:-
$.cookie('breaking-bar-delete', 'yes', { expires: 7, path: '/' });


text:
Q: Can we see an aggregate count of our upvotes/downvotes separately, for the Questions and Answers? Can we see the total number of upvotes/downvotes we have casted, separately for the questions and answers?
Something like:

Hey, user! you have:

*

*upvoted 423 Questions;

*upvoted 3432 Answers;

*downvoted 43 Questions;

*downvoted 53 Answers.

For example, in the Votes tab, which is privately available for every user, users can see:

*

*how many votes they have casted in total (in the All sub-tab).

*how many posts they have upvoted in total (in the Upvote sub-tab);

*how many posts they have downvoted in total (in the Downvote sub-tab);

But what if I want to know How many Questions I have upvoted, or how many answers I have downvoted, in total?


text:
Q: way to do Load testing on emulator for mobile app (without connecting to real device) Is there any way to run Load Testing for mobile application on Emulator without connecting to real device.
All i see over google is jmeter with mobile app on real device. but because i am connecting to remote desktop where my jmeter is installed this is not possible,

A: There is no difference whether you use a real device or an emulator for recording the mobile application traffic, you can specify the proxy for the emulator at the Extended Controls screen:

In case of recording HTTPS traffic you will need to install JMeter's self-signed certificate onto the emulator and allow trust for user added CAs in the network_security_config.xml


text:
Q: Auto reload a webpage when chrome extension is added I want to auto - reload a tab with URL, say 'www.example.com' as soon as I add a chrome extension in my browser.
I don't want to reload current tab but another tab with the URL 'www.example.com'.
How can I achieve this?


text:
Q: Add new menu items to Grub boot menu I need to remove one existing boot menu item and add two new ones related to my second disc partitions in my Grub menu. What is the best way of doing that?

A: Grub menu entries are auto-generated by sudo update-grub. Have you tried to run it ? Doesn't it suite your needs ?
Otherwise, you can use /etc/grub.d/40_custom to add your custom entries. And then run sudo update-grub to update /boot/grub/grub.cfg.
You can however edit manually /boot/grub/grub.cfg to delete an entry. But your change will be lost the next time update-grub will be run by you or automatically by ubuntu when there is a kernel upgrade.

A: GRUB should autodetect every OS installed on a partition. You have to update the menu by using the following command:
sudo update-grub


text:
Q: Event triggered VBA Macro runs, but doesn't execute I have a pivot table with caculated item. Each time, when I change the parameter in the pivot main filter, text formatting goes back do default.
In order not ot format the table each time, I created a macro, that should format the pivot table whenever I put a value in cell D1. C2 is the format sample cell. It appears that macro runs, but doesn't execute.
Could You help?
The code:
Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$d$1" Then

Application.EnableEvents = False

    Range("C2").Activate
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=ORAZ(JEŻELI($B2=" 'OFERTA/TOTAL RYNEK'";1;0);JEŻELI(C2>1;1;0))"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Font
        .Color = -16776961
        .TintAndShade = 0
    End With

    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = 0.399945066682943
    End With

    Selection.FormatConditions(1).StopIfTrue = False
    Range("C2").Select
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=ORAZ(JEŻELI($B1=""OFERTA/TOTAL RYNEK"";1;0);JEŻELI(C1>1;1;0))"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

    With Selection.FormatConditions(1).Font
        .Color = -16776961
        .TintAndShade = 0
    End With

    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = 0.399945066682943
    End With

    Selection.FormatConditions(1).StopIfTrue = False
    Selection.Copy
    Columns("C:N").Select
    Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False

Application.EnableEvents = True

End If

End Sub

A: Comparing two strings, such as Target.Address and "$d$1" using the following:
If Target.Address = "$d$1" Then

.. can never equate to TRUE, as if Target.Address did refer to column 4, row 1, it would hold the string "$D$1". Using = to compare essentially uses Binary Compare.
You either need to correct it to "$D$1", or use a Text Compare method with the StrComp function.
Stepping through the event, and hovering over the Target.Address would have highlighted this.

A: As mentioned by the other poster - the binary comparison will never evaluate you argument to True you could either save the address as a string and change the argument to If Target.Address = [Assigned String Name] Then but it's much better to just change the argument to the following:
If Not Intersect(Target, Range("$D$1")) Is Nothing And Target.Cells.Count = 1 Then

    'code here

End If

This mitigates the risk of code behaving not as you intended and also as it only passes the argument if only D1 changes and, as the comments below state, is the more appropriate code.


text:
Q: How to querySelector across all events in FullCalendar? I'm working on building a filterable calendar and to do that, I set a class name on my calendar's events in it's source array. See below:
source.push({
    id: 5695151911,
    title: "Customer Success",
    start: "2018-05-11 15:26:05",
    end: "2018-05-11 15:26:05",
    description: "",
    url: "",
    button_txt: "",
    address: "",
    addressUnformatted: "",
    location: "ttt",
    allDay: false,
    sameDay: same,
    eventType: "",
    // Handle classing for filters
   className: "filterable-item__groups active group1_-_English group2_-_filter1 group3_-_filter3 "
});

Pay attention to the className section. In there I am setting filter-item__groups which is what I want to query across to create my filters. As of right now, when I query, it will only pull the filters for group1, group2, and group3 for the current month selected. I believe the problem is because the other months aren't currently in the DOM on load.
This is how I'm querying events for the correct classes:
const modules = document.querySelectorAll('.filterable-content');
      modules.forEach(mod => {
         const items = mod.querySelectorAll('.filterable-item__groups');
         const dropdowns = mod.querySelectorAll('.filterable-content__filters ul');
         const labels = mod.querySelectorAll('.filterable-content__selected-filters');
      });

Key
.filterable-content - container for my calendar
.filterable-item__groups - class on my event
.filterable-content__filters ul - UL tag that holds the filters when dynamically created.
.filterable-content__selected-filters - Labels that are dynamically added to the UL tag
Is there a way to query all of my events, so I can generate the filters for all the classes that exist on the entire calendar, and not just the current month?


text:
Q: Download a file using php I want to download a file from the webiste "http://nccpl.com.pk/market-information/fipi-lipi/fipi-sector-wise" but there is the extract button to download the excel file. How can I download it automatically on daily basis using php.

A: The data export link is generating the CSV in JavaScript in the browser from the table. For this reason, you will not be able to download it using just PHP, since the file does not actually exist anywhere.
You might, however, be able to generate the file from the table in nothing but PHP by downloading the html of the page and parsing it. However, I do not know tools are available for that purpose in PHP.

A: readfile($file)

Is what you need my friend.
This is a snippet from php.net
<?php
$fichero = 'mono.gif';

if (file_exists($fichero)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($fichero).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($fichero));
    readfile($fichero);
    exit;
}
?>

A: believing that the file gets updated automatically you can just use
header('Location: /path-to-file/filename');

Example
<?php
  header('Location: '/docs/pdf/mypdf.pdf');
?>

just write this into a .php file and let the user to the .php file when he clicks the download buttton. Make sure the file has permissions to be downloaded.


text:
Q: Finding polygon within polygon using ArcGIS for Desktop? How do I find two parks (shapefile) that are within a census tract ?
If I'm not mistaken you have to use selection by location.. but beyond that quite sure what to do after.


text:
Q: How is it possible that selecting first after GroupBy on a DataTable does not return one value for every group? I am trying to get one row per id from a DataTable, and I do not care which row I take. The same id can exist on several rows in the table.
Here's the expression that's giving me trouble:
dt.AsEnumerable().GroupBy(i => i.Field<int>("id")).Select(i => i.First())

Running just this section dt.AsEnumerable().GroupBy(i => i.Field<int>("id") correctly gives me a result of 22 groupings for my DataTable. (I have 22 ids with data in this table)
However, when adding on the .Select(i => i.First()), I am only seeing 10 data rows.
To me this doesn't seem to make any sense. If the GroupBy function managed to find 22 distinct id values, I would expect this logic to grab one of each.
My only other thought is that maybe it's just a weird side effect of viewing this data through a watch in Visual Studio rather than assigning to a variable.

A: If you think it's just weird side effects of viewing the data in a watch, which can happen with LINQ statements, then split it out into
var groups = dt.AsEnumerable().GroupBy(i => i.Field<int>("id")).ToList();
var firstOfGroups = groups.Select(i => i.First()).ToList();

and then look at groups and firstOfGroups in the debugger. Temporarily evaluating items with .ToList() can help a lot with viewing things in the debugger.

A: I think it is possible, can double check the count of each group items
.Select(g=>new { k = g.Key, c = g.Count() })


text:
Q: Term.IsAvailableForTagging According to MSDN
Gets or sets the flag indicating whether a Term object can be used to tag in the tagging UI, but does not affect its visibility.
I am just confused and want to know what is tagging UI?
Can anybody explain little bit more the above definition?

A: By tagging UI MSDN documentation refers to TaxonomyWebTaggingControl ASP.NET web control that represents a generic Web control for picking managed metadata terms.
According to Using SharePoint TaxonomyWebTaggingControl control: Access and manipulate from client side, TaxonomyWebTaggingControl ASP.NET web control is a server side wrapper for Microsoft.SharePoint.Taxonomy.ScriptForWebTaggingUI JavaScript control from SharePoint client library (ScriptForWebTaggingUI.js).
The list of application pages that leverages Microsoft.SharePoint.Taxonomy.ScriptForWebTaggingUI contol:

*

*/_layouts/TaxonomyTreePicker.aspx

*/_layouts/TermStoreManager.aspx

*/_layouts/WebTaggingDialog.aspx


text:
Q: Schemacrawler container could not connect to host postgresql database I tried to run the following schemacrawler container on my Ubuntu 18.04 machine:
docker run \
--mount type=bind,source="$(pwd)",target=/home/schcrwlr \
--rm -it \
schemacrawler/schemacrawler:v16.19.7 \
/opt/schemacrawler/bin/schemacrawler.sh \
--server postgresql \
--host localhost \
--user postgres \
--password pass \
--database detections \
--info-level standard \
--command schema \
--output-file output.png

And got the following error:
Error: Could not connect to <jdbc:postgresql://localhost:5432/detections>, for <user 'postgres'>, with properties <{}>
java.lang.RuntimeException: Could not connect to <jdbc:postgresql://localhost:5432/detections>, for <user 'postgres'>, with properties <{}>
    at us.fatehi.utility.datasource.AbstractDatabaseConnectionSource.getConnection(AbstractDatabaseConnectionSource.java:131)
    at us.fatehi.utility.datasource.SimpleDatabaseConnectionSource.get(SimpleDatabaseConnectionSource.java:112)
    at us.fatehi.utility.datasource.SimpleDatabaseConnectionSource.get(SimpleDatabaseConnectionSource.java:49)
    at schemacrawler.tools.commandline.command.ConnectCommand.loadSchemaRetrievalOptionsBuilder(ConnectCommand.java:180)
    at schemacrawler.tools.commandline.command.ConnectCommand.run(ConnectCommand.java:124)
    at schemacrawler.tools.commandline.SchemaCrawlerCommandLine.executeCommandLine(SchemaCrawlerCommandLine.java:110)
    at schemacrawler.tools.commandline.SchemaCrawlerCommandLine.execute(SchemaCrawlerCommandLine.java:72)
    at schemacrawler.Main.main(Main.java:76)
Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:319)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:247)
    at org.postgresql.Driver.makeConnection(Driver.java:434)
    at org.postgresql.Driver.connect(Driver.java:291)
    at us.fatehi.utility.datasource.AbstractDatabaseConnectionSource.getConnection(AbstractDatabaseConnectionSource.java:122)
    ... 7 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.base/java.net.Socket.connect(Socket.java:609)
    at org.postgresql.core.PGStream.createSocket(PGStream.java:241)
    at org.postgresql.core.PGStream.<init>(PGStream.java:98)
    at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:109)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:235)*

I edited the file postgresql.conf to listen to all available IP addresses, listen_addresses = ''*, and edited pg_hba.conf file to allow TCP/IP connections to all databases for all users with any IPv4 address: host all all 0.0.0.0/0 md5 but the problem persisted...


text:
Q: Remove duplicate line with random starts php I have a file containing data something like this:
randomString-data1
randomString-data2
randomString-data4
randomString-data2
randomString-data2
randomString-data3
randomString-data4

The output I want:
randomString-data1
randomString-data2
randomString-data4
randomString-data3

The length of random string is between 20 to 25 characters. The randomString is not important. The data after it is of relevance only. What could be the best way to remove such duplicates?
All I can think of is the brute force way to explode each line at "-" and compare with all others. But is there a better way?
Note: The random strings are important. But it is okay if any one of the randomString remains from the duplicate entries.

A: firstly explode them by '\n' then by '-'
$arr = explode('\n', $str);

$data = array();
foreach($arr as $val)
{
   $temp = explode("-", $val);
   $data[$temp[1]] = $temp[0];
}

$str = "";
foreach($data as $k => $v)
{
  $str .= $v . "-" . $k;
}

A: Explode and array flip and then get array keys
$content_array = explode($file_contents);
//Remove duplicate entries
$flipped_array = array_flip($content_array);
file_put_contents('/path/to/file', implode("\n", array_keys($flipped_array));

A: i would do it this way
<?php
$file = <<<EOF
randomString-data1
randomString-data2
randomString-data4
randomString-data2
randomString-data2
randomString-data3
randomString-data4
EOF;

$found = [];
foreach (explode("\n", $file) as $line) {
    list(, $date) = explode('-', $line);
    if (!isset($found[$date])) {
        echo "$line<br>";
        $found[$date] = true;
    }
}
?>


text:
Q: make start date and end date in costum post type wordpress i try this code in costum post type wordpress but i found error.. how to fix it?
function uep_add_event_info_metabox() {
    add_meta_box(
        'uep-event-info-metabox',
        __( 'Event Info', 'uep' ),
        'uep_render_event_info_metabox',
        'event',
        'side',
        'core'
    );
}
add_action( 'add_meta_boxes', 'uep_add_event_info_metabox' );

    function uep_render_event_info_metabox( $post ) {

    // generate a nonce field
    wp_nonce_field( basename( __FILE__ ), 'uep-event-info-nonce' );

    // get previously saved meta values (if any)
    $event_start_date = get_post_meta( $post->ID, 'event-start-date', true );
    $event_end_date = get_post_meta( $post->ID, 'event-end-date', true );
    $event_venue = get_post_meta( $post->ID, 'event-venue', true );

    // if there is previously saved value then retrieve it, else set it to the current time
    $event_start_date = ! empty( $event_start_date ) ? $event_start_date : time();

    //we assume that if the end date is not present, event ends on the same day
    $event_end_date = ! empty( $event_end_date ) ? $event_end_date : $event_start_date;

    ?>

<?php _e( 'Event Start Date:', 'uep' ); ?>
        <input class="widefat uep-event-date-input" id="uep-event-start-date" type="text" name="uep-event-start-date" placeholder="Format: February 18, 2014" value="<?php echo date( 'F d, Y', $event_start_date ); ?>" />

<?php _e( 'Event End Date:', 'uep' ); ?>
        <input class="widefat uep-event-date-input" id="uep-event-end-date" type="text" name="uep-event-end-date" placeholder="Format: February 18, 2014" value="<?php echo date( 'F d, Y', $event_end_date ); ?>" />

<?php _e( 'Event Venue:', 'uep' ); ?>
        <input class="widefat" id="uep-event-venue" type="text" name="uep-event-venue" placeholder="eg. Times Square" value="<?php echo $event_venue; ?>" />

    <?php
}


text:
Q: Access individual elements of ChunkedArray by its index within column What is the best method to randomly access individual elements ("Scalars") of arrow::ChunkedArray e.g. for testing and display purposes? Is there some equivalent method to Array::GetScalar which takes into account that the ChunkedArray consists of multiple chunks?
The way I found so far is an own helper function which "searches" the appropriate chunk like this (not tested):
std::shared_ptr<arrow::Scalar>
get_scalar(const std::shared_ptr<arrow::ChunkedArray>& chunked_array, int64_t index) {
    auto it = chunked_array->chunks().begin();
    while (index >= (*it)->length()) {
        index -= (*it)->length();
        ++it;
    }
    auto result = (*it)->GetScalar(index);
    if (!result.ok()) {
        return nullptr;
    }
    return result.MoveValueUnsafe();
}

But I'm wondering if there is something like this already provided or there is a better practice to do so?
Similar applies to the arrow::stl::ArrayIterator - is there an equivalent iterator for Chunked::Array?


text:
Q: How to Send Confirmation Emails to Users after Form Submission? I would like to run a confirmation e-mail on Contact Form 7
What I want is: Once a form has been submitted, the visitor who sent the form must confirm it by going to the email address. A confirmation link is sent to the e-mail address. And after confirming, the message reaches. Also, after you submit the form, the user will be shown the information text on the form to check the email address.
How can I do this?

A: You need to take a look at the hooks of the Contact Form 7 plugin website.
Browse the documentation for the actions you need.
Have a look at this topic: how-to-hook-into-contact-form-7-before-send
All you need to do is to add your link with the hash into the e-mail.
In addition, also have a look at "wp_mail()".
That is the mechanism which triggers an e-mail.
So, catch the e-mail before it is being sent, add your link to it, then trigger the actual mail.
I know, this isn't a complete answer, but adding your own work to it should get you in the right direction.


text:
Q: Undefined function when testing public functions called in the constructor of an abstract class using mockery I have an abstract class which makes calls to public functions in its constructor. To test these calls are executed correctly, I have to mock the abstract class. Whenever I do this, I cannot make public function calls in the constructor. I get the the following error: BadMethodCallException: Method ::setData() does not exist on this mock object. The following code probably explains my issue better.
<?php

namespace Example\Tests;

use Mockery as m;
use PHPUnit_Framework_TestCase;

abstract class Foo
{

    private $data;

    public function __construct(array $defaults)
    {
        foreach ($defaults as $key => $value) {
            $this->setData($key, $value);
        }
    }

    public function getData()
    {
        return $this->data;
    }

    public function setData($key, $value)
    {
        return $this->data[$key] = $value;
    }
}

class ExampleTest extends PHPUnit_Framework_TestCase
{

    public function testDefaultsAreAssignedToData()
    {
        $expected = ['foo' => 'bar'];

        $foo = m::mock('\Example\Tests\Foo', [$expected]);

        $this->assertEquals($expected, $foo->getData());
    }
}

A: Usually you are using mocks as a replacement for external dependencies for your class under test. In this case you just want to test the real behaviour of the class, and you are not dealing with any dependencies for the class Foo. In this case there is really no need to mock, I would just define a concrete instance of the abstract class for testing purposes.
That said, you can refactor to something like this.
class ConcreteFoo extends Foo
{
}

class ExampleTest extends PHPUnit_Framework_TestCase
{
    public function testDefaultsAreAssignedToData()
    {
        $expected = ['foo' => 'bar'];

        $foo = new ConcreteFoo($expected);

        $this->assertEquals($expected, $foo->getData());
    }
}


text:
Q: Obtaining non-null output from all parts of a compound expression I've decided to post this question and self-answer, since this might be useful to others wishing to do the same thing.
I was wondering how to obtain non-null output from all parts of a compound expression.  By default, only the result of the last part of a compound expression is output, for instance:
fun1[expr_] := (expr + x; expr + y; expr + z)
fun1[a]

a+z

fun1p := (# + x; # + y; # + z) &
fun1p[a]

a+z

One could use Print (or Echo)...
fun2[expr_] := (Print[expr + x]; Print[expr + y]; Print[expr + z])
out2 = fun2[a]

a+x
a+y
a+z

...but the output has Null content:
out2

(no output)

One gets the same result using Print with a pure function.
There are workarounds, but I sometimes find it syntactically convenient to obtain the outputs directly.
Note: This is not a duplicate of Compound Statements and returning earlier results in () parentheses , since there the OP was looking to Print the results (which displays the results, but has Null content), while I (as explained above) want to actually get the results (such that I could assign them to variables).

A: I received this answer, courtesy of Wolfram Technical Support.  The desired result can be achieved using Sow and Reap:
 fun3[expr_] :=
 Reap[Sow[expr + x]; Sow[expr + y]; Sow[expr + z]][[2, 1]]
 out3 = fun3[a]

{a + x, a + y, a + z}

out3

{a + x, a + y, a + z}

fun3p := (Reap[Sow[# + x]; Sow[# + y]; Sow[# + z]])[[2, 1]] &
out3p = fun3p[a]

{a + x, a + y, a + z}

out3p

{a + x, a + y, a + z}


text:
Q: Support on Payroll Code Error? Im getting a few errors from this code, can anyone explain what seems to be the issue? Thanks!
This program is supposed to calculate the payroll for a declared (counter) amount of employees.
Note: This is Python 3.3
Also: please feel free to make any improvements you like! I am looking to learn!
def computeGrossPay(hours, rate):
    if hours > 40:
        grossPay = (40 * rate) + ((hours - 40) * 1.5 * hours)
    else:
        grossPay =  hours * rate
    return grossPay

def computeTaxAmount(status, grossPay):
    if status == 1:
            if grossPay <= 42:
                taxAmount = 0
            elif grossPay > 42 and grossPay <= 214:
                taxAmount = (grossPay - 15) * .1
            elif grossPay > 214 and grossPay <= 739:
                taxAmount = 17.2 + ((grossPay - 214) * .15)
            elif grossPay > 739 and grossPay <= 1732:
                taxAmount = 95.95 + ((grossPay - 739) * .28)
            elif grossPay > 1732 and grossPay <= 2566:
                taxAmount = 344.2 + ((grossPay - 1732) * .28)
            elif grossPay > 3566 and grossPay <= 7703:
                taxAmount = 857.72 + ((grossPay - 3566) * .33)
            elif grossPay > 7703 and grossPay <= 7735:
                taxAmount = 2222.93 + ((grossPay -7703) * .35)
            elif grossPay > 7735:
                taxAmount = 2234.13 + ((grossPay - 7735) * .396)
    elif status == 2:
            if grossPay <= 160:
                taxAmount = 0
            elif grossPay > 160 and grossPay <= 503:
                taxAmount = (grossPay - 160) * .1
            elif grossPay > 503 and grossPay <= 1554:
                taxAmount = 34.3 + ((grossPay - 503) * .15)
            elif grossPay > 1554 and grossPay <= 2975:
                taxAmount = 191.95 + ((grossPay - 1554) * .28)
            elif grossPay > 2975 and grossPay <= 4449:
                taxAmount = 547.2 + ((grossPay - 2975) * .28)
            elif grossPay > 4449 and grossPay <= 7820:
                taxAmount = 959.92 + ((grossPay - 4449) * .33)
            elif grossPay > 7820 and grossPay <= 8813:
                taxAmount = 2072.35 + ((grossPay -7820) * .35)
            elif grossPay > 8813:
                taxAmount = 2419.9 + ((grossPay - 8813) * .396)
    return taxAmount

def computeNetPay(grossPay, taxAmount):
    netPay = grossPay - taxAmount
    return netPay

def main():
    totalGrossPay = 0
    print("Welcome to the Payroll Program")
    counter = eval(input("How many employees will be entered? \n"))
    for i in range(counter):
        name = input("What are the first and last names of the employee? \n")
        id = input("What are the last four numbers of his/her Social Security Number? \n")
        hours = eval(input("How many hours did they work? \n"))
        rate = eval(input("What was the rate? \n"))
        while (True):
            status = eval(input("Are they single(1) or married(2)? \n"))
            if status != 1 or 2:
                break
        grossPay = computeGrossPay(hours, rate)
        taxAmount = computeTaxAmount(status, grossPay)
        netPay = computeNetPay(grossPay, taxAmount)
        totalGrossPay = totalGrossPay + grossPay
        averageGrossPay = totalGrossPay / counter

        print("The ID is ", id)
        print("The name is ", name, ".")
        print("This employee worked ", hours, " hours.")
        print("The hourly rate was ", rate)
        print("The gross pay was $", grossPay)
        print("The tax amount withheld for the week is $", taxAmount)
        print("The net pay is $", netPay)
    print("The total gross pay was $", totalGrossPay)
    print("The average gross pay was $", averageGrossPay)

main()

A: You "set" the status like this:

status = input("Are they single(1) or married(2)? \n")

The type() of status is going to be a string. When you attempt to compare it in your computeTaxAmount() method, you either need to turn it into an int or compare it to a string, otherwise it will never be True and taxAmount will never be set.
Ex:
if status == 1:
becomes:
if status == '1':
You have other issues in your code as well. In Python, '&' is the bitwise AND operator, not the logical AND. elif grossPay > 42 & grossPay <= 214 for example needs to become elif grossPay > 42 and grossPay <= 214.


text:
Q: Upload files to server using service in android I have a folder in which i store images....So what i want to do is upload this images to server and once the upload is complete i want to delete this images.. This uploading and deleting should happen in background...So i have created a service that works fine..What i want is whenever a new file comes in this folder it should automatically upload..i.e the service should automatically start itself...Is there any way to do this...??
public class MyServices extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "Service Started",
                Toast.LENGTH_LONG).show();

        sendfile();
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "Service Stopped",
                Toast.LENGTH_LONG).show();
        super.onDestroy();
    }
}

the sendfile() scans the folder and sends the images....So do i have to keep on calling this method infinitely or is there any other way???

A: You can use AlarmManager and sometimes run your service and check the folder. (But be aware of battery cunsuming app =) ).

A: Here are a few options:

*

*You could use a FileObserver to watch the directory for changes.

*If your app is creating the images, you could call startService each time a new image is added.

*You could listen for ACTION_NEW_PICTURE to know when new pictures are added (assuming the app adding the pictures behaves like the camera app).

A:
..So what i want to do is upload this images to server and once the upload is complete i want to delete this images.. This uploading and deleting should happen in background...

This Github library exactly does that -
https://github.com/gotev/android-upload-service  2.3K stars Apr 2020

"
-Easily upload files (Multipart/Binary/FTP out of the box) in the background with progress indication notification
-upload files to a server with FTP, HTTP multipart/form-data or binary requests
-handle multiple concurrent uploads in the background, even if the device is idle (Doze mode)
-automatically retry failed uploads, with a configurable exponential backoff
possibility to automatically delete uploaded files when the upload is successful
Apps and libraries powered by this library-
-JIRA Cloud
-Quora
...
"


text:
Q: Codeception run test from web interface I need to run codeception's test from web interface. Have no idea how to do it and cant search it in google. Or it work for console only?

A: Codeception is designed to be run from the command line, but if you want to initiate tests from within your web browser instead, you might be interested in Webception which is a web-based front end to Codeception.
See https://github.com/jayhealey/Webception

Webception is a deployable web-application that allows you to run all your Codeception tests in the browser.
You can access multiple test suites and decide which tests to include in a run. It allows you start, stop and restart the process whilst watching the test results in the Console.

A:
I need to run codeception's test from web interface.

I am assuming by web interface you mean, running acceptance tests on web browser like firefox, chrome etc.
If thats the case, then follow the steps from this page
http://codeception.com/docs/03-AcceptanceTests
Scroll down to the section: Selenium-WebDriver

*

*First create/generate a basic cept or cest test inside your acceptance directory
./vendor/bin/codecept generate:cept acceptance your-test-name

*Edit the acceptance.suite.yml:
modules:
    enabled:
        - WebDriver
    config:
        WebDriver:
            url: 'http://www.yoursite.com'
            browser: 'firefox'

*If you don't have the selenium server yet, get it from http://www.seleniumhq.org/download/. (Grab the Selenium Standalone Server - current version is 2.47.0). We need the selenium server running to communicate with the browser (web interface) using the webdriver. To start the server, run the following command in a terminal window ( * replace it with the version you downloaded )
 java -jar /path/to/selenium-server-standalone-*.jar

*Run the test on a separate terminal
./vendor/bin/codecept run acceptance --steps

This should start the test in firefox browser. If you don't have firefox browser, please download it. If you like to use chrome instead, make sure to first get the correct chromedriver for your os, and then pass the path to chromedriver when you start the selenium server
java -jar /path/to/selenium-server-standalone-*.jar -Dwebdriver.chrome.driver=/path/to/chromedriver


text:
Q: add "current" class to the current element of a navigation bar removing this class from the previous item I try to add a current class on the active item removing it from the previous item. It works but the pages don't change when I click.

$(document).ready(function() {
  $(function() {
    $('#navbarSupportedContent li a').click(function() {
      $('#navbarSupportedContent li').removeClass('current');
      $(this).closest('li').addClass('current');
      return false;
    });
  });
});
li.current a { color: red; }

Accueil

A propos

Nos services

Contact


text:
Q: Responsive web design - How to implement JavaScript part? I'm preparing to make the web page responsive from a old existing complex one. https://www.lendingclub.com/browse/browse.action
I use media query for the CSS part, making different CSS work for different width of the browser. I want to ask:

*

*How do you deal with the JavaScript part, if some functions only exist in the mobile version (and narrow width browser on PC)?

*What I am doing is by the current window width:

   window.onresize = function(){ if (document.body.clientWidth <= 720){……}}

Is it the best and primary way for the 'responsive js'?
We use YUI in old PC pages, do not include any mobile framework.
Thank you.

A: I use these values to implement responsive web design in Javascript:
screen.height;
screen.width;

Also, if some functions are not available in mobile, no script to be runned on mobile should call these functions.


text:
Q: exception: geoNear command failed: errmsg: more than one 2d index I'm trying to retrieve documents from a collection by distance. I've tried to use the $geoNear aggregation, but I either run into errors (using node.js and postman) or 0 records get returned.
Sample Document:
{
    "_id" : ObjectId("5cc37692fe9fd54b3cd136c9"),
    "category" : "art",
    "description" : "an eastbound description for The soda event.",
    "geometry" : {
        "type" : "Point",
        "coordinates" : [
            3.60178480057443,
            6.46123057784917
        ]
    }
    "__v" : 0
}
.
.

Model:
const GeoSchema = new Schema({
  type: {
    type: String,
    default: "Point"
  },
  coordinates: {
    type: [Number],
    index: "2dsphere"
  }
}, { _id: false });

const EventSchema = new Schema({
  category: String,
  description: String,
  geometry: GeoSchema,
});

Query
db.events.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [3.60178480057443, 6.46123057784917] },
        distanceField: "dist",
        maxDistance: 90000,
        spherical: true
     }
   }
]);

Running the query above returns zero results, an empty array (on postman) and sometimes displays this error:
{
    "name": "MongoError",
    "errmsg": "exception: geoNear command failed: { ok: 0.0, errmsg: \"more than one 2d index, not sure which to run geoNear on\" }",
    "code": 16604,
    "ok": 0
}

When this error is displayed, I run the db.events.dropIndex function. I copied and pasted the examples used in the docs, and it worked fine. Please How do I make this $geoNear function work. I have been struggling with it for a whole day.

A: A Single collection cannot have more then one 2dsphere index and You have created 2dsphere index on more than one field by running following command.
db.getCollection('test').createIndex({ "loc": "2dsphere" })

So remove the one of the index and it will get work. You can check the list of indices using this
db.getCollection('test').getIndexes()

Update:
You can use key parameter to specify on which field do you want to make search with if your collection have multiple $geoNear indices


text:
Q: Combining distinct combinatios of elements of an numpy array into a dataframe Maybe I could synthesize precisely my problem with my title, however I guess that by explaning it, things will get more clear.
So, what I want to do is the following: I want to create a dataframe which each row combinates each distinct element of 4 different numpy arrays.
I am trying to avoid for loops as much as possible and I am not sure if there are other means to achieve my goal utilizing pandas or python methods which I am not still aware of. The problem that I am trying to solve is naturally more complex and would involve several more arrays as well as more complex data.
I would really appreciate your help on this one!
min_x = 1

max_x = 5

x1_set = np.linspace(min_x, max_x, 5)

x2_set = np.linspace(min_x, max_x, 5)

x3_set = np.linspace(min_x, max_x, 5)

x4_set = np.linspace(min_x, max_x, 5)

X_set_df = pd.DataFrame([x1_set,x2_set,x3_set,x4_set]).T

I would expect a dataframe that would be somehow like this
First row : 1,1,1,1

Second row: 1,1,1,2

Third row: 1,1,1,3

...

n-row: 5,5,5,5

A: Use itertools.product for cartesian product, last pass it to DataFrame constructor:
from  itertools import product
df = pd.DataFrame(list(product(*[x1_set,x2_set,x3_set,x4_set])))
print (df)
       0    1    2    3
0    1.0  1.0  1.0  1.0
1    1.0  1.0  1.0  2.0
2    1.0  1.0  1.0  3.0
3    1.0  1.0  1.0  4.0
4    1.0  1.0  1.0  5.0
..   ...  ...  ...  ...
620  5.0  5.0  5.0  1.0
621  5.0  5.0  5.0  2.0
622  5.0  5.0  5.0  3.0
623  5.0  5.0  5.0  4.0
624  5.0  5.0  5.0  5.0

[625 rows x 4 columns]


text:
Q: Hammerspoon - how to paste text? I can't find it in the docs - how do i paste text with Hammerspoon on OS X?
I tried the following:
hs.hotkey.bind({"ctrl", "pad1"}, "1", function()
    hs.eventtap.keyStrokes("this needs to be pasted!")
end)

but it does not work.
I pressed "control" and Numpad's "1" on my keyboard.
Thanks for help!

A: I found out how it works, the keybinding was wrong.
hs.hotkey.bind(
    {"ctrl"}, "Pad1", function()
        hs.eventtap.keyStrokes("asd") end
    )

Thank you all for helping.


text:
Q: Entity Framework won't set FKs when creating a new record I am attempting to add a Line to an existing header in the following conceptual model through entity framework.

I have exposed this model through a wcf data service. I am attempting to add a record like this:
SampleModelContainer context = new SampleModelContainer(new Uri("http://localhost:57588/WcfDataService1.svc"));

Line newLine = new Line();
newLine.item = 123;

// Generate new LineId
newLine.LineId = context.Lines.ToList().Last().LineId + 1;

// Grab a random header (doesn't matter right now)
newLine.Header = context.Headers.ToList().First();

context.AddToLines(newLine);
context.SaveChanges();

This fails with an error that states that my HeaderId must not be null. However, shouldn't this be filled in by EF because I set the navigation property? If I fill in the HeaderId, it works, but I don't want to set that every time.
Any ideas on what I'm doing wrong?
EDIT: Added connection string

A: Instead of this
newLine.Header = context.Headers.ToList().First();

Do this:
newLine.HeaderId = context.Headers.First().HeaderId;

Don't try to assign objects directly, set the appropriate foreign key (in this case HeaderId) and let the framework take care of the rest.
EDIT
See BrokenGlass's answer.

A: This should work given your entity data model:
Line newLine = new Line();
newLine.Item = 123;

// Grab a random header (doesn't matter right now)
var header = context.Headers.First();
newLine.Header = header; // Establish the relationship

// Add the new line
context.Lines.AddObject(newLine);
context.SaveChanges();


text:
Q: Angular pass arguments from controller to service I'm new in angular and I work with legacy code.
In controller I got:
$scope.data= GenerateService.generate(DataService.all, {
            showOptions : true,
            sort : {
                name: "created",
                dir: "DESC"
            }
        });

this with another directive somehow generates data on site.
And I also got DataService witch invokes web service:
angular.module('services-data-service', []).factory('DataService', function ($resource) {
    return $resource('rest/data/:method/', {}, {
        all:{method:'GET',  params:{method:'all', param:1},           isArray:true}
    });
});

I can't modify GenerateService, but I could modify  DataService, could anybody tell me how dynamicly pass arguments from controller to DataService request?
Now service generates request like:
http://localhost:8087/my-app/rest/data/all?isArray=false&param=1&data=0&fetch=10

So GenerateService somehow add &data=0&fetch=10 parameters. I added manually param=1, so please tell me how pass arguments from controller to DataService


text:
Q: The code is supposed to return string without spaces, but it returns string until first space character I'm making a console calculator, and I want to remove any whitespace that the user might enter while using the program. This is the code:
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string str;
    std::cout<<"Enter sum): ";
    cin>>str;
     str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end());
    cout<<str;
    system("pause");
    return 0;
}

if i entered 2 + 2   =, output should be 2+2=
but the output is: 2
am i using the wrong function here?

A: The problem is with getting the user input, not with stripping the spaces.
The code that removes spaces is correct, as you can see for yourself on IDEone.
The problem is that operator std::istream::operator >> stops reading input on encountering the first whitespace character. You should use another function (such as getLine) instead.

A: Your use of remove_if and erase is fine.  Your method for getting input is not.  operator>> is whitespace delimited.  Use getline instead.
int main()
{
    string str;
    std::cout<<"Enter sum): ";
    getline(cin,str);
    str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end());
    cout<<str;
    return 0;
}

A: I use the following function I wrote:
std::string& ReplaceAll(std::string& sS, const std::string& sWhat, const std::string& sReplacement)
{
    size_t pos = 0, fpos;
    while ((fpos = sS.find(sWhat, pos)) != std::string::npos)
    {
        sS.replace(fpos, sWhat.size(), sReplacement);
        pos = fpos + sReplacement.size();
    }
    return sS;
}

You can adapt it to your needs.


text:
Q: How can I double click to open Nautilus folders in a new window instead of a tab? I want to be able to shift-double click to open a folder in a new window rather than a tab. Currently, both shift-click and control-click open into new tabs.
Is there a way to achieve this?
I find it easier to drag files to a window rather than a tab's title when I want to use the mouse (otherwise I'd use mv).
I know I can get a new window by right clicking and selecting "Open in new window". That's not the solution I'm after.
I'd also like to be able to customize whether that new window becomes active or not by holding down different keys.
Thanks!


text:
Q: Image browse and upload buttons are not showing in magento I am new in Magento...Installed 1.7 community Edition.
I am trying to add images to a Product but 'Browse files' and 'Upload' buttons are missing from the backend.
If any one found solution to this problem please let me know.

A: If you don't use a browser with flash plugin installed (chromium) the buttons will not display. What you need to do is to use a browser with the flash plugin (ex: google-chrome).
If you are on chromium, you can use the developer tools (F12) and you will if the error come from missing flash plugin.

A: These buttons are coming from flash.So check your media folder on following location
design/adminhtml/default/default/template/media
if there is no media folder then copy from fresh magento
This will solve your problem :)

A: Its mostly comes from browser fist check it on any other browser if work fine just reinstall your browser.

A: In mozilla, these buttons will load a little bit slowly. Try to load the page in chrome. I had the same problem when I was new to magento.


text:
Q: JBOSS EAP 6.2 server crash due to out of memory Facing the below issue in production environment but not reproducible in QA environment. Please help to resolve this issue.
We have a java application deployed in Jboss EAP 6.2 cluster setup using domain controller and using HornetQ as messaging system which has 4 queues and one topic and using MDB and MDP listeners for the queues and topic, application works fine with good server health for a week but after a week server crashes with out of memory error. I took the heap dump and analysed it with MAT and the finding is many instances of ClientSessionFactoryImpl (around 1,73,329 instances occupying 707MB of heap memory) is created and it is not getting garbage collected.
Problem Suspect 1

1,73,329 instances of "org.hornetq.core.client.impl.ClientSessionFactoryImpl", loaded by "org.jboss.modules.ModuleClassLoader @ 0x760004438" occupy 741,790,528 (83.13%) bytes. These instances are referenced from one instance of "java.util.HashMap$Entry[]", loaded by "<system class loader>"

Keywords
org.jboss.modules.ModuleClassLoader @ 0x760004438
org.hornetq.core.client.impl.ClientSessionFactoryImpl
java.util.HashMap$Entry[]

OS: RHEL 6.8

server: Jboss EAP 6.2

java: JDK 1.6_24

MAT Screenshot


text:
Q: HDFS dfs -ls path/filename I have copied few files to the path. but when I tried to run the command hdfs dfs -ls path/filename then it returns no file found.
hdfs dfs -ls till directory works but when i use the file name it returns no files found. For one of the file, I copied and pasted the file name using ambari. Then file started getting returned on using hdfs dfs -ls path/filename.
What is causing this issue?

A: Because when you are executing HDFS dfs -ls path/filename what you are saying to hdfs is show me all the files that are in the directory and if end path is a file, of course, you are not listing anything. You must point to a directory not a file.

A: @saravanan it seems like a permission issue if the file shows up only after using ambari.  Make sure the files are owned correctly to confirm the commands.   The ls command will list files and folders per documentation.
Here is full documentation for ls command:
[root@hdp ~]# hdfs dfs -help ls
-ls [-C] [-d] [-h] [-q] [-R] [-t] [-S] [-r] [-u] [-e] [<path> ...] :
  List the contents that match the specified file pattern. If path is not
  specified, the contents of /user/<currentUser> will be listed. For a directory a
  list of its direct children is returned (unless -d option is specified).

  Directory entries are of the form:
    permissions - userId groupId sizeOfDirectory(in bytes)
  modificationDate(yyyy-MM-dd HH:mm) directoryName

  and file entries are of the form:
    permissions numberOfReplicas userId groupId sizeOfFile(in bytes)
  modificationDate(yyyy-MM-dd HH:mm) fileName

    -C  Display the paths of files and directories only.
    -d  Directories are listed as plain files.
    -h  Formats the sizes of files in a human-readable fashion
        rather than a number of bytes.
    -q  Print ? instead of non-printable characters.
    -R  Recursively list the contents of directories.
    -t  Sort files by modification time (most recent first).
    -S  Sort files by size.
    -r  Reverse the order of the sort.
    -u  Use time of last access instead of modification for
        display and sorting.
    -e  Display the erasure coding policy of files and directories.


text:
Q: Node js, why is setTimeout with 50ms is faster than setTimeout 0 I'm a Node.js developer for a year now. Last night I thought I'd do a benchmark between express and http module, basically it is a simple promise that returns a string and it is passed to the response, now i saw that http is quite faster, but I came to a different problem, if I set setTimeout to 50 ms in the ab test with a concurrency of 500 and a 100000 requests, the response times are twice faster than setTimeout 0 or process.nextTick.
Now I know that setTimeout takes it to the next cycle but at the end of the queue, nextTick puts it first on the next cycle, but I really do not understand why setTimeout 50ms is faster than setTimeout 0.
even without setTimeout, the ab test is a lot slower than setTimeout 50ms.
I suspect its something with the apache ab test or maybe i missed something with node?
http.createServer((req,res)=>{
  setTimeout(()=>{
    check().then(data=>{
      res.write(data);
      res.end();
    })
  },0)

}).listen(3000);

let check = () =>{
  return Promise.try(()=>{
    return 'done with Async'
  })
};

// setTimeout 0 times with ab test
Concurrency Level:      500
Time taken for tests:   53.824 seconds
Complete requests:      100000
Failed requests:        0
Total transferred:      9000000 bytes
HTML transferred:       1500000 bytes
Requests per second:    1857.90 [#/sec] (mean)
Time per request:       269.121 [ms] (mean)
Time per request:       0.538 [ms] (mean, across all concurrent requests)
Transfer rate:          163.29 [Kbytes/sec] received

// setTimeout 50ms response times
Concurrency Level:      500
Time taken for tests:   23.174 seconds
Complete requests:      100000
Failed requests:        0
Total transferred:      9000000 bytes
HTML transferred:       1500000 bytes
Requests per second:    4315.12 [#/sec] (mean)
Time per request:       115.872 [ms] (mean)
Time per request:       0.232 [ms] (mean, across all concurrent requests)
Transfer rate:          379.26 [Kbytes/sec] received

A: When you use setTimeout(0), you are adding an extra job on the process which may takes some tick. But using setTimeout(50), requests get to be ready in queue and after 50ms, they will be sent altogether whiteout extra ticks of time. For example consider a request takes 10ms to be sent and 10ms for getting response. By using setTimeout(50), sending 500 requests will take 5000ms plus 50ms for timeout and 10ms for response, it will spend 5060ms. Now if we use setTimeout(0), we will have 10ms for sending request and 10ms for getting response. Therefore, for 500 requests, it will spend 10000ms.


text:
Q: OpenSSL : "unable to verify the first certificate" in every HTTPS site I'm not sure what's wrong with my Ubuntu 18.04 server.
I need to setup a web server on it but when I try to install packages from the Ubuntu repository I cannot download any packages because of certificate verification issues.
Then I tried to hit any random https links with curl and wget, it has the same issue too.
when I try to verify any https site's certificate with
openssl s_client -connect packagist.org:443 -CAfile /etc/ssl/certs/ca-certificates.crt

I got an error code 21 output from OpenSSL like this.

Anyone can help me?


text:
Q: AngularJS in ASP.NET MVC Partial View I am currently loading Partial View returned by MVC controller to a bootstrap model via AngularJS $http.get call. My View in rendered properly in modal dialog, but the only problem is that my partial view which is rendered also uses angular and for some reason angular is not working in my partial view, but if the i convert the same partial view to a normal view it works properly.
Partial View Code:
 @{
    ViewBag.Title = "Add Article Types";
}
//other scripts files e.g app.js and angular.js are included in main layout file.

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        Add New Article Type

    <form novalidate role="form" name="ArticleTypeForm" ng-submit="ArticleTypeForm.$valid && Add(model)">

                Article Type
                <input type="text" required ng-model="model.ArticleTypeName" class="form-control" id="ArticleType" />

    </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" value="Add" >Add</button>
        {{ArticleTypeForm.$valid}}

Controller to load modal with the partial view.
MenuController.js
angular.module('myApp').controller('MenuController', [
        '$scope', '$http', 'httpPreConfig', function ($scope, $http, httpPreConfig) {

            $scope.AddArticleType = function () {
                $.get("/ArticleType/Add")//returns the partial view.
                    .success(function (response) {
                        ShowModal(response);//it properly shows the modal. but angular doesn't work
                    });
            }
        }]);

As you can see from the image below that angular expression is not being evaluated.

Any help would be really appreciated.
Just so that you know, angular expressions etc. are working in normal views.

A: Perhaps the view you're returning is not compiled by Angular. Try compiling it before displaying it in the modal by the $compile service and linking to a correct scope:
$scope.AddArticleType = function () {
    $.get("/ArticleType/Add")
        .success(function (response) {
            $compile(response)($scope);
            ShowModal(response);
        });
}

But actually, this is not the right thing to do in the Angular world. IMO it would be better to use ng-include to load your content inside the modal and then show it to the user.


text:
Q: VMware Snapshot Longer than 3 days Referring to this article
https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1025279
I know it is not good practice to keep a snapshot longer than a day or two because the performance can degrade.
The chain will very rarely go above 4 or 5
However we have a couple of application that before we can push to production have to be tested by the vendor.
Most are pretty good about getting in and testing within a couple days of the snapshot being taken, however there are a few who take a week or more.
There have a been a couple instances, maybe 3 or 4 in the past year we had to a do either a full system restore or a file level restore because the application did not work and we had to revert to the previous application and the snapshot had already been deleted.
The boxes are fairly busy, logging, email, etc.
How do other organizations deal with this? Is there a way to "backup" the snapshots?

A:
How do other organizations deal with this?

I do more or less what you're doing. Keeping snapshots around for a few days for a specific reason isn't bad. You just need to make sure to not forget about them and let them "rot" for any longer than is needed. I have my monitoring system set to alert me if snapshots stay around for longer than three days.

Is there a way to "backup" the snapshots?

Not backup the snapshots per se, but better than that - use a product like Veeam to backup your VM images on a regular basis.

A: In my opinion, the simplest way will be just to backup VMs regularly, as @EEAA mentioned before.
We have quite large amount of VMs running in our environment. So we configured backup Every 1 week. Our setup is StarWind + Veeam.
Also, we considered other solutions, e.g. MS DPM, but encountered some issues with it. Veeam just works great.

A: That's fine... you can live with a snapshot for a few days. Many of us have situations where failed backups or replication leave orphaned snapshots for far longer than 3 days. In my worst case, I inherited systems with 400 day-old snapshots.
For your use case, it doesn't seem like there's anything wrong with the timelines you've described.


text:
Q: How to handle two forms in one asp.net core view? I have two forms in one view, with one ViewModel, with two submission buttons included for everyone, with two independent actions for everyone.
the problem
when I submit either one of them this error appears

An unhandled exception occurred while processing the request.
AmbiguousMatchException: The request matched multiple endpoints.
Matches:
DAS.Controllers.DocumentsController.CreateIn (DAS)
DAS.Controllers.DocumentsController.CreateEx (DAS)

The view
// one ViewModel
@model VMCreateDoc

// First form to submit "CreateIn" action
<form asp-controller="Documents" asp-action="CreateIn" enctype="multipart/form-data">
 // bla bla bla
<input type="submit" class="btn btn-success" value="Save In">
</form>

// Second form to submit "CreateEx" action
<form asp-controller="Documents" asp-action="CreateEx" enctype="multipart/form-data">
 // bla bla bla
<input type="submit" class="btn btn-success" value="Save Ex">
</form>

The actions
    // DocumentInternal Included in the same ViewModel VMCreateDoc
    [HttpPost("FileUpload")]
    public IActionResult CreateIn(DocumentInternal documentIn, List<IFormFile> files)
    {
       // bla bla bla
       return View();
    }

    // DocumentExternal Included in the same ViewModel VMCreateDoc
    [HttpPost("FileUpload")]
    public IActionResult CreateEx(DocumentExternal documentEx, List<IFormFile> files)
    {
       // bla bla bla
       return View();
    }

The view model
public class VMCreateDoc
{
    public DocumentExternal DocEx { get; set; }
    public DocumentInternal DocIn { get; set; }
}

It seems every submission does submit for both forms. So, conflict takes place.

what do you think this problem can be solved?

A: Thanks for all guys who try to help me. and big thanks for Panagiotis Kanavos.
the problem was with the annotation above actions.
all I did is to change it and the problem got solved.
like this
// DocumentInternal Included in the same ViewModel VMCreateDoc
[HttpPost("documentIn")]
public IActionResult CreateIn(DocumentInternal documentIn, List<IFormFile> files)
{
   // bla bla bla
   return View();
}

// DocumentExternal Included in the same ViewModel VMCreateDoc
[HttpPost("documentEx")]
public IActionResult CreateEx(DocumentExternal documentEx, List<IFormFile> files)
{
   // bla bla bla
   return View();
}


text:
Q: HTML image on side same height I am trying to make an image on the side remain the same height as the calculator.
Where should either the css or html go within the structure? I would like to keep the aspect ratio as close to possible
Code: http://jsbin.com/gijitaluta/edit?html,output

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Calculator</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

  <form action="" method="post" id="theForm">
        <fieldset >
          <legend>Calculator</legend>

Use this form to calculate the order total

              Quantity
                <input class="form-control" id="quantity" type="number" value="1"/>

                Price Per Unit
                <input type="text" class="form-control" id="ppu" placeholder="1.00" required>

                Tax Rate (%)
                <input type="text" class="form-control" id="tax" placeholder="0.0" required>

                Discount (%)
                <input type="text" class="form-control" id="discount" placeholder="0.00" required>

                Total
                <input type="text" class="form-control" id="output" placeholder="0.00">

                <button type="submit" class="btn btn-calculate" id="submit">Calculate</button>

       </fieldset>
 </form>

Copyright CSUN

A: This way uses a table. Doesn't require many changes. You'll need a version of the image with the gray edges removed and you'll have to play with padding and/or margins.
http://jsbin.com/xepiren/edit?html,css,output

td {
  background-color:#fff;
}
form {
  padding: 5%;
  /*width: 50%;*/
  font-family: 'Open Sans'
}

#theForm {
  background-color: white;
}

legend {
  color: red;
  font-size: 1.3em;
}

#maincontainer {
  margin: 5%;
}

fieldset {

}

img {
  /*width:30%;*/
  float: right;
  height: 430px
}

body {
  background-color: grey;
}

fieldset {
  padding: 10%;
}

#calculatorcontainer {
  margin: 10%;
  border-style: solid;
  border-style: groove;
}

h4 {
  margin: 0px;
}

footer {
  padding: 10px;
  border-style: solid;
  border-style: groove;
}

footer h3 {
  color:red;
  font-size:80%
}
input {
  width: 90%
}

#submit {
  margin:10px
}

@media (max-width: 479px) {

  img {
  width:30%;
  float: right;
  height: 230px
}

  fieldset {
  padding: 0%;
  }
  form {
    font-size: 7px;
  }

  footer {
    padding: 7px;
  }
  footer h3 {
    color:red;
    font-size:10%
  }
}

@media (min-width: 1000px) {

    img {
  width:30%;
  float: right;
  height: 480px
}

}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Calculator</title>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

            <form action="" method="post" id="theForm">
              <fieldset >
                <legend>Calculator</legend>

Use this form to calculate the order total

                    Quantity
                      <input class="form-control" id="quantity" type="number" value="1"/>

                      Price Per Unit
                      <input type="text" class="form-control" id="ppu" placeholder="1.00" required>

                      Tax Rate (%)
                      <input type="text" class="form-control" id="tax" placeholder="0.0" required>

                      Discount (%)
                      <input type="text" class="form-control" id="discount" placeholder="0.00" required>

                      Total
                      <input type="text" class="form-control" id="output" placeholder="0.00">

                      <button type="submit" class="btn btn-calculate" id="submit">Calculate</button>

             </fieldset>
            </form>

Copyright CSUN


text:
Q: Logical OR (||) followed by colon in Bash I know what the operators && and || do in Bash.
But recently I came across the following case in a shell script:
[[ test1 ]] && { test2 } || :

I am confused as to what does the || : (logical OR followed by :) in the above statement does?
Could anyone elaborate?

A: One step at a time:

*

*: is a shell builtin that is basically equivalent to the true command. If you're interested, there is a very good description of it's history and how it works on this question.

*[[ test1 ]] tests for the presence of test1. (Normally, this would be a variable.)

*{ test2 } executes test2 in the current shell environment. (Normally, this would be a list of commands terminated with a newline or semicolon.)

*&& has a higher precedence then ||. Thus [[ test1 ]] && { test2 } will be evaluated before ||.
Putting it all together,
[[ test1 ]] && { test2 } || :

Means:

*

*If test1 exists, then execute test2

*If test1 doesn't exists, or if test2 fails, then return true (ie: $? == 0)

Things to note:

*

*returned exit code ($?) is not the same as "return no errors"! If test2 fails, you might still see errors in the script's output, but the exit code of the entire command will always be true.

*Errors when executing test2 will not terminate the script if it is executed under set -e.

A: cmd || : is a way to ignore an error caused by cmd. This is useful if the script is executed using set -e and you don't want it to be interrupted if cmd fails.


text:
Q: MongoDB - Sort collection by amount of fields with same value I have a unsorted collection like this:
_id | name
1 | Michael

2 | Tobias

3 | John

4 | Michael

5 | Tobias

6 | Michael

I would like to sort this collection by the number of same values for "name".
So it should look like this:
_id | name
1 | Michael

4 | Michael

6 | Michael

2 | Tobias

5 | Tobias

3 | John

Thank you in advance

A: Model.find({}).sort({ name: 'asc'})

OR
Model.find({}).sort({ name: 1 })

OR
it can also be used with findOne too.
Model.findOne({condition comes here}).sort({ name: 1 })
OR For Aggregation
Model.aggregate(
   [
     { $sort : { name: 1 } }
   ]
)

and here is the reference for aggregation.

A: This needs an aggregation query, as follows.The $group gets the documents grouped by name and their count. The$sort puts them by descending order of the count. The $unwind ungroups the earlier grouped documents. The $project and $replaceRoot stages are for shaping the document into the original form.
db.names.aggregate( [
  { $group: { _id: "$name", count: { $sum: 1 }, doc: { $push: "$$ROOT"} } },
  { $sort: { count: -1 } },
  { $project: { doc: 1, _id: 0 } },
  { $unwind: "$doc" },
  { $replaceRoot: { newRoot: "$doc" } }
] )


text:
Q: C# Enlarge Button When Mouse Cursor Point to it C#.I have 18 buttons to select, but before I will choose a selection. How to enlarge Button with BackgroundImage when mouse point in it? It's like ToolTip, when you point the cursor it will show the Text. But in my case, it will enlarge the Button. Thanks
Button[] ButtonSelect = new Button[17];
for (i = 1; i <= 18; i++)
{
ButtonSelect[i] = new Button();
ButtonSelect[i].BackgroundImage = Properties.Resources.SelectImages[i];
}

A: Make the size of the Button grow larger in MouseEnter event:
Button btn = (Button)sender;
int width = btn.Size.Width;
int height = btn.Size.Height;
int larger = 10;
btn.Size = new Size(width + larger, height + larger);

Then in the MouseLeave event do the opposite by shrinking the button size.
You can hook up the events like this:
for (i = 1; i <= 18; i++)
{
ButtonSelect[i] = new Button();
ButtonSelect[i].BackgroundImage = Properties.Resources.SelectImages[i];
ButtonSelect[i].MouseEnter += new System.EventHandler(Btn_MouseEnter);
ButtonSelect[i].MouseLeave += new System.EventHandler(Btn_MouseLeave);
}


text:
Q: loadUrl error "ERR_ABORTED (-3) error" can't be catched I have an page that is behind an Auth0 login. When you have the proper session, you are automatically redirected to a final page.
The problem is I am doing this using loadURL on Electron and the loadURL throw a Uncaught (in promise) Error: ERR_ABORTED (-3).
I would like to rescue this error, because visually everything is working well on my app and I do not see a way to fix this error.
But I am not able to rescue with did-load-fail. Here is a code snippet I have on my app.
  const { remote } = require('electron');
  const win = new remote.BrowserWindow({
    width: 800,
    height: 600,
    show: false,
    webPreferences: {
      partition: LOGIN_PARTITION,
      nodeIntegration: false,
    },
  });
  win.webContents.on('did-finish-load', () => {
    console.log('finish-load'); // triggered twice
  });
  win.webContents.on('did-fail-load', () => {
    console.log('fail-load'); // never triggered
  });
  try {
    win.loadURL(urlThatContainsAutoRedirect);
  } catch (error) {
    console.log('catch loadUrl'); // never triggered
  }
  win.show();

How could I avoid this error or rescue it properly?

A: loadUrl returns Promise (https://github.com/electron/electron/blob/c41b8d536b2d886abbe739374c0a46f99242a894/lib/browser/navigation-controller.ts#L53) that you can't catch via synchronous try/catch. either use catch handler in then or use .catch. Also note it may not work in remote proxied renderer process, in that case it need to be handled in main process.


text:
Q: facebook graph api: understanding offset_y offset_x API Hello I am trying to understand what offset_y means in facebooks graph API https://developers.facebook.com/docs/graph-api/reference/cover-photo/.

y_offset: When greater than 0% but less than 100%, the cover photo overflows
  vertically. The value represents the vertical manual offset (the
  amount the user dragged the photo vertically to show the part of
  interest) as a percentage of the offset necessary to make the photo
  fit the space.

I have tried using the solution in facebook graph api: offset_y offset_x,
but it does work.
for example, this event https://www.facebook.com/events/164312630996898/. The event picture has a css top offset of -3px:

In order to calculate this, I will attempt to use the method in facebook graph api: offset_y offset_x
The image is 500x622px (when resized to fit), the event image space is 500x262px. 622px-262px = 360px. using the facebook graph API (https://developers.facebook.com/tools/explorer?method=GET&path=164312630996898%3Ffields%3Dcover&version=v2.12) gives an offset-y of 9:

so 9% of 360px is, 32.4px, but the actual answer should be 3px.
any help would be greatly appreciated!

A: So I have experimented with this a lot and I am 100% sure the offset_x, offset_y are not properly documented and may not be even sufficient in many cases to even depict the offset
In my case I used two images listed below and did some experiment with different drags

The event was created on
https://www.facebook.com/events/901430313369669/

And data collected was below for the above 2 images

For the 2nd image you can see that whether i kept the image left aligned, right aligned or center aligned the offset were always 0. But the left was still calculated. This means facebook is not share the offset information correctly. It is most probably a bug based on observation from second image.
Also weird thing is the -77, 177 entries from the first image


text:
Q: How to restrict user from going to Next Page if all the fields are not populated in Eclipse SWT I have a requirement like this:-
The user shouldn't be allowed to traverse to the Next Page in case he has not entered all the required parameters in the First Page itself. Also, in case he has entered something erroneous he should be displayed the warning and restricted from going to the Next Page. This needs to be implemented using Eclipse Plugin Developement using JFace/SWT.

A: Check your GUIItem.value() for empty on the Next Page button action or deactivate the button until the required fields have data.

A: use WizardPage.setPageComplete(boolean complete) method (easy way), or use JFace databinding. Even better if you wire databinding with org.eclipse.jface.databinding.wizard.WizardPageSupport.

A: Override the ispagecomplete method to return true only when all the values in your wizardpage are complete. When the user edits any value ensure that you have listener on these fields that call getContainer().updatebuttons() This should work for your requirement.


text:
Q: android sqlite date range I have a sqlite DB in my Android project, and I try to select all rows between dates.
But no row is returned by this query:
String where = OperationEntry.COLUMN_NAME_ENTRY_ACCOUNT_FK + " = ? AND " +
           OperationEntry.COLUMN_NAME_ENTRY_DATE + " > date('2013-01-01') AND "+
           OperationEntry.COLUMN_NAME_ENTRY_DATE + " < date('2013-12-31') ;";
String[] whereValue = {accountName};

Cursor c = db.query(
    OperationEntry.TABLE_NAME,  // The table to query
    projection,                 // The columns to return
    where,          // The columns for the WHERE clause
    whereValue,                 // The values for the WHERE clause
    null,                       // don't group the rows
    null,                       // don't filter by row groups
    sortOrder                   // The sort order
);

Moreover, if I use 2013-01-01 and 2014-12-31, all rows are matching.
I have tested with and without date's function, I have the same issue.
Note that OperationEntry.COLUMN_NAME_ENTRY_DATE is a Date type.
Can you help me? Do you find any mistake in my code?
Thank's
Jonathan.
EDIT:
I put here some additional code.
query for table creation:
public static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + OperationEntry.TABLE_NAME + " (" +
    OperationEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
         ... +
    OperationEntry.COLUMN_NAME_ENTRY_DATE + " DATE, " + ...
" )";

query for insertion:
GregorianCalendar calendar = ...;
String date = calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
ContentValues values = new ContentValues();
values.put(OperationEntry.COLUMN_NAME_ENTRY_TITLE, operation.getTitle());
values.put(OperationEntry.COLUMN_NAME_ENTRY_QTE, operation.getQte());
values.put(OperationEntry.COLUMN_NAME_ENTRY_DATE, date);
    ...

long newRowId;
newRowId = db.insert(
    OperationEntry.TABLE_NAME,
    null,
    values);

A: I'm not Android expert but you are obviously misusing date SQLite function. date('2013-01-01') is pointless, it evaluates to '2013-01-01'.
Try instead:
String where = OperationEntry.COLUMN_NAME_ENTRY_ACCOUNT_FK + " = ? AND " +
           "date(" + OperationEntry.COLUMN_NAME_ENTRY_DATE + ") > '2013-01-01' AND " +
           "date(" + OperationEntry.COLUMN_NAME_ENTRY_DATE + ") < '2013-12-31';";

You need to ensure column data returned is properly formated, not the string you hard-coded!

A: try this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date firstDate = formatter.parse("2013-01-01");
Date endDate = formatter.parse("2013-12-31");
String where = OperationEntry.COLUMN_NAME_ENTRY_ACCOUNT_FK + " = ? AND " +
OperationEntry.COLUMN_NAME_ENTRY_DATE + " > ? AND "+
OperationEntry.COLUMN_NAME_ENTRY_DATE + " < ?";
String[] whereValue = {accountName, firstDate.getTime(), endDate.getTime()};

A: sqlite has no buildin dateformat. the result of you query depends on how the data is stored in the colum ENTRY_DATE.
i am using int values for sqlite-date which are convertet by java code. if your businesslayer wants to search for date-range the databaselayer can search for an int range.
if you execute your query without the where filter, how do the result values look like?
for example i convert from long to string like this
final private static java.text.DateFormat isoDateTimeformatter = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ");

public static String getDateStr(long dateTime) {
    if (dateTime == TimeSlice.NO_TIME_VALUE) {
        return "";
    } else {
        return isoDateTimeformatter.format(new Date(dateTime));
    }
}

to convert from string back to long i use this
public static long parseDate(String mDateSelectedForAdd) {
    try {
        return isoDateTimeformatter.parse(
                mDateSelectedForAdd).getTime();
    } catch (ParseException e) {
        Log.w(Global.LOG_CONTEXT,"cannot reconvert " + mDateSelectedForAdd + " to dateTime using " + isoDateTimeformatter,e);
        return TimeSlice.NO_TIME_VALUE;
    }
}


text:
Q: Verify that in a range of bits only one is on I've written this algorithm where three condition bits are evaluated to determine how text should be aligned based on a given address.
7 = Justify right6 = Justify center5  = Justify left.
Currently, there isn't a default implemented so if nothing is defined, ZF is returned indicating nothing happened. Text not being on the screen where expected will be an indicator too.
        test    al, 111000000B
        jz      Done

Now this solution works for me because as part of the ABI I'm designing, where CF denotes error. This addresses the need and will work for 16/32/64 bit, but I want to think there is a more efficient way or at least one that isn't so weighty.
    0  0FBC46FE          bsf ax,[bp-0x2]
    4  88C3              mov bl,al
    6  0FBD46FE          bsr ax,[bp-0x2]
    A  28C3              sub bl,al
    C = 12 bytes

As there is special processing for each condition at epilogue, I could catch it there by rotating bit AH into carry and keep doing that until CY and ZF. If there is a carry and non-zero then I know there was more than 1 bit set or I could just ignore extraneous bits and then function would be prioritized by bit position.

A: You might want to redesign this to use 3 or 4 values in a 2-bit field, instead of a bitmap, if they're all mutually exclusive anyway.  (See my comments on the question).
After masking off the non-bitmap bits:
One pretty good way is to use the (n & (n - 1)) == 0 bithack to an integer for being a power of 2.  (Or actually, to test that it has at most 1 bit set, not exactly 1 bit set, because that expression is true when n == 0).
You can implement that with lea edx, [rax-1] / and edx, eax / add edx, -1, which leaves CF set if eax had more than 1 bit set, otherwise CF is clear.  (add edx, -1 carries for every edx value except 0).

On CPUs with BMI1
VEX prefixes are not usable in real-mode or virtual-8086 mode (for compat with some old real-mode conventions of using the same previously-illegal bit pattern as a trap). But they are usable in 16-bit protected mode I think, and definitely in 32 / 64-bit mode.  This is relevant because blsr is encoded with a VEX prefix.
There's an extremely efficient way to implement that bithack with blsr (Reset Lowest Set Bit), because it sets flags in a way that's useful for this.  Almost as if instruction-set architects knew what they were doing...:
and   eax, 11100000b     ; clear other bits

; requires BMI1
blsr  edx, eax           ; destination = a dummy register, also sets flags

jnz  multiple_bits_were_set       ; and thus edx still has a bit set
jc   input_was_zero

i.e. it does everything you want in one instruction, even using CF in a way that works for your code without a cmc.  Your multiple_bits_were_set branch target could just stc and fall into input_was_zero.
There's no JCC that jumps if (CF==1 or ZF==0), only ja (CF=0 and ZF=0) and jbe (CF=1 or ZF=1).  I don't think even cmc can help; we'd really need to complement ZF, not CF.  (Skylake and later CPUs don't have flag-merging uops or partial flag stalls, and at worst on Haswell it would be a merging uop not a stall, if you were doing something where cmc was useful.  Perhaps with a different use-case, since it doesn't seem useful with blsr.)
You might want 2 branches.  Or since you're probably branching on which bit was set, maybe only use blsr to check for multiple bits set, and then use cmp al, 01000000b / jae bits_1_or_2 to sort things out into highest or 2nd highest vs. lowest (of the top 3) or none set.

If you want to only branch once for no bits or too many bits:
 AND   eax, mask

 blsr  edx, eax     ; edx = 0 iff no more than 1 bit was set in the input
 ; CF=1 iff eax==0
 adc   edx, 0
 jnz   not_exactly_one_bit_set

The adc can't wrap to zero because blsr always leaves the low bit clear, by definition.  edx can only be zero (and thus ZF can only be set) if edx=0 after BLSR, and the adc didn't add anything.
If your bitmask doesn't include the high bit of the register, adc edx,edx would also work, saving one byte.  But adc with an immediate 0 may is special-cased to 1 uop even on Haswell, where the general case is 2 uops there.  (Later Intel CPUs always have 1 uop adc, earlier Intel CPUs don't have BMI1.  AMD CPUs always have 1 uop adc.)


text:
Q: OpenShift: How to set the log-level of JBoss AS In OpenShift I want to set the log level of JBoss AS to "DEBUG".
In my local JBoss installation I can achieve this by editing the logging configuration in JBOSS_HOME/standalone/configuration/standalone.xml.
The default level of the root-logger is "INFO", but when I set that to "DEBUG" and restart JBoss, then I have achieved my goal.
How can I acheve the same in OpenShift?
I can SSH into the OpenShift App and manually modify jbossas/standalone/configuration/standalone.xml. However when I restart the App, all those changes are lost, and consequently the level of the root-logger is reset to "INFO".

A: If you want this settings to be permanent you should add something to *.openshift/action_hooks/deploy* which applies this setting during deploy of the application. The hook is part of the git repo, so you can modify it locally and it gets executed during deployment. See also https://www.openshift.com/developers/deploying-and-building-applications.
You could use a perl one lines to do the modification. Something like this should do:
perl -p -i -e 's/<level name=\"INFO\"\/>/<level name=\"DEBUG\"\/>/g' <path-tp-standalone-xml>


text:
Q: why json values converted to string in my code I have a few values that I want give from Json
what I received from server:
(as you can see values aren't string)
 "HP": {
  "BaseValue": 44.0, //float
   "Point": 3.0, //float
   "UpdateFactor": 1.5 //float
   }

After receiving jason from server
IEnumerator ReceiveJson()
{
    var postScoreURL = Url;
    var postHeader = new Dictionary<string, string>();
    postHeader.Add("Content-Type", "application/json");
    WWW request = new WWW(postScoreURL, null, postHeader);
    yield return request;
    if (request.error != null)
    {
    }
    else
    {
        Receive = JSONNode.Parse(request.text);
        Debug.Log(Receive);
    }
}

why I received string value?
(but here I have string values!!!)
 "HP": {
  "BaseValue": "44.0", //string
   "Point": "3.0", //string
   "UpdateFactor": "1.5" //string
   }

A: Your json is invalid.
You can check your json at Jsonlint.
Your json needs to look like this:
{
    "HP": {
        "BaseValue": 44.0,
        "Point": 3.0,
        "UpdateFactor": 1.5
    }
}