text:
Q: How to write a Sparql query for checking duplicates without using GROUP BY? I have a fairly complicated Sparql query that I don't know how to write.  Here's a simplified background of the ontology:
A class "Fruit" has subclasses "Apple" and "Mango". Another class "Nutrition" has subclasses "Vitamin" and "Fiber". "fruit_has_nutrition" is a property that has domain "Fruit" and range "Nutrition".
Then I created the following instances:
Apple_1, Mango_1, Vitamin_1, Vitamin_2, Fiber_1 and Fiber_2, Fiber_3.
The following is what Apple_1 and Mango_1 look like:
fruit:Apple_1
   rdf:type fruit:Apple ;
   fruit:fruit_has_nutrition fruit:Fiber_1 ;
   fruit:fruit_has_nutrition fruit:Fiber_2 ;
   fruit:fruit_has_nutrition fruit:Vitamin_1 ;
   rdfs:label "Apple 1" ;.

fruit:Mango_1
   rdf:type fruit:Mango ;
   fruit:fruit_has_nutrition fruit:Fiber_3 ;
   fruit:fruit_has_nutrition fruit:Vitamin_2 ;
   rdfs:label "Mango 1" ;.

Assume that an instance of fruit can contain as many kinds of nutrition as possible, but for each kind, it should only contain 1 instance of that nutrition. If that's the case, Apple_1 violates the assumption because it has two instances of Fiber.
Therefore, the query I want to write is "give me all the fruits which have multiple nutritions of the same kind, and give me the type of those nutritions". With the data above, it should give me back Apple_1 and Fiber.
The challenge part is that I can't just GROUP BY rdf:type because it loses distinctions on the kinds of fruit. I tried MINUS (All fruits - fruits without violation):
SELECT
WHERE {
    ?fruit fruit:fruit_has_nutrition ?nutrition .
    ?nutrition rdf:type ?type .
        MINUS {SELECT   DISTINCT ?fruit ?type
                 WHERE {
                    ?fruit fruit:fruit_has_nutrition ?nutrition .
                    ?nutrition rdf:type ?type .
                        }
                }
}

But that ends up giving me nothing.
Is there a way to group by two variables? How else can I write this query?
Thank you so much!!

A: Maybe I don't understand the problem, but why can't you group by fuit type as well?
As usual, no minimal sample data that can be used for testing, thus, an untested query that might be wrong:
select ?fruit ?fruit_type {
  ?fruit fruit:fruit_has_nutrition ?nutrition .
  ?nutrition rdf:type ?fruit_type .
}
group by ?fruit ?fruit_type
having (count(?nutrition) > 1)


text:
Q: converting gradient to linear-gradient syntax I'm trying to convert a CSS style from gradient linear-gradient, but am a little confused about the syntax:
background: gradient(linear, left top, right top, from(#BF942F), to(#BF942F), color-stop(0.5, #F8F8DC));

I know I can obviously remove the 'linear' parameter but I'm a bit lost after that:
background: linear-gradient(left top, right top, from(#BF942F), to(#BF942F), color-stop(0.5, #F8F8DC));

Can anyone offer some insight?

A: *

*left top, right top should map to a single direction parameter: to right. The top bit is insignificant since this is a horizontal linear gradient.

*The from, to and color-stop functional notations are not used; instead the color stops are specified in order. Based on what you have, it looks like it should be #BF942F, #F8F8DC, #BF942F. Since each color stop is equidistant (0%, 50%, 100%) there is no need to specify the precise location of each one.
Hence:
background: linear-gradient(to right, #BF942F, #F8F8DC, #BF942F);

Here's a comparison of the old and new syntaxes. Note that since the notation that you have is a WebKit invention, it only exists as -webkit-gradient() and thus can only be seen in a WebKit-based browser such as Safari or Chrome.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't seem to get my website's mobile nav to work I have been creating a website and I am using Bootstrap 3.2.0 with a material design theme. When I go on my website and resize the window to be smaller and click on the button to open the nav nothing happens.
This is my code:

<link rel="stylesheet" href="css/bootstrap.min.css"></link>

<link rel="stylesheet" href="material/dist/css/ripples.min.css"></link>

<link rel="stylesheet" href="material/dist/css/material-wfont.min.css"></link>

<link rel="stylesheet" href="fezvrasta.github.io/snackbarjs/dist/snackbar.min.css"></link>

<meta content="width=device-width, initial-scale=1" name="viewport"></meta>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-warning-collapse" aria-controls="navbar">

                </button>
                Python for Beginners

Learn

Contact

This is the material theme's site: http://fezvrasta.github.io/bootstrap-material-design/#about
I haven't made a JSFiddle because I'm not sure how to add bootstrap to it.
The site is online at: pythonforbeginners.site90.com

A: Include the bootstrap script--without it that stuff wont work. Add this to your doc, below your jQuery script tag:


text:
Q: CMake files to build main and tests separately I have the following directory structure:
main.cpp
CMakeLists.txt
src/
    some_function.h
    some_function.cpp
    some_class.h
    some_class.cpp
    CMakeLists.txt
test/
    catch.hpp
    tests.cpp
    CMakeLists.txt

CmakeLists.txt in the project root:
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CXX_STANDARD 11) # C++11

project(main)

add_subdirectory (src)

add_executable(main main.cpp)

target_link_libraries (main some_class)

CmakeLists.txt in the src/:
add_library (some_class some_class.h some_class.cpp some_function.h some_function.cpp)

The above works to build and run the main target.
Now I want to build and run tests. The file tests.cpp includes some_function.h and some_class.h. However, I am not sure how to add the src/ directory here.
This is what I have so far in test/ (results in a linking error for the function in some_function.h):
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CXX_STANDARD 11) # C++11

project(tests)

set(CATCH_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
add_library(Catch INTERFACE)
target_include_directories(Catch INTERFACE ${CATCH_INCLUDE_DIR})

add_executable(tests tests.cpp)
target_link_libraries(tests Catch)

A: Just link the some_class library target to the tests target, like you did with the main executable target.
CmakeLists.txt in the project root:
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CXX_STANDARD 11) # C++11

project(main)

add_subdirectory (src)
# Add the test sub-directory also.
add_subdirectory(test)

add_executable(main main.cpp)

target_link_libraries (main some_class)

CmakeLists.txt in the test directory:
project(tests)

set(CATCH_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
add_library(Catch INTERFACE)
target_include_directories(Catch INTERFACE ${CATCH_INCLUDE_DIR})

add_executable(tests tests.cpp)
# Link 'some_class' here also!
target_link_libraries(tests PRIVATE some_class Catch)

A: Normal targets created by add_library() or add_executable() have the scope of the project not the directory that's why their name must be unique within the project. So you can "target_link" some_class to your target tests even if target tests is not in a subdirectory of src/...

The <name> corresponds to the logical target name and must be globally unique within a project.

ref: https://cmake.org/cmake/help/latest/command/add_library.html#normal-libraries
This is not the case for imported targets.

The [imported] target name has scope in the directory in which it is created and below, but the GLOBAL option extends visibility. It may be referenced like any target built within the project.

ref: https://cmake.org/cmake/help/latest/command/add_library.html#imported-libraries


text:
Q: How to hide a  with media queries? I'm trying to hide a certain div element  only on my ipad and mobile versions of my site.
I have it hidden but it's not really "gone" if that makes sense? it's position is till taken just invisible.
Is there a way to completely remove it on mobile and ipad so that my text re-position itself on those platforms?
Thanks for the help!

A: Below are list of standard media queries for devices
/* Large screens ----------- */
/*some CSS*/

/* Desktops and laptops ----------- */
@media only screen and (max-width : 1824px) {...}

/* iPads (landscape) ----------- */
@media only screen and (max-width : 1224px) {...}

/* iPads (portrait) ----------- */
@media only screen and (max-width : 1024px) {...}

/* Smartphones (landscape) ----------- */
@media only screen and (max-width : 768px) {...}

/* Big smartphones (portrait) (ie: Galaxy 3 has 360)*/
@media only screen and (max-width : 640px) {...}

/* Smartphones (portrait) (ie: Galaxy 1) */
@media only screen and (max-width : 321px) {...}

as per your requirement within these blocks you need to add CSS as follows
.foo{display:none;} /* foo is class of element you need to hide*/

either you can use display:none or visually hide as follows
.visuallyhidden {
  position: absolute;
  overflow: hidden;
  clip: rect(0 0 0 0);
  height: 1px; width: 1px;
  margin: -1px; padding: 0; border: 0;
}

useful question
CSS-Tricks article

A: You must use .divclass{display:none;} display none will hide your DOM elements to browser.No evidence of block there.
Eventually visibility property
    .divclass{ visibility:invisible; } only hides DOM element to Users. Blank Space Background will be displayed instead of that block.


text:
Q: CUDA mixing float and double causing kernel to not execute Using CUDA C I have a statistics kernel that when I add a breakpoint in VS2012 anywhere within the kernel and include the stddev line with the preceding variable definitions:
double mean, stddev, sumOfValues, sumOfValuesSquared;
unsigned int n;

// acquire greater than 0 values for: sumOfValues, sumOfValuesSquared, and n

stddev = (float)(sqrt((double)(n) * sumOfValuesSquared - (sumOfValues*sumOfValues)) / (double)(n));

The breakpoint is never reached, and the kernel does not execute.  When I remove that single line, the kernel executes.  I thought it had to do with the sqrt, but it does not.  I have another line:
mean = sumOfValues / n;

When I use that line, it also does not execute the kernel.  What am I missing about type conversions in CUDA (is this a registers issue, or single precision vs. double precision)?
-- UPDATE (10/2/2013 14:25 CST) --
I adjusted the number of threads from 1, and then 1024.  The first run, it goes to my breakpoint, the second with the high thread count, the kernel does not execute.  Please see the code, below:
#include "stdafx.h"

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>

typedef struct
{
    unsigned int value;
} ValueStruct;

__global__ void FailsToExecute(ValueStruct *vs)
{
    unsigned int numerator = vs->value;
    unsigned int denominator= 3;
    bool eject = false;

    if(denominator > 0)
    {
         if(1.0f * numerator / denominator > 17.98f)
             eject = true;
         else
             eject = false;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    ValueStruct *vsHost;
    ValueStruct *vsDevice;

    cudaMallocHost((void **)&vsHost, sizeof(ValueStruct));
    cudaMalloc((void **)&vsDevice, sizeof(ValueStruct));

    vsHost->value = 54;

    cudaMemcpy(vsDevice, vsHost, sizeof(ValueStruct), cudaMemcpyKind::cudaMemcpyHostToDevice);

    dim3 blocks(5);
    dim3 threads(1024);

    FailsToExecute<<<blocks, threads>>>(vsDevice);

    return 0;
}

How do I calculate / cope with register boundaries, I don't know much about them?

A: Kernels that require more resources than are available (e.g. registers, shared memory) will not launch. This can be detected by appropriate error checking, for example as shown here:
https://devtalk.nvidia.com/default/topic/545591/how-to-debug-kernel-throwing-an-exception-/?offset=16
Due to allocation granularity effects that are different for each GPU architecture, the accurate calculation of resources required for the combination of a particular kernel with a particular launch configuration can be non-trivial. For this reason, I would suggest using the CUDA occupancy calculator which incorporates the granularity details. You can find the occupancy spreadsheet here:
http://developer.download.nvidia.com/compute/cuda/CUDA_Occupancy_calculator.xls

A: Is it possible that the nvcc compiler optimized the kernel away to nothing?  Looking at the kernel function, I could see how this could safely be optimized to zero instructions, since it effectively doesn't do anything.
__global__ void FailsToExecute(ValueStruct *vs)
{
    unsigned int numerator = vs->value;
    unsigned int denominator= 3;
    bool eject = false;

    if(denominator > 0)
    {
         if(1.0f * numerator / denominator > 17.98f)
             eject = true;
         else
             eject = false;
    }
}

Setting eject doesn't matter since eject is never used again.  So we can scratch out those two assignments.  The expression in the if () condition doesn't modify anything, and since it there's nothing to do for either branch of the if statement, it looks like the if() can be removed.  And continuing likewise back up to the top of the kernel, it seems like it can all be optimized to nothing and still have the kernel produce the same result.
Maybe if you added some kind of output, like maybe an array of bools, and saved the results of eject into that array, then you would see the kernel being executed.


text:
Q: RegExp replace substring in JavaScript I have a few signal flags in a serialized string and I need to remove the flag from the string when the user requests a certain operation.
I was unable to find a regex that works in all cases for the below string.
var flags = "out:ab,bc,bcc,cd";

This is the closest I got (e.g. removing bc flag)
flags.replace(/[:,]bc\b/, "");

Result is out:ab,bcc,cd which is cool, but when removing ab I will get outbc,bcc,cd which is wrong. The result must always keep the string serialized, e.g. out:flag1,flag2
I tried capturing subpatterns but could not find an all-round working combo.
-- more info:
Flags are 0/1 signals, if a flag is present I must remove it.
Out: is the operation mode and it's the opposite of In: (this is a second group of flags). To put it simple, Out: is a "allow all, but blacklist these", where In: is "deny all, but whitelist these". The app can run in either mode. ab, bc, cd ... are sample alphabetical keys.

A: Use non-capturing parentheses:
var q = ['cd', 'bc'].join('|'),
    re = new RegExp('(?:[:]('+q+'))|(,('+q+')(?=,))|(,('+q+')$)', 'g'),
    flags = "out:ab,bc,bcc,cd";
flags.replace(re, '');
=> "out:ab,bcc"

From MDN's Regular Expressions:

(?:x) Matches 'x' but does not remember the match. The parentheses are called non-capturing parentheses, and let you define subexpressions for regular expression operators to work with. Consider the sample expression /(?:foo){1,2}/. Without the non-capturing parentheses, the {1,2} characters would apply only to the last 'o' in 'foo'. With the capturing parentheses, the {1,2} applies to the entire word 'foo'.

Edit: An explanation of the RegExp
/(?:[:](cd|bc))|(,(cd|bc)(?=,))|(,(cd|bc)$)/g

There are three sections, separated by pipes. ?:[:](cd|bc) covers flags right after the semicolon; ,(cd|bc)(?=,) covers flags between commas, including the preceding comma in the matched expression; ,(cd|bc)$ covers flags at the end of the string, also including the preceding comma.

Edit 2:
Fixed RegExp, replace q with the flags you want to match.


text:
Q: MOSS custom MasterPage not displaying on all site pages I have created a master page under my top level MOSS site. I have applied it to a sub-site. When I go to some pages such as "Site Settings" the custom master page has not been applied. Do you know why this may be happening? I have set the custom master page as the System and Site page. I am using http://www.heathersolomon.com/blog/archive/2007/01/26/6153.aspx as the base of my custom master. I have just added div tags and id's to help position elements.

A: Yes, this is true - the pages under /_layouts/ folder (for instance, http://yoursite/_layouts/viewlsts.aspx) do not use the default.master, rather application.master is used there.
EDIT: You should take a look at another Heater Solomon's article about your problem - http://www.heathersolomon.com/blog/archive/2006/10/26/5914.aspx


text:
Q: Restore default permissions on /dev/pts Hey guys I tried to activate multiuser for some screens so I used
screen -A -m -d -S test
screen -S stest -X multiuser on
screen -S test -X acladd testuser

But I got
chmod /dev/pts/17: Permission denied

Unfortunately I thought it would be a great idea to play around with the permissions.
Now I´m with the folder it self
drwxrw-rw- 2 root sys            0 Jul 10 09:39 pts

And the files inside with the following
total 0
crw-rw-rw- 1 root   sys         136,  0 Aug  4 22:30 0
crw-rw-rw- 1 markus mTeam 136,  1 Aug  1 23:20 1
crw-rw-rw- 1 markus mTeam 136, 10 Jul 24 13:47 10
crw-rw-rw- 1 markus mTeam 136, 11 Jul 27 17:43 11
crw-rw-rw- 1 markus mTeam 136, 12 Aug  4 22:33 12
crw-rw-rw- 1 markus mTeam 136, 13 Aug  4 22:32 13
crw-rw-rw- 1 markus mTeam 136, 14 Aug  4 22:33 14
crw-rw-rw- 1 markus mTeam 136, 15 Jul 27 20:12 15
crw-rw-rw- 1 markus mTeam 136, 16 Aug  4 21:46 16
crwxrwxrwx 1 markus mTeam 136, 17 Aug  4  2021 17
crw-rw-rw- 1 markus mTeam 136, 18 Aug  4 22:07 18
crw-rw-rw- 1 markus mTeam 136, 19 Aug  4 16:29 19
crw-rw-rw- 1 markus mTeam 136,  2 Jul 27 17:43 2
crw-rw-rw- 1 markus mTeam 136, 20 Jul 27 17:37 20
crw-rw-rw- 1 markus mTeam 136, 22 Jul 27 17:43 22
crw-rw-rw- 1 markus mTeam 136, 23 Aug  1 20:16 23
crw-rw-rw- 1 markus mTeam 136, 24 Aug  4 17:55 24
crw-rw-rw- 1 markus mTeam 136, 25 Jul 27 17:43 25
crw-rw-rw- 1 markus mTeam 136, 28 Jul 27 12:29 28
crw-rw-rw- 1 markus mTeam 136, 29 Jul 27 17:43 29
crw-rw-rw- 1 markus mTeam 136,  3 Aug  4 22:24 3
crw-rw-rw- 1 markus mTeam 136, 31 Jul 27 17:43 31
crw-rw-rw- 1 markus mTeam 136, 33 Jul 27 17:43 33
crw-rw-rw- 1 markus mTeam 136,  4 Aug  4 22:33 4
crw-rw-rw- 1 markus mTeam 136,  5 Jul 13 10:01 5
crw-rw-rw- 1 markus mTeam 136,  6 Aug  4 22:14 6
crw-rw-rw- 1 markus mTeam 136,  7 Aug  4 22:14 7
crw-rw-rw- 1 markus mTeam 136,  8 Aug  4 22:33 8
crw-rw-rw- 1 markus mTeam 136,  9 Jul 10 09:41 9
crw-rw-rw- 1 root   sys           5,  2 Jul 10 09:39 ptmx

On some other pages I have read that the permissions can change and aren't static.
And my problem is now that since I changed the permissions I'm not able to create new screens nor operate them.
When I use for example:
screen -A -m -S test

I get
Cannot open /dev/pts/27: Permission denied

So is there a way to fix my stupid mistake?
I'm grateful for every help I get :)
I'm using Ubuntu 20.10

A: Without the x permission bit for anyone other than root, the /dev/pts directory is inaccessible for regular users.
Start with:
sudo chmod a+rx /dev/pts

Note that /dev and /dev/pts are RAM-based: any changes you make to them won't persist over a reboot, unless you make an udev rule or something else to re-apply your changes. So a simple reboot would also undo your mistake.


text:
Q: rdkafka 0.8.1 ERROR: Failed to build gem native extension I'm runnning bundle install Then I get this error:
Fetching rdkafka 0.8.1
Installing rdkafka 0.8.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

Extracting v1.4.0 into tmp//ports/librdkafka/1.4.0... OK
Running 'configure' for librdkafka 1.4.0... ERROR, review '/Users/codegeek/.rvm/gems/ruby-2.5.1@ls-member/gems/rdkafka-0.8.1/ext/tmp/ports/librdkafka/1.4.0/configure.log' to see what happened. Last lines are:
========================================================================
source:
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
void foo (void) {
   int s = socket(0, 0, 0);
   close(s);
}

 libpthread ()
    module: self
    action: fail
    reason:
compile check failed:
CC: CC
flags: -lpthread
  -g -O2 -Wall -Wsign-compare -Wfloat-equal -Wpointer-arith -Wcast-align -Wall -Werror _mkltmpVFiBMn.c -o _mkltmpVFiBMn.c.o   -lpthread:
mklove/modules/configure.base: line 1349: -g: command not found
source: #include <pthread.h>

But then it will suggest to do:
Make sure that `gem install rdkafka -v '0.8.1' --source 'https://rubygems.org/'` succeeds before bundling.

So I'll run gem install rdkafka -v '0.8.1' --source 'https://rubygems.org/' but then
it will produce an error too
Building native extensions. This could take a while...
ERROR:  Error installing rdkafka:
    ERROR: Failed to build gem native extension.

Please help. Thanks!

A: I was able to fix it by providing the following compilation flags
CPPFLAGS=-I/usr/local/opt/openssl/include LDFLAGS=-L/usr/local/opt/openssl/lib gem install rdkafka -v '0.8.1'

I was able to find the answer in this GitHub issue
Hopefully that works for you!

A: just run the following on your terminal:
xcode-select --install

A: Based on @Luan answer I could fix my error. I have 2 homebrews installed which creates a mess in some occasions.
If you are in an arm silicon macos try
CPPFLAGS=-I/opt/homebrew/opt/openssl@1.1/include/ LDFLAGS=-L/opt/homebrew/opt/openssl@1.1/lib gem install rdkafka -v '0.10.0'


text:
Q: Parse error: syntax error, unexpected '[', expecting ',' or ';' on line 30 i get this error `Parse error: syntax error, unexpected '[', expecting ',' or ';'
in my footer.php for some reason, i have had a look through and cannot figure out whats wrong with it ( ive had very little sleep so i may just of missed it )
footer.php
the full error is -
Parse error: syntax error, unexpected '[', expecting ',' or ';' in footer.php on line 30

footer.php
<!-- JS -->
<script src="js/jquery.js"></script> <!-- jQuery -->
<script src="js/funcs.js"></script> <!-- jQuery -->
<script src="js/bootstrap.js"></script> <!-- Bootstrap -->
<script src="js/jquery-ui-1.10.2.custom.min.js"></script> <!-- jQuery UI -->
<script src="js/fullcalendar.min.js"></script> <!-- Full Google Calendar - Calendar -->
<script src="js/jquery.rateit.min.js"></script> <!-- RateIt - Star rating -->
<script src="js/jquery.prettyPhoto.js"></script> <!-- prettyPhoto -->

<!-- jQuery Flot -->
<script src="js/excanvas.min.js"></script>
<script src="js/jquery.flot.js"></script>
<script src="js/jquery.flot.resize.js"></script>
<script src="js/jquery.flot.pie.js"></script>
<script src="js/jquery.flot.stack.js"></script>

<script src="js/sparklines.js"></script> <!-- Sparklines -->
<script src="js/jquery.cleditor.min.js"></script> <!-- CLEditor -->
<script src="js/bootstrap-datetimepicker.min.js"></script> <!-- Date picker -->
<script src="js/jquery.toggle.buttons.js"></script> <!-- Bootstrap Toggle -->
<script src="js/filter.js"></script> <!-- Filter for support page -->
<script src="js/custom.js"></script> <!-- Custom codes -->
<script src="js/charts.js"></script> <!-- Custom chart codes -->

<script type="text/javascript">
  $(function() {
    $( "#master2" ).slider({
      value:15,
      min: 0,
      max: <?php if($uinfo['level'] != 5) { echo $users->pack_info($uinfo; ['package'] )['max_attack_time'] } else { echo 1000; } ?>,
      step: 1,
      slide: function( event, ui ) {
        $( "#amount" ).html( ui.value + ' sec' );
      }
    });
    $( "#amount" ).html( $( "#master2" ).slider( "value" ) + ' sec' );
  });
  </script>
  <script>run_live_chat(0);</script>

any ideas ?

A: It might be
echo $users->pack_info($uinfo['package']['max_attack_time']);

instead of
echo $users->pack_info($uinfo; ['package'] )['max_attack_time']

edit
assuming you are trying to do function array dereferencing (which requires php>=5.4) it might be
echo $users->pack_info($uinfo['package'])['max_attack_time'];


text:
Q: How to get position in 3D cordinates using mpu 6050? I am working in a project using MPU6050 with my designed chip to detect object movement.
Project is divided into 2 phases:

*

*Phase I: visualize object orientation (DONE)

*Phase II: visualize object position in 3D cordinates with gyroscope  and accelerator.I follow instructions from this website:http://www.x-io.co.uk/oscillatory-motion-tracking-with-x-imu/. The position must be derived from this through 'double integration'; the accelerometer is first integrated to yield a velocity and then again to yield the position.
void COpenGLControl::Update()
{
  double mX;
  double mY;
  double mZ;
  mX = mXCordinate*9.81;  // mXCordinate-> X accelerator
  mY = mYCordinate*9.81;  // mYCordinate-> Y accelerator
  mZ = mZCordinate*9.81;  // mZCordinate-> Z accelerator

  /* linear velocity*/
  curVelX = preVelX  + mX *sampleRate;
  curVelY = preVelY  + mY*sampleRate;
  curVelZ = preVelZ  + mZ*sampleRate;
  /* linear location*/
  curLoX = preLoX + curVelX*sampleRate;
  curLoY = preLoY + curVelY*sampleRate;
  curLoZ = preLoZ + curVelZ*sampleRate;

  preVelX = curVelX;
  preVelY = curVelY;
  preVelZ = curVelZ;

  preLoX = curLoX;
  preLoY = curLoY;
  preLoZ = curLoZ;
 }

Then curLoX, curLoY, curLoZ is used to visualize 3D object with openGL:
glPushMatrix();
glTranslatef(curLoY,curLoX,curLoZ); //-> object moving visualization
glBegin(GL_QUADS);
........
glPopMatrix();

My purpose is that when moving object up, down, left, right, the 3D object will have the same movement. But object just only move when I rotate my device not linear movement following in http://www.x-io.co.uk/oscillatory-motion-tracking-with-x-imu/.
How can I solve this problems?

A: Accelerometers don't give you the object's position, but the, well it's in their name, acceleration, i.e. the rate of change of velocity.
You have to double integrate over time the values from the accelerometer to determine the position of the object. But there's a catch: Technically doing this is only valid for bodies in free fall. Down here on Earth (and every other massive body in the universe) there's gravity. The mechanical effect of gravity is acceleration. So down here on Earth you can measure a constant acceleration of about 9.81m/s² towards the Earth's center of gravity (you already have a constant of 9.81 up there but you completely misunderstood what it means).
There is no physically correct way to compensate for that. Acceleration is acceleration and in fact we are all moved in spacetime by it (that's why time is progressing a little slower down here on Earth than in outer space) and if you plotted the movement of the IMU in 4D spacetime it'd be the actual proper movement.
What you probably want to see however is the relative movement in the local accelerated frame of reference. If you assume a constant acceleration, that you can take this acceleration vector and subtract it from the measured values. Of course with every rotation of the IMU the acceleration vector will rotate, so you have to integrate the IMU rotation and apply that on the acceleration offset vector before subtracting. Assuming that relative movements are short and have a rather high frequency you may get away with low-pass filtering the accelerometer signal to determine the gravity offset vector.


text:
Q: Azure AD Connect Start-ADSyncSyncCycle causes error We are using Office 365 Business and have our Active Directory synchronised using Azure AD Connect. According to the portal the synchronisation is working ok however when we try to run PowerShell commands on the server running Azure AD Connect we just get error messages.
For example trying to force a synchronisation using Start-ADSyncSyncCycle -PolicyType Initial causes the below error. Similar errors happen when we run Get-ADSyncAutoUpgrade etc.
Does anyone know what the cause would be and how to resolve? It appears the synchronisation is actually working as the portal reports that it happened "X minutes ago" however we have Googled some parts of the large error below without much results.
PS C:\Users\Administrator.DOMAIN> Start-ADSyncSyncCycle -PolicyType Initial
Start-ADSyncSyncCycle :
System.Management.Automation.CmdletInvocationException: System.Exception:
Unexpected exception thrown. Action:
ProvisioningWebServiceAdapter::GetCompanyConfiguration, Exception:  --->
System.Runtime.InteropServices.COMException
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.Initialize(Boolean getObject)
   at System.Management.ManagementBaseObject.get_Properties()
   at System.Management.ManagementBaseObject.GetPropertyValue(String
propertyName)
   at Microsoft.Online.DirSync.Common.PrerequisiteChecks.TryMachineIsDomainCont
rollerCore()
   at Microsoft.Online.Coexistence.ProvisionHelper.IsMachineDomainController()
   at Microsoft.Online.Coexistence.ProvisionHelper.GenerateSyncToken()
   at Microsoft.Online.Coexistence.ProvisionHelper.OpenProxyConnection()
   at Microsoft.Online.Coexistence.ProvisionHelper.InvokeAwsAPI[T](Func`1
awsOperation, String opsLabel)
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.<>c__DisplayClass1.<GetCompanyConfiguration>
b__0()
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName, Action
action)
   --- End of inner exception stack trace ---
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName, Action
action)
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.GetCompanyConfiguration(Boolean
includeLicenseInformation)
   at Microsoft.Azure.ActiveDirectory.Synchronization.AADConfig.get_CloudEnforc
edSyncSchedulerInterval()
   at Microsoft.MetadirectoryServices.Scheduler.SchedulerSettingUtilities.get_C
urrentSchedulerSettings()
   at SchedulerUtils.GetCurrentSchedulerSettings(SchedulerUtils* ,
_ConfigAttrNode* pcanList, UInt32 ccanItems, Char** syncSettingsSerialized,
Char** errorString) ---> System.InvalidOperationException: System.Exception:
Unexpected exception thrown. Action:
ProvisioningWebServiceAdapter::GetCompanyConfiguration, Exception:  --->
System.Runtime.InteropServices.COMException
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.Initialize(Boolean getObject)
   at System.Management.ManagementBaseObject.get_Properties()
   at System.Management.ManagementBaseObject.GetPropertyValue(String
propertyName)
   at Microsoft.Online.DirSync.Common.PrerequisiteChecks.TryMachineIsDomainCont
rollerCore()
   at Microsoft.Online.Coexistence.ProvisionHelper.IsMachineDomainController()
   at Microsoft.Online.Coexistence.ProvisionHelper.GenerateSyncToken()
   at Microsoft.Online.Coexistence.ProvisionHelper.OpenProxyConnection()
   at Microsoft.Online.Coexistence.ProvisionHelper.InvokeAwsAPI[T](Func`1
awsOperation, String opsLabel)
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.<>c__DisplayClass1.<GetCompanyConfiguration>
b__0()
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName, Action
action)
   --- End of inner exception stack trace ---
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName, Action
action)
   at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServiceAda
pter.ProvisioningWebServiceAdapter.GetCompanyConfiguration(Boolean
includeLicenseInformation)
   at Microsoft.Azure.ActiveDirectory.Synchronization.AADConfig.get_CloudEnforc
edSyncSchedulerInterval()
   at Microsoft.MetadirectoryServices.Scheduler.SchedulerSettingUtilities.get_C
urrentSchedulerSettings()
   at SchedulerUtils.GetCurrentSchedulerSettings(SchedulerUtils* ,
_ConfigAttrNode* pcanList, UInt32 ccanItems, Char** syncSettingsSerialized,
Char** errorString)
   at Microsoft.DirectoryServices.MetadirectoryServices.UI.WebServices.MMSWebSe
rvice.GetSchedulerSettings(String& settingsDeserialized, String& errorString)
   at Microsoft.IdentityManagement.PowerShell.Cmdlet.GetADSyncScheduler.Process
Record()
   --- End of inner exception stack trace ---
   at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable
input)
   at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork
(Runspace rs, Boolean performSyncInvoke)
   at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndD
oWork(Runspace rsToUse, Boolean isSync)
   at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](
PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings
settings)
   at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSData
Collection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
   at System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumerable
input, PSDataCollection`1 output, PSInvocationSettings settings)
   at Microsoft.Online.Deployment.PowerShell.LocalPowerShell.Invoke()
   at Microsoft.Online.Deployment.PowerShell.PowerShellAdapter.TypeDependencies
.InvokePowerShell(IPowerShell powerShell)
   at Microsoft.Online.Deployment.PowerShell.PowerShellAdapter.InvokePowerShell
Command(String commandName, InitialSessionState initialSessionState,
IDictionary`2 commandParameters, Boolean isScript)
   at Microsoft.Azure.ActiveDirectory.Synchronization.PowerShellConfigAdapter.S
chedulerPowerShellAdapter.GetCurrentSchedulerSettings()
   at
Microsoft.MetadirectoryServices.Scheduler.Scheduler.StartSyncCycle(String
overridePolicy, Boolean interactiveMode)
   at SchedulerUtils.StartSyncCycle(SchedulerUtils* , Char* policyType, Int32
interactiveMode, Char** errorString)
At line:1 char:1
+ Start-ADSyncSyncCycle -PolicyType Initial
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (Microsoft.Ident...ADSyncSyncCycle:S
   tartADSyncSyncCycle) [Start-ADSyncSyncCycle], InvalidOperationException
    + FullyQualifiedErrorId : System.Management.Automation.CmdletInvocationExc
   eption: System.Exception: Unexpected exception thrown. Action: Provisionin
  gWebServiceAdapter::GetCompanyConfiguration, Exception:  ---> System.Runti
 me.InteropServices.COMException
       at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(I
   nt32 errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.Initialize(Boolean getObject)
   at System.Management.ManagementBaseObject.get_Properties()
       at System.Management.ManagementBaseObject.GetPropertyValue(String prope
   rtyName)
       at Microsoft.Online.DirSync.Common.PrerequisiteChecks.TryMachineIsDomai
   nControllerCore()
       at Microsoft.Online.Coexistence.ProvisionHelper.IsMachineDomainControll
   er()
   at Microsoft.Online.Coexistence.ProvisionHelper.GenerateSyncToken()
   at Microsoft.Online.Coexistence.ProvisionHelper.OpenProxyConnection()
       at Microsoft.Online.Coexistence.ProvisionHelper.InvokeAwsAPI[T](Func`1
   awsOperation, String opsLabel)
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.<>c__DisplayClass1.<GetCompanyConf
  iguration>b__0()
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName
  , Action action)
   --- End of inner exception stack trace ---
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName
  , Action action)
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.GetCompanyConfiguration(Boolean in
  cludeLicenseInformation)
       at Microsoft.Azure.ActiveDirectory.Synchronization.AADConfig.get_CloudE
   nforcedSyncSchedulerInterval()
       at Microsoft.MetadirectoryServices.Scheduler.SchedulerSettingUtilities.
   get_CurrentSchedulerSettings()
       at SchedulerUtils.GetCurrentSchedulerSettings(SchedulerUtils* , _Config
   AttrNode* pcanList, UInt32 ccanItems, Char** syncSettingsSerialized, Char*
  * errorString) ---> System.InvalidOperationException: System.Exception: Un
 expected exception thrown. Action: ProvisioningWebServiceAdapter::GetCompa
nyConfiguration, Exception:  ---> System.Runtime.InteropServices.COMExcept
ion
       at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(I
   nt32 errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.Initialize(Boolean getObject)
   at System.Management.ManagementBaseObject.get_Properties()
       at System.Management.ManagementBaseObject.GetPropertyValue(String prope
   rtyName)
       at Microsoft.Online.DirSync.Common.PrerequisiteChecks.TryMachineIsDomai
   nControllerCore()
       at Microsoft.Online.Coexistence.ProvisionHelper.IsMachineDomainControll
   er()
   at Microsoft.Online.Coexistence.ProvisionHelper.GenerateSyncToken()
   at Microsoft.Online.Coexistence.ProvisionHelper.OpenProxyConnection()
       at Microsoft.Online.Coexistence.ProvisionHelper.InvokeAwsAPI[T](Func`1
   awsOperation, String opsLabel)
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.<>c__DisplayClass1.<GetCompanyConf
  iguration>b__0()
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName
  , Action action)
   --- End of inner exception stack trace ---
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.ExecuteWithRetry(String actionName
  , Action action)
       at Microsoft.Azure.ActiveDirectory.Synchronization.ProvisioningWebServi
   ceAdapter.ProvisioningWebServiceAdapter.GetCompanyConfiguration(Boolean in
  cludeLicenseInformation)
       at Microsoft.Azure.ActiveDirectory.Synchronization.AADConfig.get_CloudE
   nforcedSyncSchedulerInterval()
       at Microsoft.MetadirectoryServices.Scheduler.SchedulerSettingUtilities.
   get_CurrentSchedulerSettings()
       at SchedulerUtils.GetCurrentSchedulerSettings(SchedulerUtils* , _Config
   AttrNode* pcanList, UInt32 ccanItems, Char** syncSettingsSerialized, Char*
  * errorString)
       at Microsoft.DirectoryServices.MetadirectoryServices.UI.WebServices.MMS
   WebService.GetSchedulerSettings(String& settingsDeserialized, String& erro
  rString)
       at Microsoft.IdentityManagement.PowerShell.Cmdlet.GetADSyncScheduler.Pr
   ocessRecord()
   --- End of inner exception stack trace ---
       at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerab
   le input)
       at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndD
   oWork(Runspace rs, Boolean performSyncInvoke)
       at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeede
   dAndDoWork(Runspace rsToUse, Boolean isSync)
       at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOut
   put](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSett
  ings settings)
       at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](P
   SDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings s
  ettings)
       at System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumera
   ble input, PSDataCollection`1 output, PSInvocationSettings settings)
   at Microsoft.Online.Deployment.PowerShell.LocalPowerShell.Invoke()
       at Microsoft.Online.Deployment.PowerShell.PowerShellAdapter.TypeDepende
   ncies.InvokePowerShell(IPowerShell powerShell)
       at Microsoft.Online.Deployment.PowerShell.PowerShellAdapter.InvokePower
   ShellCommand(String commandName, InitialSessionState initialSessionState,
  IDictionary`2 commandParameters, Boolean isScript)
       at Microsoft.Azure.ActiveDirectory.Synchronization.PowerShellConfigAdap
   ter.SchedulerPowerShellAdapter.GetCurrentSchedulerSettings()
       at Microsoft.MetadirectoryServices.Scheduler.Scheduler.StartSyncCycle(S
   tring overridePolicy, Boolean interactiveMode)
       at SchedulerUtils.StartSyncCycle(SchedulerUtils* , Char* policyType, In
   t32 interactiveMode, Char** errorString),Microsoft.IdentityManagement.Powe
  rShell.Cmdlet.StartADSyncSyncCycle

PS C:\Users\Administrator.DOMAIN>


text:
Q: Retrieving data from a form? I am trying to enter data to a website using python, search for it and then extract the address, but not sure where to proceed after this. My code as of now looks like this:
import mechanize

br = mechanize.Browser()
response = br.open("https://www.matsugov.us/myproperty")
for form in br.forms():
     print "Form name:", form.name
     print form

This gives me the formname and the form. The form has multiple fields under drop down and I need to select Tax ID search and fetch the value '218N02W27C003' and then should display the result. Out of this result we just need to take the parcel address and display the output.

A: As you already know the name of form, form name can be selected using
for form in br.forms():
        if form.attrs.get('name') == 'frmSearch':
            br.form = form
            break

To select a option from drop down menu, pass the value of option as a list
br.form['ddlType']=["taxid"]
overall code:
import mechanize

br = mechanize.Browser()
response = br.open("https://www.matsugov.us/myproperty")

for form in br.forms():
    if form.attrs.get('name') == 'frmSearch':
        br.form = form
        break

br.form['ddlType']=["taxid"]
br['txtParm']="abcdef"
req=br.submit().read()
print req

for reference HTML code was something like this.
<select name="ddlType" id="ddlType">
    <option value="owner">Owner Search</option>
    <option value="buyer">Buyer Search</option>
    <option value="address">Address Search</option>
    <option value="subdivision">Subdivision Search</option>
    <option value="subdivision2">Subdivision ID Search</option>
    <option value="taxid">Tax ID Search</option>
    <option value="parcel">Parcel ID Search</option>

</select>


text:
Q: RESTful WCF Service: Sending back user confirmation In my Rest WCF project I am saving data to DB.
My question is when the user sends data to my wcf service,
I need to validate the data and if there is any error
how can I inform it back to the user?
And once data is successfully saved to Database , I need to
send a confirmation to the user saying "Data successfully saved".
How can I do this.
Thanks in advance for your help.

A: Use the HttpStatusCode:
WebOperationContext context = WebOperationContext.Current;
context.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;


text: Q: how to trigger a vpn connection in F5 Access from other app in android I am implementing a company level app, so all the api calling needs the device to connect to the company network first, otherwise it would not work. we have a F5Access app installed on the device with a vpn configuration for connecting to company network. so is there a way to trigger the connection in F5 when my app opens? or if there is other workaround.  thanks very much!!!!!!!!!


text:
Q: FIrefox and Chromium use all RAM and pc freezes I have a problem that I'm trying to solve for a long time. I'm using Ubuntu 16.04 dual boot with Windows 10:
When I'm using several tabs in Firefox or Chromium, I see significant memory usage. One tab takes up to 500MB of RAM and when it gets to 3,7GB Ram usage my pc freeze and only what I can do is hard-reset my pc.
I've tried several things to solve this problem:

*

*Disabled all add-ons in Firefox (Firefox version is 58)

*Update kernel to 4.13

*Disabled "Use hardware acceleration when available" and made more thing to optimize Firefox performance

*Tried to use Firefox in safe mode

*Increased swapping vm.swappiness=10 and swap to 8gb

I have a total 4GB of RAM.
I never had that problem using Windows before only this happens on Ubuntu.
free --human output:
              total        used        free      shared  buff/cache   available
Mem:           3,7G        1,2G        1,2G         50M        1,3G        2,2G
Swap:          8,1G          0B        8,1G

swapon output
Filename            Type        Size     Used   Priority
/swapfile           file        8388604     0         -1
/dev/sda5           partition   102396      0         -2

uname -r output
4.13.0-32-generic

What else can I try to solve the problem?

A: What you're running into is called swapping: You're out of RAM and the kernel swaps unused programs to disk. Setting swappiness to 10 just means the kernel is swapping later rather than earlier (as the default is 60).
As swapping to disk is 1000 times slower than using RAM it just looks like your PC is freezing, but it's not.
You have a few options:

*

*Don't use Chromium: that's a real memory hog; stick to Firefox only!

*Use AdBlock+ (advertisements eat memory too)

*Use NoScript (only allow the scripts you need on the pages you need)

*Use fewer tabs

*set swappiness back to 60 and be patient when swapping
and the easiest solution of all:

*

*Buy more RAM

(also the most expensive)


text:
Q: Logging detailed network activity on Windows Server 2008 One of my clients is experiencing internet delays and outages within their small network. They've verified with their cable company that the issue is not related to any cable company outages. The concern has been raised that either there's too much network activity for their one server to handle, or their website might be getting attacked. Due to this, we'd like to start logging their main server's network activity.
This server has the following responsibilities:

*

*DNS

*Web Server hosting a public site

*Hosts a WCF service that their "admin" desktop application heavily interacts with

*Runs SQL Server 2008, which the WCF server and public website interact with

Goal:
Ideally, I'd like to log network bandwidth used by the processes, as I feel this would give a good handle on what services/software is eating too much bandwidth. I started looking at the native Windows Performance Monitor tool, but I can't figure out how to log the data to a file, and I'm wondering if there's a better [free] logging tool that will give details about how much bandwidth a given process is using.
Questions:

*

*How do I log the activity seen from the Perfomance Monitor Tool (if possible)

*Is there a better logging tool that will log how much bandwidth a given process is using?

A: Presumably "internet (sic) delays and outages" is referring to problems with PCs accessing websites. Assuming that this server is acting as the DNS server for PCs its only material role in Internet access by PCs would be in name resolution.
The web server logs can give you some idea of the bandwidth being consumed by access to the website being hosted by this server computer. You certainly could user Performance Monitor but I think it's the wrong tool for the job in this case. Regarding using Performance Monitor, a Data Collector Set is what you're looking for.
I think you'd be better off examining ingress/egress traffic at the firewall to ascertain if bandwidth there is being exhausted, packets are being dropped by policy, etc. Something like ntop or a Netflow probe is going to give you a breakdown on that traffic. I'd argue that you need visibility into the traffic at the firewall before you start spending time breaking that traffic down at the host level.
I'd suspect a PC with malware, a failing switch, or an overloaded firewall before I'd suspect the web server.

A: This is where you put on your IT sleuthing hat.
First, let's start with:

One of my clients is experiencing internet delays and outages within their small network

While troubleshooting this on the server is fine, you need to get details like:

*

*time of day affected?

*who is affected?

*examples of what is affected?

*how long is "it" affected?

Your comment above mixed with your other details and comments almost sounds more like:

One of my clients is experiencing delays and outages serving up their website

not "internet delays"...whatever that specifically means.
If you want to go the Perfmon route, you can collect logs with a Data Collector set in Perfmon.  But you might be better off deducing what is really affected by first starting with some simple questions and answers from the client.


text:
Q: How to avoid writing multiple operators in If statement I'm interested if it's possible to avoid using multiple operators to make an if statement when you want to check a similar condition for multiple variables. for example :
var good = 0;
var bad = 0;
var neutral = 0;

if(good === 0 && bad === 0 && neutral === 0){
  DO SMTH . . .
}

instead of this if there's something that does it similar to the following :

if(good,bad and neutral === 0){
  do smth . . .
}

So basically, just to avoid multiple operators. thank you!

A: Well... what about this
def total = good + bad + neutral;

if (total === 0) {
   // do something
}

This works only if you are sure values are positive values.


text:
Q: PyMOL: Get sequence of selection I have made a selection of residues like this:
fetch 1bsx
select interface_1bsx, byres((1bs and chain A) within 5A of (1bsx and chain X))

How do I get the sequence of interface_1bsx?

A: Use the iterate command (pymol wiki):
iterate interface_1bsx, resn

Or if you prefer to have it in a python list:
residues = []
iterate interface_1bsx, residues.append(resn)
print(residues)


text:
Q: Bash reg-exp substitution Is there a way to run a regexp-string replace on the current line in the bash?
I find myself rather often in the situation, where I have typed a long commandline and then realize, that I would like to change a word somewhere in the line.
My current approach is to finish the line, press Ctrl+A (to get to the start of the line), insert a # (to comment out the line), press enter and then use the ^oldword^newword syntax (^oldword^newword executes the previous command after substituting oldword by newword).
But there has to be a better (faster) way to achieve this. (The mouse is not possible, since I am in an ssh-sessions most of the time).
Probably there is some emacs-like key-command for this, that I don't know about.
Edit: I have tried using vi-mode. Something strange happened. Although I am a loving vim-user, I had serious trouble using my beloved bash. All those finger-movements, that have been burned into my subconscious suddenly stopped working. I quickly returned to emacs-mode and considered, giving emacs a try as my favorite editor (although I guess, the same thing might happen again).

A: G'day,
What about using vi mode instead? Just enter set -o vi
Then you can go to the word you want to change and just do a cw or cW depending on what's in the word?
Oops, forgot to add you enter a ESC k to o to the previous line in the command history.
What do you  normally use for an editor?
cheers,
Rob
Edit: What I forgot to say in my original reply was that you need to think of the vi command line in bash using the commands you enter when you are in "ex" mode in vi, i.e. after you've entered the colon.
Worst thing is that you need to move around through your command history using the ancient vi commands of h (to the left) and l (to the right). You can use w (or W) to bounce across words though.
Once you get used to it though, you have all sorts of commands available, e.g. entering ESC / my_command will look back through you r history, most recent first, to find the first occurrance of the command line containing the text my_command. Once it has found that, you can then use n to find the next occurrance, etc. And N to reverse the direction of the search.
I'd go have a read of the man page for bash to see what's available under vi mode. Once you get over the fact that up-arrow and down-arrow are replaced by ESC k, and then j, you'll see that vi mode offers more than emacs mode for command line editing in bash.
IMHO natchurly! (-:
Emacs? Eighty megs and constantly swapping!
cheers,
Rob

A: in ksh, in vi mode, if you hit 'v' while in command mode it will spawn a full vi session on the contents of your current command line.  You can then edit using the full range of vi commands (global search and replace in your case).  When :wq from vi, the edited command is executed.  I'm sure something similar exists for bash.  Since bash tends to extend its predecessors, there's probably something similar.

A: Unfortunately, no, there's not really a better way.  If you're just tired of making the keystrokes, you can use macros to trim them down.  Add the following to your ~/.inputrc:
"\C-x6": "\C-a#\C-m^"
"\C-x7": "\C-m\C-P\C-a\C-d\C-m"

Now, in a new bash instance (or after reloading .inputrc in your current shell by pressing C-x C-r), you can do the following:

*

*Type a bogus command (e.g., ls abcxyz).

*Press Ctrl-x, then 6.  The macro inserts a # at the beginning of the line, executes the commented line, and types your first ^.

*Type your correction (e.g., xyz^def).

*Press Ctrl-x, then 7.  The macro completes your substitution, then goes up to the previous (commented) line, removes the comment character, and executes it again.

It's not exactly elegant, but I think it's the best you're going to get with readline.


text:
Q: Send specific packets with HttpWebRequest Hey. Is it possible to send a packet from a C# application without using sockets? I'd like to use WebClient or HttpWebRequest in order to send specifically formatted packets to a server. Examples I've seen tend to use UDP client. Thanks

A: It depends on what you mean by "Specifically Formatted". HttpWebRequest is a .Net wrapper around the HTTP protocol which is not UDP in nature, so you can not customize the packets it sends other than modifying object data like headers, etc.

A: You should look at the IPEndPoint class, this is designed for sending data to an network endpoint by IP and port address.  Here is a simple example, see the link for more details and a longer example with error checking.
byte[] data = new byte[1024];
string payload = "<Enter Your Payload Here>";
IPEndPoint ep = new IPEndPoint("127.0.0.1", 1234); //IP + Port

Socket remoteServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
data = Encoding.ASCII.GetBytes(payload);
remoteServer.SendTo(data, data.Length, SocketFlags.None, ep);


text:
Q: Python: How to combine two dictionaries in python such that the resultant contains key as the value from the first I have two dictionaries as follows:
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}

The resultant dictionary should be such that it takes the key as the value of first dictionary.
 Result_dictionary= {'apple':50, 'banana':30}

A: You can use a dictionary comprehension using the values of the first dictionary as the keys of the resulting dictionary. This assumes all keys of the first are present in the second dict
{v: dict2[k] for k, v in dict1.items()}

you can also add a check for the presence of the keys in the second dictionary
{v: dictionary_2[k] for k, v in dictionary_1.items() if k in dictionary_2}

A: Loop through one of the dictionaries and check if the value for a key in mydictionary_1 exists in mydictionary_2.
You can achieve this using python's dictionary comprehension -
Result_dictionary = { v:mydictionary_2[k] for k,v in mydictionary_1.iteritems() if k in mydictionary_2.keys()}

To see how this list comprehension is working you can even use general for loop to loop through each key, value pair in mydictionary_1
for key,value in mydictionary_1.iteritems():
  if key in mydictionary_2.keys():
    Result_dictionary[value]=mydictionary_2[key]

A: Dictionary comprehension is an ideal solution for this one, as previously mentioned. Here is a for loop example:
def combine_dictionaries(dict1, dict2):
    result_dictionary = {}
    for key in dict1.keys():
        result_dictionary[dict1[key]] = dict2[key]
    return result_dictionary

combine_dictionaries({1:'apple', 2:'banana'}, {1:50, 2:30})

>>>{'apple': 50, 'banana': 30}

This assumes all values of the dict1 are present in the dict2.

A: def dict_cross_match(dict1, dict2):
    new_dict = {}
    for item in dict1.keys():
        if item in dict2.keys():
            new_dict[dict1[item]] = dict2[item]
    return new_dict

mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
print(dict_cross_match(mydictionary_1, mydictionary_2))


text:
Q: Output PHP Mysql Date format to ISO 8601 with "T" sign only I would like to get a datetime formatted a specific way. Can I do this in MySQL or do I need to do it in PHP?
This is the output from MYSQL :
2016-01-30 23:21:46

I need it formatted in this (similar but not exactly the same) fashion:
2016-01-30T23:21:46

Is there a PHP function to handle this correctly or is it possible to change it from MYSQL?

A: You could use insert():
select insert(<whatever>, 11, 1, 'T')


text:
Q: How to delete a non-empty folder in Batch script? I have tried numerous methods of doing this including Remove-Item, rmdir, del, and rd. I have seen similar questions, but none of the answers have helped me. To be clear, I am not asking for a specific "book, tool, or software library"; I just want a Batchfile command to recursively delete a folder. I'm sorry if I'm doing something wrong; I'm pretty new here.

A: For the previous answer, I checked the current Microsoft documentation about commands it has, and it does NOT say clearly that the del command will delete only files.
The command you need to recursively delete a folder, and all files OR folders it contains is:
rmdir [name of the folder] /s /q

Please note the "/s" and "/q" arguments, which have the same meaning as for the del command, but they come AFTER the name of the folder! This is what the command documentation shows, as you may read here.
But there are more possible reasons for the recursive directory deletion failing! If you try to delete a directory that has system files or hidden files, the rmdir command will fail. To solve this problem, you need to do more work. To quote the documentation pointed above:

You can't delete a directory that contains files, including hidden or system files. If you attempt to do so, the following message appears:
The directory is not empty
Use the dir /a command to list all files (including hidden and system files). Then use the attrib command with -h to remove hidden file attributes, -s to remove system file attributes, or -h -s to remove both hidden and system file attributes. After the hidden and file attributes have been removed, you can delete the files.

A: To delete a non empty folder, you need something called recursion. What we usually read is that we want to "delete a folder recursively", which means to delete a folder and all its contents, including other folder, with their respective contents and folders, and so on.
The command del does it for you. Have you read its help or its documentation? To see that, the command you use in the cmd program is:
del /?

But this does not directly answer your question. What you need to put in your batch file is:
del /s /q [non empty folder name]

*

*"/s" is to delete it recursively

*"/q" is to delete it without asking for confirmation of each file or folder being deleted. You may want to remove this item, if you want to choose what will be deleted inside the folder.

*You must not write the square brackets I wrote in the command example. Just the folder name, as it is.


text:
Q: Not able to install composer package I'm trying to install my first composer package which I have built for learning.
For that, I have successfully setup Github repository and packagist account:
https://github.com/xparthx/Composer-package-demo
https://packagist.org/packages/xparthxvorax/demo
The issue is when I'm trying to install it using composer require xparthxvorax/demo, it gives me following error:

[UnexpectedValueException]
   Error while installing xparthxvorax/demo, composer-plugin packages should have a class defined in their extra key to be usable.

I think the issue is with the package type. As per this doc, the default package type should be library:
https://getcomposer.org/doc/04-schema.md#type

A: Create a new tag, because with composer require composer will try to install latest tag, which in your case is the one with "composer-plugin" type: https://github.com/xparthx/Composer-package-demo/blob/v1/composer.json


text:
Q: Android accelerometer difficulties I'm a beginner in Android game Development, and I developing a small Game.
I am facing some difficulties with the Motion Sensor: Accelerometer.
this game is in Landscape mode.
I want if my phone tilts in right, my character also goes right. ( same thing for left )
And when I stop tilting Character in the game should stop moving.
But i don't understand really good the operation of the accelerometer,
here is my code:
 @Override
public void onSensorChanged(SensorEvent event) {
     synchronized (this) {
        long penchement = (long) (event.values[1]- 0.5);
          if(penchement>0){
              if(penchement>lastUpdate)
                  lastUpdate=penchement;
              if(penchement>0.2){
                  booldroite=true; // boolean for going right
                  boolgauche=false; // boolean for going left
              }
              if(lastUpdate-penchement<0.2)
                  booldroite=false;
          }
          else{
              if(penchement<lastUpdate)
                  lastUpdate=penchement;
              if(penchement<-0.2){
                  boolgauche=true;
                  booldroite=false;
              }
              if(lastUpdate+penchement>-0.2)
                  boolgauche=false;
          }

}

So my code works (a bit), but my character's moves aren't smooth at all. Sometimes my phone tilts but my Characters doesn't move...
Thank you very much in advance if you can help me.

A: Sensor readings are noisy by nature, that's the reason for the flickering movement of your character.
You will need to implement some kind of low pass filter after the readings. There's a basic low pass filter example in SensorEvent.
 public void onSensorChanged(SensorEvent event) {

      // alpha is calculated as t / (t + dT)
      // with t, the low-pass filter's time-constant
      // and dT, the event delivery rate

      final float alpha = 0.8;

      gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
      gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
      gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

      linear_acceleration[0] = event.values[0] - gravity[0];
      linear_acceleration[1] = event.values[1] - gravity[1];
      linear_acceleration[2] = event.values[2] - gravity[2];
 }

You might want to use the values in gravity[] to find out the 'tilt' of the phone. Also, play around with the value of final float alpha: Values near 1.0 will improve the smoothness, while smaller values near 0.0 will obtain noisier readings, but have a faster response.
Bonne chance!


text:
Q: WordPress add_rewrite_rule 404 error I am adding rewrite_rules for my custom project.
I was able to make them work till some extent, but have some difficulties.
Here's what i have tried out so far
public function add_query_vars($vars) {
   $vars[] = 'gallery';
   $vars[] = 'project';
   $vars[] = 'palbum';
   return $vars;
}
public function add_endpoint() {
   add_rewrite_rule('^gallery/([^/]*)/([^/]*)?','index.php?gallery=true&project=$matches[1]&palbum=$matches[2]','top');
}

Here project is parent and palbum are all its child.
It seems to work properly at mysite.com/gallery/my-project-name/my-album-name
(These page is to show single album)
But it gives me 404 error at mysite.com/gallery/my-project-name
(These page is to show all albums which the project is parent of)
Any clue why?

A: Based on your rewrite rule, both the section used for project and palbum are required in order for the rewrite rule to apply.  If you modify the rule just slightly, it will match what you are looking for:
public function add_endpoint() {
    /**
     *
     * Matches:
     * http://example.com/gallery/my-project-name/my-album-name/
     * http://example.com/gallery/my-project-name/my-album-name
     * http://example.com/gallery/my-project-name/
     * http://example.com/gallery/my-project-name
     */
    add_rewrite_rule('^gallery/([^/]+)/?(.*?)/?$','index.php?gallery=true&project=$matches[1]&palbum=$matches[2]','top');
}

Created a test to run against any other iterations you'd like to check - https://www.regex101.com/r/f54odP/1


text:
Q: How to drop SQL UNIQUE constraint without knowing its name? I am using MYSQL database .
I have created a Table as  shown below
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)

Now i am trying to remove the Unique Constarint on the Persons table
I have tried as


text:
Q: iMessage (iOS 10) doesn't index messages properly Here's the situation. I backed up an old iPhone 5S to iTunes on Windows via a  USB cable. I bought a new iPhone SE and restored the backup onto it. Everything works fine...except...no past messages show in Messages. The view, that usually shows them in reverse chronological order, is empty. Using the search widget doesn't find anything either. However, after creating a new message, that goes to one of the existing contacts, suddenly all the past messages appear in the chain!
Obviously the messages are on the device, but not indexed properly, probably a result of the backup and restore. Is there some way to re-index them so they'll show in the chronological view and be searchable via the search widget? Would another backup and restore help?
Seems to be related to Weeks after updating to iOS 10.0.1, all but ~5 most recent messages disappeared, and messages would no longer organize by time and Old iMessages and text messages have all disappeared after iOS 10 update? neither of which got an answer.

A: According to Apple's engineering department, backups only store the past 200 messages in the search database. The rest are stored for regular viewing, just not in the database.
"What the customer is experiencing is actually considered expected behavior.  With the release of iOS 10, customers are now only able to search the last 200 messages with Spotlight or the in-app search. This would include the last 200 sent and received messages.
The 200 searchable messages limit is only after restoring from a backup prior to iOS 10.  This is why devices that had the same Messages database and were not restored from a backup when they upgraded to iOS 10 can still search prior to the 200 limit.
If the customer would like to see this function in a different manner going forward, please encourage the customer to submit feedback at apple.com/feedback. "

A: I wonder if we could use Spotlight indexing to force the Messages app to fix itself.

*

*Settings app -> General -> Spotlight Search. Turn off Messages.

*Reboot the iPhone.

*(Don't open Messages yet.) Settings app -> General -> Spotlight Search. Turn back on Messages.

*Wait one minute. Open Messages.

It's really a long-shot, but maybe having Spotlight read the database will force whatever goof is going on to un-goof. It's at least something to try while we continue to think.


text:
Q: OneSignal push notification opens MainActivity, instead of opening the Launch URL I have created a webview app on android. I use onesignal to send notification to users. But when a user clicks on notification - MainActivity class is opened, instead of opening the URL provided in the Launch URL field while sending notification.
package app.example.com;

import android.app.Application;
import android.util.Log;

import com.onesignal.OneSignal;

public class ApplicationClass extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        // OneSignal Initialization
        OneSignal.startInit(this)
                .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .unsubscribeWhenNotificationsAreDisabled(true)
                .init();

        Log.d("OneSignalTag", "Before OneSignal init");

        OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
        OneSignal.startInit(this).init();

        Log.d("OneSignalTag", "After OneSignal init");
    }

}


text:
Q: Systemd immidiately running execstop At work, we are running Nagios for system monitoring. I have written a python script to store data from Nagios in a postgresql database. This is running on centos 7.6. Using a systemd service file, I have no problem starting the script and having it restarted if it for some reason should go down. I can stop the script in a controlled way by writing a file in a certain location. This works fine to stop it manually, but it does not work if I try to use it through systemd.
My service file is like:
[Unit]
Description=Nagiosdata to postgresql
After=postgresql-12.service

[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/local/nagios/libexec/importdata
StandardInput=null
User=nagios
Restart=on-failure
RestartSec=30s
TimeoutStopSec= 180
ExecStop=/usr/bin/touch <file to stop the process>

[Install]
WantedBy=multi-user.target

If I add in TimeoutStopSec and ExecStop as shown here, systemd will write out the control file immideately after starting the process so the process will stop again. I have tried to set Type to forking (which as far as I do understand is not correct since my script runs in the foreground if run interactively) but with the same result.
I notice if I do systemctl status dataimport, if I do not have the ExecStop line, status is Active (running). With the ExecStop, I have status Active (exited)
Do I need to do something differently or will this just not work on systemd 219 on centos 7.6?


text:
Q: How to Get The Oldest And The Newest Record of Different Columns By Person - SQL Server? I need to get the oldest previous balance and the newest actual balance of each person in a table of transactions.
For example I got this:
+-----------------+---------------+-----------------+---------------+
| dateTransaction | idPerson      | previousBalance | actualBalance |
+-----------------+---------------+-----------------+---------------+
| 01-11-2017      |      1        |       0         |    1000       |
| 02-11-2017      |      2        |       500       |    2000       |
| 03-11-2017      |      1        |       1000      |    1500       |
| 04-11-2017      |      2        |       2000      |    2500       |
+-----------------+---------------+-----------------+---------------+

So I need to get something like this:
+---------------+-----------------+---------------+
| idPerson      | previousBalance | actualBalance |
+---------------+-----------------+---------------+
|      1        |       0         |    1500       |
|      2        |       500       |    2500       |
+---------------+-----------------+---------------+

This is the script to create the table:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Transaction]
(
    [numberTransaction] [int] NOT NULL,
    [dateTransaction] [datetime] NOT NULL,
    [idPerson] [decimal](20, 0) NOT NULL,
    [transactionAmount] [decimal](18, 3) NOT NULL,
    [previousBalance] [decimal](18, 3) NOT NULL,
    [actualBalance] [decimal](18, 3) NOT NULL,

    CONSTRAINT [PK_Transaction]
        PRIMARY KEY CLUSTERED ([numberTransaction] ASC)
) ON [PRIMARY]
GO

Thanks in advance...

A: Use row_number() over() as follows:
SELECT *
FROM (
    SELECT t.*
    , row_number() over(partition by idPerson order by dateTransaction ASC) as is_oldest
    , row_number() over(partition by idPerson order by dateTransaction DESC) as is_newest
    FROM Transaction t
     ) d
WHERE ( is_oldest = 1 OR is_newest = 1 )
ORDER BY idPerson, dateTransaction ASC

In the over clause the partition by means numbers assigned by row_number() will be PER idPerson. Then the order by sets 1 at the oldest date (when sorted asending) or 1 at the newest (when sorted descending).


text:
Q: How do I query Ubuntu One account information? For what I promise are un-nefarious reasons, I'd like to programmatically fetch the Ubuntu One account details for the current user of an application (eg name, email, free space). Is there way to achieve this?

A: Yes. Ubuntu One provides an OAuth-secured Web API for account details; the OAth credentials of the local user are accessible via the freedesktop.org secrets keyring service. Of course, you can't read these credentials willy-nilly, as the user needs to password-unlock them.
Fortunately, you do not need to navigate the maze of technologies on your own (as I did), but can instead can use a handy tool Ubuntu One provides:
u1oauthrequest https://one.ubuntu.com/api/account/

If the current user doesn't have a U1 account, this will raise a CredentialsNotFound error. Otherwise it will return a server response in the form of a JSON string. Check the 'status' value to make sure the authentication went through ('200' indicates success). On success, the JSON will have the values:

username, openid, last_name, features, couchdb_root, nickname, id, subscription, first_name, couchdb, total_storage, current_plan, email, detailed_plans

Wield your API powers responsibly.


text:
Q: C++11 source code generation Is there some sort of library for C++ which contains classes which represents C++ source code?
It should of course be able to output the source code to a stream.
I'm looking for something which supports most C++11 features and is also capable of generating templated constructions.
When I google for this, I'm not getting the results I want. I'm sure though, that there is something available. Maybe I'm just using the wrong terms.

A: Check out the Clang compiler which uses a library-based architecture  to support implementing IDEs and other tools that need to process the AST. Clang fully supports all C++11 features (and some C++1y features)
More information can be found in the Clang documentation. Or in this blog which describes basic source to source transformations using clang::Rewriter.

A: This is still in a very experimental phase, but in our lab we are developing a tool (Clava), which is based on Clang and uses a Javascript-like language to query and transform a given C/C++ code. It will be made open-source by the end of August 2017.
For instance, the current default example in the demo website reads all classes and structures in the C/C++ code and creates a C++/H pair with HDF5 wrappers for those classes (however, that code generation is a mix between AST and String literals).
(Clava - Online Demo)


text:
Q: C++ std::vector push_back with strange behaviour First of all, I'm relatively new to C and C++, I'm way more used to C#.
Basically, I have a vector an object called CTe, this object has several variables and a vector of another object called NFe, all the information that I want to fill the CTes objects are stored in a 2D vector of strings, so the goal of this loop is to iterate through all the lines of the vector, being one CTe per line, and this CTe may have one or multiples NFes attached to it.
    /*The declaration of the vectors, just to help visualize the structure
    vector < string > dirlist;
    vector < vector < string > > listElement;
    vector < CTe > ctes;*/

    //This will iterate through the 2D vector
    for (int i = 1; i < listElement.size(); i++)
    {
        //Temporally CTe object to store information
        CTe temp;

        string targetCNTR = listElement[i][6];
        int countNFE = 0;
        bool haveFoundReference = false;

        // This will iterate reading all the xmls I have in a folder
        for (int j = 2; j < dirlist.size(); j++)
        {
            string extraInfoNFE = ReadXML(dirlist[j], "infAdic", "infCpl");

            //Check if a valid xml was found.
            if (extraInfoNFE.find(targetCNTR) != string::npos)
            {
                haveFoundReference = true;

                string sColeta = "000"+listElement[i][3];
                stringstream tipoNumber (listElement[i][4]);

                //Fill the variables of the temp object
                temp.cntr = targetCNTR.c_str();
                temp.booking = listElement[i][0].c_str();
                temp.motorista = listElement[i][1].c_str();
                temp.placas = listElement[i][2].c_str();
                temp.coleta = sColeta.c_str();
                temp.seqEndereco = listElement[i][5].c_str();
                tipoNumber >> temp.tipoCTE;

                listElement[i][8+countNFE] = ReadXML(dirlist[j], "ide", "nNF");

                //Create a temporally object to store the NFe information
                NFe tempNFe;

                //Fill the tempNFe object
                stringstream nfeNumber (listElement[i][8+countNFE]);
                nfeNumber >> tempNFe.numeroNFE;

                string sXML = dirlist[j].substr(5, 43);
                tempNFe.codigoXML = sXML.c_str();

                string sDest = ReadXML(dirlist[j], "dest", "xNome");
                tempNFe.destinatario = sDest.c_str();

                stringstream cfopNumber (ReadXML(dirlist[j], "det", "prod", "CFOP"));
                cfopNumber >> tempNFe.cfop;

                stringstream qtdeNumber (ReadXML(dirlist[j], "transp", "vol", "qVol"));
                qtdeNumber >> tempNFe.qtde;

                stringstream valorNumber (ReadXML(dirlist[j], "total", "ICMSTot", "vNF"));
                valorNumber >> tempNFe.valor;

                stringstream pesoNumber (ReadXML(dirlist[j], "transp", "vol", "pesoB"));
                pesoNumber >> tempNFe.pesoBruto;

                //push_back the tempNFe into the temp object
                //This part is working perfectly
                temp.notas.push_back(tempNFe);
                countNFE++;
            }
        }

        //Check if a valid xml was found, if so push_back
        //The temp object into the ctes object
        //HERE LIES THE PROBLEM
        if (haveFoundReference)
        {
            cout<<temp.cntr<<" - ";
            ctes.push_back(temp);
        }
        else
        {
            cout << "Não foi possível localizar a nota do CNTR " <<targetCNTR;
        }
    }

The problem is, that all the CTe objects in the ctes vector are the same, the only thing that is working is the NFe vector inside the CTe.
Here is the CTe and the NFe classes:
NFE
class NFe
{
    public:
        NFe();
        const char* codigoXML;
        const char* destinatario;
        int numeroNFE;
        int cfop;
        int qtde;
        float valor;
        float pesoBruto;
        ~NFe();
};

CTE
#include <nfe.h>
#include <vector>

class CTe
{
    public:
        CTe();
        const char* motorista;
        const char* placas;
        const char* booking;
        const char* cntr;
        const char* seqEndereco;
        const char* coleta;
        int espelho;
        int tipoCTE;
        std::vector < NFe > notas;
        virtual ~CTe();
};

A: As I mentioned in the comments earlier, the char * returned by c_str() is valid only until the corresponding string object is destroyed or modified. In your case,
string targetCNTR = listElement[i][6];

creates a copy of the string inside the vector, and this copy is destroyed right after exiting the for loop. So
temp.cntr = targetCNTR.c_str();

is invalid as soon as the targetCNTR gets destroyed after exiting the scope.
If you cannot modify the class definition to change const char * to std::string and if the vector listElement remains valid throughout the lifetime of your program, you can fix your code by obtaining the reference to the actual string like below
string &targetCNTR = listElement[i][6];

This way, the returned c_str() will be valid as long as listElement vector is not destroyed or modified. In case istElement is modified/destroyed (you haven't provided the code populating listElement so it is not obvious), you can also create the copy of char * like this
/* allocate a new char * on heap */
char *cntr = new char [strlen(targetCNTR.c_str()) + 1];
/* copy the c string */
strcpy(cntr, targetCNTR.c_str());
/* move the char * to desired object */
temp.cntr = cntr;

You can do the same for all char * variables. If you use this approach, remember to free the char * in the class destructor. For example,
class CTe
{
    public:
        CTe();
        const char* motorista;
        const char* placas;
        const char* booking;
        const char* cntr;
        const char* seqEndereco;
        const char* coleta;
        int espelho;
        int tipoCTE;
        std::vector < NFe > notas;
        virtual ~CTe() {
            /* free char * */
            delete [] motorista;
            delete [] placas;
            delete [] booking;
            delete [] cntr;
            delete [] seqEndereco;
            delete [] coleta;
        }

};


text:
Q: Word VBA - CompareDocuments - How to check Revisions object's contents After comparing word documents with Application.CompareDocuments method, I need check all revisions found to keep only those 'real' text changes.
Thanks

A: So the soluition is to perform some check on the 'Text' property of each item belongs the Revision object.
The code is something like :
i = 1
While i <= ActiveDocument.Revisions.Count
    If ActiveDocument.Revisions.Item(i).Range.Text is text ...
    i = i + 1
...
Wend


text:
Q: How to generate short, reasonably non-sequential keys in Scala (unique web links) I'm sure someone has created a great, terse, and effective Scala function for generating short non-sequential keys suitable for use in web links. I'd like the keys to be hard to guess sequentially... I don't want someone just "browsing" through the links – but, hitting on one randomly is not a big deal.
There are a few related posts (this one and this other one), but they don't really address the problem (and they are in the wrong languages). The idea is to make seemingly random, reasonably short URL keys. Something like Vimeo or Youtube short links would be fine, but not too short (http://watever.com/abc is too easy to guess/browse) and not too long (http://watever.com/de305d54-75b4-431b-adb2-eb6b9e546014 is just too long). A happy medium would be most desirable: http://watever.com/de8f43a3.
They keys will ultimately be stored in a relational database, so I have the option of checking for uniqueness, and retrying until I "get lucky."
Any ideas? Or hopefully a slick little algorithm?

A: Ended up with the following, which seems to work pretty well. It may generate duplicates, so I have to double check against pre-existing keys – but, I think the odds of getting a duplicate are low so it will be rare (and easy enough to retry):
def shortCode(id: Int): String = {
    val size = (log10(id) + 4).toInt
    Random.alphanumeric.take(Random.nextInt(size) + 1).mkString
}

In this case, I'm using the primary key as the id, so a small key (1) will get a 4-digit serial key. A larger key (1,000,000) will get an 11 digit key. Using a larger key size and an alphanumeric base will make it pretty hard to "browse" the URLs.


text:
Q: Can Oracle Label Security be configured with an alternative LDAP server? Oracle mentions the ability to connect to their LDAP server - the Oracle Internet Directory http://download.oracle.com/docs/cd/B19306_01/network.102/b14267/olsoid.htm. Can Oracle Label Security be configured with an alternative LDAP server such as Active Directory?

A: Not that easy. Oracle is another big gorilla in the room: they don't publish ldap schemas used in many oracle components. Some times they create hooks for their OID within Oracle software, the way MS does with their AD.
if you know the schemas used in Oracle OID and the seed data they use, you can load those schemas and the data in whatever ldap server you have, and connect it.


text:
Q: Spring NotBlank annotation with errorCode parameter I have the following form:
public class Form {

    @NotBlank(errorCode = "my.custom.error")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

My goal is to reject value with specified error code.
But unfortunately, I cannot do it.
The field rejected with my message wrapped by Form name.
Will be good to know in which way error code for the similar annotation can be specified?


text:
Q: React native: How to do a "shared element/zoom" transition using navigator? Is it possible to make a "shared element/zoom" transition like this in react native using navigator?
Especially useful for something like image galleries/modals.
https://github.com/codepath/android_guides/wiki/Shared-Element-Activity-Transition

A: "Currently React doesn't support reusing a native view in different parts of the component hierarchy, which makes it difficult to implement shared element transitions in pure JS."
Checkout the below link:
https://github.com/brentvatne/hard-react-native-problems/issues/11
Additionally, It(Shared Element) may be roll-out in next version as part of Navigator.
Check out the following thread:
https://twitter.com/intelligibabble/status/764162422831652865
Edit: airbnb launched native navigation with shared element transition to try. It not official yet. but can try out..
http://airbnb.io/native-navigation/docs/guides/shared-element-transitions.html
Update: It is worth to checkout https://wix.github.io/react-native-navigation for shared element implementation.


text:
Q: Django: Get other field's value from an aggregation query es = Employee.objects.filter(a few filters).aggregate(Max('Age'))

That query is going to give me the oldest employee, so I also want to know some other information associated with that row, for example, the id.
How can I accomplish that? Thanks.

A: You do not need aggregate you only have to order by descending Ages your query set
 Employee.objects.filter(a few filters).order_by(['-Age'])[0]

Will give you the oldest
Or if you have several old item
 age = None
 for x in Employee.objects.filter(a few filters).order_by(['-Age']):
    if age and age != x.Age:
       break
    age = x.Age

A: Use annotate() instead of aggregate().


text:
Q: How to utilize sizeof() to return the size of malloc buffer allocation If I allocate:
int *d =  malloc(5* sizeof(int));
printf("%d", (int) sizeof(d));

I get a value of 8 instead 5. I know sizeof() is not meant to return the length in this case but I wonder if there is a workaround for that since I want to avoid tracking the size manually ( by parameter passing).

A: sizeof(d) gives the size of the pointer, d.    A value of 8 is consistent with a 64-bit host system.
This is distinct from the allocated size of whatever d points at.
Since malloc() allocates at run time (the length to be allocated is specified when the program is run) and sizeof is a compile-time operator, it is not possible to use sizeof to obtain the length.
You need to track the size manually, in a separate variable.
  size_t allocated_size = 5*sizeof int;
  int *d = malloc(allocated_size);
  printf("%d", (int) allocated_size);

It is more common to track the number of elements (i.e. take account of the type of d).
  size_t allocated_ints = 5;
  int *d = malloc(allocated_ints * sizeof (*d));
  printf("%d", (int) allocated_ints);   // prints number of `int`

size_t is defined in <stdlib.h> (among others).   In C99 and later, the format specifier for printing a size_t is %zu (rather than converting to int and using %d as you have done).

A: When the sizeof operator is applied to a pointer, it gives the size of the pointer itself.  It does not give the size of the array it may be pointing to.
When dynamically allocating an array, you need to manually keep track of how many elements you've allocated.

A: sizeof cannot provide the information you want. You have to keep track of it yourself.

A: C does not track the size of an allocated buffer for you.  You must track the size manually.

A: You should first decide how much memory you're going to allocate, then keep track of it in a constant or a variable.
const size_t sz = 5 * sizeof(int);


text:
Q: Mysql find a value between Script outputs random value (winning ticket) from 0 to 5000 (in this case). Lets take 3001. I need a query to take a row where id = 4, because it has the winning ticket. How can I do it?
More info:
id 1 has tickets from 0 to 1000
id 2 has tickets from 1000 to 2000
id 3 has tickets from 2000 to 3000
id 4 has tickets from 3000 to 3500 <----- The winning ticket
id 5 has tickets from 3500 to 5000

Mysql table:
+-----------------------+
| id | Userid  | Ticket |
+-----------------------+
| 1  | 1234567 | 1000   | // 0 to 1000
| 2  | 1234567 | 1000   | // 1000 to 2000
| 3  | 1234567 | 1000   | // 2000 to 3000
| 4  | 9876543 | 500    | // 3000 to 3500
| 5  | 1234567 | 1500   | // 3500 to 5000
+-----------------------+

A: Does the following query work for you :
set @winningticket=3001;
set @cstart=0;
SELECT id, Userid, (lastticket-tickets+1) firstticket, lastticket
FROM
(
SELECT id, Userid, Ticket as tickets, (@cstart := @cstart+Ticket) lastticket
FROM mytable
order by id) a
having @winningticket between firstticket and lastticket;

I have made the assumption that id=1 has tickets from 1-1000, id=2 has tickets from 1001 to 2000 - rather than the values you give - otherwise ticket 1000 is owned by id=1 AND id=2, 2000 by id=2 AND id=3 etc - if that is incorrect remove the +1 from the calculation for firstticket & the values will match yours.
The inner subquery creates a cumulative total for the final ticket number owned by that id using a user variable.
The outer query calculates the start ticket number - note this cannot be reliably done in the inner query as the first & last ticket numbers both rely on the same user variable & order of evaluation of columns is not guaranteed & use of the same user variable in the select list is advised against if it is modified in any way.
The outer query uses a having clause to select the winning ticket between first & last ticket number.


text:
Q: Selenium does not work when we get a upgrade from firefox I am working on Automation tool Behat/Mink . After upgrading Firefox version to 25 , i am seeing this error .
     Curl error thrown for http POST to http://localhost:4444/wd/hub/session/execute with params: {"script":"return document.getElementById('user') !== null;","args":[]}
  Failed to connect to 127.0.0.1: Can't assign requested address

I am using selenium webdriver version 2.37.0.jar as the server.

A: Support for Firefox 25 has been added in version 2.38. Current version is 2.39 which supports Firefox 26.
It is a good practice to check for the new selenium version every time Firefox upgrades. Updating the server should work.
Official download page.

A: run this command before running your tests
    java -jar selenium-server-standalone-*

this will help you to resolve your problem
make sure your selenium latest version should be on same folder


text:
Q: Move UITextField in UIView that has constraints I am making an app that the use can input their car info into. I need the UITextFields to move up so they are not covered by the keyboard. I did this with this code.
func textFieldDidBeginEditing(_ textField: UITextField)
{
    if make==textField
    {
        self.infoContainer.frame = self.infoContainer.frame.offsetBy(dx: 0, dy:-50)
    }
    if model==textField
    {
        self.infoContainer.frame = self.infoContainer.frame.offsetBy(dx: 0, dy:-75)
    }
    if color==textField
    {
        self.infoContainer.frame = self.infoContainer.frame.offsetBy(dx: 0, dy:-100)
    }
}

Which worked great until I added constraints to to the UIView *infoContainer. then it would only work once. Like if I clicked on Make it would move up -50, or if I clicked on color it would move up -100. But after that one time it will not move again. Like if I clicked on Make it would move up -50, but then if I would click Color it will not move to -100. So then I tried doing it changing the constraints.
func textFieldDidBeginEditing(_ textField: UITextField)
    {
        if make==textField
        {
            infoContainer.translatesAutoresizingMaskIntoConstraints = false

            self.view.addSubview(infoContainer)

            let leadingConstraint = infoContainer.leadingAnchor.constraint(equalTo: self.view.leadingAnchor)
            let trailingConstraint = infoContainer.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
            let topConstraint = infoContainer.topAnchor.constraint(equalTo: self.view.topAnchor, constant: -50)
            let bottomConstraint = infoContainer.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -50)

            initialConstraints.append(contentsOf: [leadingConstraint,trailingConstraint,topConstraint,bottomConstraint])

            NSLayoutConstraint.activate(initialConstraints)
        }
        if model==textField
        {
            infoContainer.translatesAutoresizingMaskIntoConstraints = false

            self.view.addSubview(infoContainer)

            let leadingConstraint = infoContainer.leadingAnchor.constraint(equalTo: self.view.leadingAnchor)
            let trailingConstraint = infoContainer.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
            let topConstraint = infoContainer.topAnchor.constraint(equalTo: self.view.topAnchor, constant: -75)
            let bottomConstraint = infoContainer.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -75)

            initialConstraints.append(contentsOf: [leadingConstraint,trailingConstraint,topConstraint,bottomConstraint])

            NSLayoutConstraint.activate(initialConstraints)
        }
        if color==textField
        {
            infoContainer.translatesAutoresizingMaskIntoConstraints = false

            self.view.addSubview(infoContainer)

            let leadingConstraint = infoContainer.leadingAnchor.constraint(equalTo: self.view.leadingAnchor)
            let trailingConstraint = infoContainer.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
            let topConstraint = infoContainer.topAnchor.constraint(equalTo: self.view.topAnchor, constant: -100)
            let bottomConstraint = infoContainer.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -100)

            initialConstraints.append(contentsOf: [leadingConstraint,trailingConstraint,topConstraint,bottomConstraint])

            NSLayoutConstraint.activate(initialConstraints)
        }
    }

This worked a little bit better. If I clicked on Make it moved up -50, and then model moved up -75, and then Color moved up -100. But then it will not move back down, like if I clicked back on Make it will not move back down to -50. I even set Color to +50. When I clicked on color it would drop +50, and then when I would click on Make it would move up to -50, and Model would move it up -75. But if I would click color again, it will not move back down to +50. Where am I going wrong?

A: The problem is that you add the constraints every move , and this with time makes the conflicts , so you need to add the constraints only once , and adjust the constant value of the constraint you want to move , instead do this
1- Add this code snippet inside viewDidLoad
var bottomConstraint:NSLayoutConstraint!

//
infoContainer.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(infoContainer)
let leadingConstraint = infoContainer.leadingAnchor.constraint(equalTo: self.view.leadingAnchor)
let trailingConstraint = infoContainer.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
let topConstraint = infoContainer.topAnchor.constraint(equalTo: self.view.topAnchor, constant: -50)
bottomConstraint = infoContainer.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -50)
initialConstraints.append(contentsOf: [leadingConstraint,trailingConstraint,topConstraint,bottomConstraint])
NSLayoutConstraint.activate(initialConstraints)

2-
func textFieldDidBeginEditing(_ textField: UITextField)
{
    if make == textField
    {
        self.bottomConstraint.constant = -50
    }
    if model == textField
    {
        self.bottomConstraint.constant = -75
    }
    if color == textField
    {
        self.bottomConstraint.constant = -100
    }

   self.view.layoutIfNeeded()

   // you can animate it to

   /*
    UIView.animate(withDuration:0.5) {
      self.view.layoutIfNeeded()
    } */
}

You can do the same with topConstraint if you wanted to


text:
Q: how to get the object reference of a class which has a label control inside it from that label? I have a class which has a Label field. Now i want to get the reference of that class from that label. How can i do that?
Here is what i have.
public class Abc
{
    Label l;
}
public partial class Form1 : Form
{
    private void btnins_Click(object sender, EventArgs e)
    {
       Abc ob=new Abc();
       ob.l=new new Label();
       l.Text="Right Click Me";
       l.ContextMenuStrip = cntxtdelmnu;
    }

    private void cntxtdelnode_Click(object sender, EventArgs e)
    {
       Label lbl= (Label)cntxtdelmnu.SourceControl;

       //Here I have to get the reference of ob using lbl.
    }
}

A: You can't, basically. There could be multiple objects which have references to that label - or none at all. You can't get a "backwards" reference. You could potentially store a reference in the Tag property:
Abc ob=new Abc();
ob.l= new Label();
ob.l.Text="Right Click Me";
ob.l.ContextMenuStrip = cntxtdelmnu;
ob.l.Tag = ob;

Or using an object initializer:
Abc ob = new Abc();
ob.l = new Label { Text = "Right Click Me", ContextMenuStrip = cntxtdelmnu, Tag = ob };

I would try to avoid needing that though. It's not clear from the question why you want it, but there may be better approaches. (I really hope those aren't your real names, too...)