text:
Q: SQL date diff disregarding nights using an Oracle database, I need to know the difference between any two dates (in seconds), disregarding the interval from 6pm to 8am.
So for example, the difference between 01.11.2011 1pm and 03.11.2011 1pm amounts to 20 hours (or 72000 seconds respectively). I also need to disregard weekends and holidays, but I already got a PLSQL function for that.
Thank you in advance!
Regards,
 Alex

EDIT
Meanwhile I came up with a solution myself, which is honestly not very sophisticated but does the work:
CREATE OR REPLACE FUNCTION "GET_WORKTIME"
(
  startdate_in in date,
  enddate_in   in date
)
RETURN NUMBER
AS
  days_between number(4);
  duration number;
  end_of_first_day date;
  start_of_last_day date;
  startdate date;
  enddate date;
  weekday number(1);
  temp_date date;
  holidays day_array;
  is_holiday boolean;
BEGIN
  duration     := 0;
  startdate    := startdate_in;
  enddate      := enddate_in;

IF (startdate IS NULL OR enddate IS NULL OR startdate >= enddate) THEN
  RETURN 0;
END IF;

days_between := trunc(enddate) - trunc(startdate);

end_of_first_day  := to_date(concat(to_char(startdate, 'dd.mm.yyyy'), ' 18:00:00'), 'dd.mm.yyyy hh24:mi:ss');
start_of_last_day := to_date(concat(to_char(enddate,   'dd.mm.yyyy'), ' 08:00:00'), 'dd.mm.yyyy hh24:mi:ss');

temp_date := startdate;

FOR i IN 0..days_between LOOP
    -- if it is the first day, just calculate the time until the end of that day
    IF i = 0 THEN
        duration := duration + greatest((end_of_first_day - startdate), 0) * 24 * 3600;

    -- if it is the last day, just calculate the time until that point in time
    ELSIF i = days_between THEN
        duration := duration + greatest((enddate - start_of_last_day),  0) * 24 * 3600;

    -- for every other day, simply add 10 hours (6pm - 8am) if it is neither
    -- saturday or sunday nor a holiday
    ELSE
        weekday    := to_number(to_char(temp_date, 'D'));
        is_holiday := false;

        -- weekend?
        IF (NOT weekday IN (6,7)) THEN

            -- holiday?
            FOR j IN extract(year FROM startdate)..extract(year FROM enddate) LOOP
                holidays := get_holidays_for_year(j);

                FOR k IN 1..holidays.count LOOP
                    IF (holidays(k) = trunc(temp_date)) THEN
                        is_holiday := true;
                    END IF;
                END LOOP;
            END LOOP;

            -- add 10 hours to the duration
            IF (NOT is_holiday) THEN
                duration := duration + 10 * 3600;
            END IF;
        END IF;
    END IF;

    temp_date := temp_date + 1;
END LOOP;
RETURN duration;
END;

The function also disregards weekends and holidays, so it looks a little more comprehensive than it actually is. Thank you for your help!
Regards,
 Alex

A: It may be easiest to break this into 3 parts:

*

*The first partial day (if any)

*The last partial day (if any)

*The intervening whole days (if any)

The first partial day is from the later of (start time, 8am) to the earlier of (last_date, 6pm on the first day), so we subtract those to get the time for the first day:
greatest ( least ( trunc(first_date)+18/24
                        , last_date
                        ) - greatest( first_date
                                    , trunc(first_date)+8/24
                                    )
                , 0) * 24 as last_day_hours

The outer greatest function ensures that we don't get a negative value e.g. if start time is after 6pm.
If the last day is not the same as the first day then the last partial day is from 8am to (end time) on the last day:
   case when trunc(last_date) != trunc(first_date)
        then greatest ( least( last_date
                             , trunc(last_date)+18/24
                             )
                        - (trunc(last_date)+8/24)
                      , 0) * 24
        else 0 end as last_day_hours

The intervening whole days are (in hours):
   greatest ( (trunc(last_date) - (trunc(first_date)+1))
            , 0
            ) * 10 as intervening_days_in_hours

10 being the number of hours between 8am and 6pm
So adding those 3 values together gives the total hours for the period, and multiplying the total by 3600 gives the seconds:
(
   (greatest ( least ( trunc(first_date)+18/24
                    , last_date
                    ) - greatest( first_date
                                , trunc(first_date)+8/24
                                )
            , 0) * 24)
 + case when trunc(last_date) != trunc(first_date)
        then greatest ( least( last_date
                             , trunc(last_date)+18/24
                             )
                        - (trunc(last_date)+8/24)
                      , 0) * 24
        else 0 end
 + (greatest ( (trunc(last_date) - (trunc(first_date)+1))
            , 0
            ) * 10)
) * 3600 as total_seconds

I can't help feeling it should be easier than this though!  And of course, this does not take weekends into account.

A: In Oracle you can simply subtract two dates.
You can calculate the number of seconds by dividing the result by (24*60*60)
select (last_date - first_date) / (24*60*60) as seconds from table

A trick to format the difference is this:
select to_char(trunc(sysdate) + (last_date - first_date), 'hh24:mi:ss') as time_between from table


text:
Q: I updated to 10.9.2 and now SSL is broken. How do I fix this? As per the title, I upgraded my Mac to Mavericks 10.9.2, and now a bunch of websites which use SSL (aka https) don't work!

What do I do?

A: Open Keychain Access and delete the DigiCert certificates, but only the ones in the login keychain - not the ones in System or System Roots.
Afterward, you may need to restart your browser and/or network service (switch Airport off and on again, or disable and re-enable Ethernet. If you want to be sure, just restart your computer.
If you're a dummy (like I was) and deleted all the DigiCert entries, you can restore them by manually downloading and installing the 10.9.2 update from Apple.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parse error: syntax error, unexpected '=', expecting ',' or ';' when using PDO connection script I have copied the PDO connection script directly from the php.net documentation, however, it fails to work, because it gets this error.
<?php
  global $pdo = new PDO('mysql:host=localhost;dbname=pionear', "root", "");
?>

http://php.net/manual/en/pdo.connections.php

A: You cannot declare a variable in the global scope like that. You have to declare it as a normal variable and than access it through global (e.g. in a function):
$pdo = new PDO('mysql:host=localhost;dbname=pionear', "root", "");

function something() {
    global $pdo;
    $pdo->doSometing();
}

something();

You can check the documentation on the global keyword for more information. If you do not want to use the global keyword you can instead use $GLOBALS (which is a 'superglobal', thus no need to do global $pdo;).


text:
Q: SQOOP IMPORT AND EVAL I have a view on SQL server and the view on X DB is joined with table on Y DB.If I try to access this View from SQOOP using SQL server connection rferencing X DB, I am unable to get the results but If I move the data from Y DB to X DB and chnage the view to refer both the tables in XDB I see the results.
How can I overcome this problem because It's not possible to bring more than 100 tables from Y to X DB.
Please advice

A: The problem was with the SQL server side with permissions.
Thank you.


text:
Q: Redis connect ECONNREFUSED Пробую запустить скрипт zbx_redis_stats.js в консоли получаю ответ
/etc/zabbix/script/redis/zbx_redis_stats.js
Error: Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED

Редис запущен и работает. Порт слушает. В чём может быть проблема?

A: Проблема заключается в том что для работы скрипта нужен nmp не ниже 2й версии. После обновления всё заработало.


text:
Q: Some Steam games won't start up, gameoverlayrenderer.so error I'm using an Intel HD Graphics card.
For the last few days, for an unknown reason, some Steam games won't start up, including Half-Life and Garry's Mod.
Here's the shell output with Half-Life:
Game update: AppID 70 "Half-Life", ProcID 28160, IP 0.0.0.0:0
ERROR: ld.so: object '/home/s0/.local/share/Steam/ubuntu12_32/gameoverlayrenderer.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.
ERROR: ld.so: object '/home/s0/.local/share/Steam/ubuntu12_32/gameoverlayrenderer.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.
pid 28164 != 28163, skipping destruction (fork without exec?)
ERROR: ld.so: object '/home/s0/.local/share/Steam/ubuntu12_32/gameoverlayrenderer.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.
ERROR: ld.so: object '/home/s0/.local/share/Steam/ubuntu12_64/gameoverlayrenderer.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS64): ignored.
Generating new string page texture 399: 128x256, total string texture memory is 3,84 MB
Using breakpad crash handler
Setting breakpad minidump AppID = 70
Forcing breakpad minidump interfaces to load
Looking up breakpad interfaces from steamclient
Calling BreakpadMiniDumpSystemInit
Looking up breakpad interfaces from steamclient
Calling BreakpadMiniDumpSystemInit
Steam_SetMinidumpSteamID:  Caching Steam ID:  76561198056430718 [API loaded yes]
Steam_SetMinidumpSteamID:  Setting Steam ID:  76561198056430718
ERROR: ld.so: object '/home/s0/.local/share/Steam/ubuntu12_64/gameoverlayrenderer.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS64): ignored.
assert_20150621233104_1.dmp[28171]: Uploading dump (out-of-process)
/tmp/dumps/assert_20150621233104_1.dmp
/home/s0/.local/share/Steam/SteamApps/common/Half-Life/hl.sh : line 38 : 28166 Segmentation fault  (core dumped) ${DEBUGGER} "${GAMEROOT}"/${GAMEEXE} $@
Game removed: AppID 70 "Half-Life", ProcID 28166

I've tried removing all the Steam Runtime libraries, but nothing changed.

A: You need the 32 bit libGL drivers (libgl1-mesaa-dri:i386).
You can issue this command via terminal,
sudo apt-get install libgl1-mesa-dri:i386

If you already have it, try reinstalling,
sudo apt-get install --reinstall libgl1-mesa-dri:i386

Restart your computer and try again.
If that doesn't work, check out this: Error loading libGL.so.1


text:
Q: If a point is visible on the map How to know if a point is visible on my map ?
var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
if map.getbounds().contains(point) ...

A: If by visible you are meaning if a point is inside a map's visible area (viewport);
// assuming you initialized your map

var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var currentBounds = map.getBounds() // get bounds of the map object's viewport

if(currentBounds.contains(point)){
    // your location is inside your map object's viewport
}else{
    // your location is out of the bounds of the map's visible viewport
}


text:
Q: Mediation: Significant indirect effect, but total effect nonsignificant, no inconsistent mediation I conducted a mediation analysis via lavaan. For estimating all effects, I used 10,000 bootstraps.
I have problems interpeting my results.
Path a is negative and significant.
Path b is positive and significant.
Path c is negative, but not significant.
The indirect effect aXb is small, negative, but significant.
However, the total effect aXb+c is not significant, although its absolute value is greater than the indirect effect (since aXb and c are both negative).
So I don't have the case of an inconsistent mediation, since the mediator doesn't suppress the effect of X on Y.
Is it really possible that the indirect effect can be significant in bootstraps, while the total effect is not although it is greater than the indirect effect? Can I still interpret a mediation? If c was positive, then the total effect would be smaller than the indirect effect and then it would make sense that the indirect effect is significant while the total effect is not.


text:
Q: Which package is required for \Z to work as the symbol for the set of integers? According to http://www.proofwiki.org/wiki/Symbols:Z#The_Set_of_Integers,
\Z should produce the symbol for the set of integers, but I have not been able to find the package that enables this feature.
I have tried dsfont as well as amsmath,amsfonts,amsthm,amssymb but none of them seem to have it.

A: What about using
\usepackage{amsfonts}
\newcommand{\Z}{\mathbb{Z}}

and then using it in equations?
EDIT: forgot, that it needs amsfonts package.


text:
Q: Google API | Distance Matrix I need help with my code.
First, is my approach correct that I use the GoogleDistanceMatrix to get the real route distance and not just the linear distance?
I want to use an Geocoordinate for the origin and destination Adress but it doesnt seem to work:
public double CalculateGoogleDistance(GeoCoordinate from, GeoCoordinate to) {
  DistanceMatrixRequest request = new DistanceMatrixRequest();
  request.Key = "****";

  request.Origins = new Location[] {
    new Location(from)
  };
  request.Destinations = new Location[] {
    new Location(to)
  };

  var response = GoogleApi.GoogleMaps.DistanceMatrix.Query(request);

  return response.Rows.First().Elements.First().Distance.Value;
}

A: First off, you appear to be using 3rd party libraries/repositories in using Google Maps API services, so I would advice that you only follow their official documentations, in which I will be providing as I answer your questions.
As mentioned in their official documentation, even though it is optional, the default trafic_model is bestguess, meaning that the result will be based on the best estimate of travel time given what is known about both historical traffic conditions and live traffic. You can learn more about the other traffic model optional parameters here.
Now, with regards to getting "real route distance", you are only referring to the live result excluding historical traffic. To get this, you would need to specify the departureTime to now as given in the example from the doc:
drivingOptions: {
    departureTime: new Date(Date.now() + N),  // for the time N milliseconds from now.
    trafficModel: 'bestguess'
}

As you can see, that is how Distance Matrix API works.

Note: The departure time and traffic model is also applicable to Directions API.

See this link for the web service version of Distance Matrix API web service.


text:
Q: Mecha anime with female villain put into cryo-sleep I'm trying to identify an anime I saw on TV 15-20 years ago. It was a mecha anime (maybe one of the Gundams?) with two space empires at war. The "bad" side was led by a female commander, and at the end of the series she and her fleet were defeated. Instead of being killed, she chose to be put into eternal cryo-sleep as her punishment.
I was a kid when I watched this, so the details could be wrong in various places; sorry in advance. I vaguely remember the female commander had green hair, but this might be wrong too.


text:
Q: How to read adsense URL in C# (the one that is shown on mouse over) How do I read the URL which is shown when move your mouse over to Adsense link? I am trying to read it using Webbrowser control in C# but it is nowhere to be found in DocumentText. Seems like it is being displayed through Javascript so how can I read it?
Even GetElementById function doesn't return the required element id.
Two examples of such URL are:
http://www.googleadservices.com/pagead/aclk?sa=L&ai=By4nW0cV2nGieB6e7.........
and
http://googleads.g.doubleclick.net/aclk?sa=l&ai=BgdDhR3M1L47d..........

A: Google adsense is placed on a page by the inclusion of a script. that script then runs once the page has loaded and generates either an iframe, or markup diurectly in the page. just getting the page will not run the adsense, you have to run the actual javascript in the page first, and then examine the generated markup.
If you want to do this from c# you should use something like javascriptdotnet or similar. - Or spider the page in java and use Rhino.

A: Use the library provided by CodeCentix to read iframes
http://codecentrix.blogspot.com/2008/02/when-ihtmlwindow2document-throws.html


text:
Q: Dag example pet failed to insert and getbirth I am new to airflow. I set up everything according to official documentation. I use pet example DAG, nevertheless when i look into DAG log it shows me following errors:
First error comming from populate_pet_table
psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type integer: "Maxy"
LINE 2:             INSERT INTO pet VALUES ('Maxy', 'Dog', '2018-07-...

Second error comming from get_birth_date
BETWEEN SYMMETRIC 2020-01-01 AND 2020-12-31;

HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

What is wrong there? This is really official example so to me should work fine. This is the dag's code:
import datetime

from airflow import DAG
from airflow.providers.postgres.operators.postgres import PostgresOperator

# create_pet_table, populate_pet_table, get_all_pets, and get_birth_date are examples of tasks created by
# instantiating the Postgres Operator

with DAG(
    dag_id="postgres_operator_dag",
    start_date=datetime.datetime(2020, 2, 2),
    schedule_interval="@once",
    catchup=False,
) as dag:
    create_pet_table = PostgresOperator(
        task_id="create_pet_table",
        postgres_conn_id="postgres_default",
        sql="""
            CREATE TABLE IF NOT EXISTS pet (
            pet_id SERIAL PRIMARY KEY,
            name VARCHAR NOT NULL,
            pet_type VARCHAR NOT NULL,
            birth_date DATE NOT NULL,
            OWNER VARCHAR NOT NULL);
          """,
    )
    populate_pet_table = PostgresOperator(
        task_id="populate_pet_table",
        postgres_conn_id="postgres_default",
        sql="""
            INSERT INTO pet VALUES ( 'Max', 'Dog', '2018-07-05', 'Jane');
            INSERT INTO pet VALUES ( 'Susie', 'Cat', '2019-05-01', 'Phil');
            INSERT INTO pet VALUES ( 'Lester', 'Hamster', '2020-06-23', 'Lily');
            INSERT INTO pet VALUES ( 'Quincy', 'Parrot', '2013-08-11', 'Anne');
            """,
    )
    get_all_pets = PostgresOperator(
        task_id="get_all_pets", postgres_conn_id="postgres_default", sql="SELECT * FROM pet;"
    )
    get_birth_date = PostgresOperator(
        task_id="get_birth_date",
        postgres_conn_id="postgres_default",
        sql="""
            SELECT * FROM pet
            WHERE birth_date
            BETWEEN SYMMETRIC {{ params.begin_date }} AND {{ params.end_date }};
            """,
        params={'begin_date': '2020-01-01', 'end_date': '2020-12-31'},
    )

    create_pet_table >> populate_pet_table >> get_all_pets >> get_birth_date

A: There seem to be an error with the SQL itself.
Change:
INSERT INTO pet VALUES ( 'Max', 'Dog', '2018-07-05', 'Jane');
INSERT INTO pet VALUES ( 'Susie', 'Cat', '2019-05-01', 'Phil');
INSERT INTO pet VALUES ( 'Lester', 'Hamster', '2020-06-23', 'Lily');
INSERT INTO pet VALUES ( 'Quincy', 'Parrot', '2013-08-11', 'Anne');

To:
INSERT INTO pet (name, pet_type, birth_date, OWNER) VALUES ( 'Max', 'Dog', '2018-07-05', 'Jane');
INSERT INTO pet (name, pet_type, birth_date, OWNER) VALUES ( 'Susie', 'Cat', '2019-05-01', 'Phil');
INSERT INTO pet (name, pet_type, birth_date, OWNER) VALUES ( 'Lester', 'Hamster', '2020-06-23', 'Lily');
INSERT INTO pet (name, pet_type, birth_date, OWNER) VALUES ( 'Quincy', 'Parrot', '2013-08-11', 'Anne');

For the second issue you need to change
BETWEEN SYMMETRIC {{ params.begin_date }} AND {{ params.end_date }};

to:
BETWEEN SYMMETRIC DATE '{{ params.begin_date }}' AND DATE '{{ params.end_date }}';

and it will work fine.
Example from sqlfiddle
I raised a PR to fix the issue.


text:
Q: Storing Conditional Logic (Logical Structures) in XML I have the need to express simple conditionals as program input.  The input must be human readable.
Is XML suited for this?
For example, I have the following conditional statement:
If AnimalType = Leopard And (SourceCountry = Kenya Or TargetCountry = Kenya) Then
    ZooKeeper=Jack
Else
    ZooKeeper=Jill
End If

Expressing the above in XML might look something like this:
<If>
    <Conditional>
        <And>
            <AnimalType>Leopard<AnimalType>
            <Or>
                <SourceCountry>Kenya</SourceCountry>
                <TargetCountry>Kenya</TargetCountry>
            </Or>
        </And>
    </Conditional>
    <True>
        <ZooKeeper>Jack</ZooKeeper>
    </True>
    <False>
        <ZooKeeper>Jill</ZooKeeper>
    <False>
</If>

Any ideas on how best to represent conditional statements in XML?
I haven't yet explored using attributes.  I don't currently have the need for nested 'If' statements or the 'Else If' clause, but I'm going to try and work them in anyway.
Perhaps the VB code is more 'readable' than XML can be in this case and I should create a custom flat-file format instead.

A: There's nothing wrong with XML for this, but you could save yourself some overhead with a lighter syntax like a LISP-style lists:
(if
    (and
         (AnimalType Leopard)
         (or
             (SourceCountry Kenya)
             (TargetCountry Kenya)
         )
     )
     (ZooKeeper Jack)
     (ZooKeeper Jill)
 )

You can use ordering of the items inside the if instead of explicitly declaring condition, true, false.  The basic requirement that you'll have is that a proper syntax tree is preserved.

A: Perhaps you've heard of or seen RuleML?
This seems to be what you're looking for. There is an open source rules engine that uses RuleML for .NET that I've used with C#: NxBRE
NxBRE also has a Visio stencil that makes looking at the rules easy for others to understand. They also experimented with a human readable format but I'm not sure that's still in progress or not.

A: You said you wanted it to be human-readable, and then you presented a nearly impenetrable XML example.  I'm not sure what XML is buying you here.  A simple parser for a truly human-readable language would probably be a good investment of your time.

A: Since XML is convenient in this case and VB is quite 'human readable', I think I'll go with something like this:
    <Conditional>
        If AnimalType = Leopard And (SourceCountry = Kenya Or TargetCountry = Kenya) Then
            ZooKeeper=Jack
        Else
            ZooKeeper=Jill
        End If
    </Conditional>


text:
Q: "Who him?" as a stand-in for "Who is he?" I'm curious: is this valid under some rule of grammar I don't know?  Was it ever valid, or was it slang or a personal idiosyncrasy?  Or (I shudder to think) was it invented by later authors, as a phrase that sounds sufficiently outlandish to add "flavor" to a novel?
I've run across this construction in several "period" novels set in the 18th century, most recently in The Yellow Admiral by Patrick O'Brian:

'I shall just have time to run up to
the House for the committee meeting,
deliver my thunderbolt, and then post
down to Torbay, where Heneage Dundas
will touch before the change of the
moon, landing Jenkins -,
'Who him?'
'My jobbing captain, my temporary
replacement,' said Jack, and from his
tone and the set of his face Stephen
gathered that he did not think highly
of the man.

I'd like to clarify: I am not talking about "Who, him?" ("are you seriously talking about THAT guy?"), nor am I talking about the poetic reversal of verb and object, as in Spenser's Faerie Queen:

At last, when as himself he 'gan to find
To Una back he cast him to retire:
Who him awaited still with pensive Mind.
Great thanks and goodly Meed, to that good Sire,
He thence departing gave for his pains Hire.
So came to Una, who him joy'd to see,
And after little rest, 'gan him desire,
Of her Adventure mindful for to be.
So leave they take of Caelia, and her Daughters three.

I ask because... well, I rather like the sound of it, and have been tempted to slip it into my own conversation.  But I'd like to have cover for the inevitable discussion afterward!

A: The phrase "who him" is also used in Jamaican dialect. It may mean "who is he?" , as well as "who does he think he is?." This depends on the situation in which the phrase is used and also the tone used to deliver the phrase. I  tend to use it to mean "who does he think he is."

A: "Who he" or "Who him" are idiomatic usages. They're not that common, but they are at least understood, if not very widely.

A: Not a B.E. speaker, so I can't say for sure on that side of the pond, but A.E. wouldn't typically ever use this construction. While I have no problem grasping the semantic meaning, the syntax sounds "odd" to my ear, and would likely get a bit of a raise. That alone might be worth using it. ;-)

A: I lived in the UK for two years an never heard (or at least noticed) this. However, in 2014's BBC Sherlock, season 3, episode 2, Sherlock says "Who he?" when reviewing wedding invitations with John Watson's fiance. I've watched the episode multiple times, and it is definitely "Who he?" Since Benedict Cumberbatch's Sherlock is a very "public school" type with a sophisticated speaking style, I wondered if "who he?" might be an accepted form of British English.


text:
Q: Background copy large files to a laptop? I like to watch Windows Media Center recorded TV files on my laptop in bed.  I find, though, that when the programs are in high definition (HD), I have a lot of stuttering and delays—no doubt because of the amount of data being transferred.
I actually have a fair amount of space on the laptop's HDD, and wouldn't mind moving the files onto that hard drive, where no doubt my problem would go away.  But that requires some planning & time for the files to move.
Is there a utility out there that would kind of 'trickle' the files to the laptop over a long period of time, w/out soaking its bandwidth?  Something like Microsoft's BITS tech?
Both machines are running Windows 7.

A: Just use the easiest solution. Download SMplayer, set the cache large enough (you can go to 25000kb even or more) and try with that. Definitely fixes your problem. (Download the portable 7z version, no need to install it.)Explanation. Mplayer is a very versatile and awesome player. SMplayer is a frontend for that. You can replace the in-built mplayer (which comes with smplayer) with a few clicks (for better performance. And you can use the 'ffmpeg-mt' version.). Grab your copy from the linked site (ffmpeg-mt is using the multi cores also), place it in the unzipped smplayer folder. Open SMplayer and select the mplayer binary in the options.Other solutions are using TeraCopy or Total Commander. (You can specify the transfer speed or pause it.)

If the performance is the problem. Install CCCP pack , launch Media Player Classic HC and go to settings. There, go to Internal Filters and on the far right column, select the H264/AVC(DXVA) and the VC1(DXVA) ones. Close mpc-hc and start your movie with it. If everything is OK, you should be able to play it without a problem, and mpc-hc switches to "Playing[DXVA]" at the bottom.
NOTE: This works with ANY video card. However, you can also use CUDA acceleration with NVidia cards. You need a 8600 or higher NVidia card for that, and a "CoreAVC" codec. (Its proprietary, not free, however its the best.) Buy it, install it, launch Start -> Combined Community... -> Filters -> ffdshow video configuration. Go to Codecs at the left and at the H264/AVC, select disabled instead of the "libavcodec". (mpc-hc lets you use ffmpeg-mt also as you can see it here). Restart your mpc-hc/playback, there you go. :)

A: Try NetLimiter. This can limit bandwidth usage of certain programs. I'm not sure if it works on Win7 though, I used it on XP.

A: Are you sure that your problem is network I/O?  Because even on a wireless network it shouldn't be, unless you're watching 1080p Blu-ray rips.  I don't mean encodes, I mean the raw rips.
h.264 is CPU-intensive to decode though.  Make sure your problem isn't that the CPU isn't fast enough to do the decoding unassisted.

A: I think the HDD activity is interfering with the prefetching when watching your vids...personally I would set up a ftp server and have bandwidth limits but it prob wont solve the core issue. If you haven't already try bumping up the cache as suggest earlier and adding more ram to your system if you haven't maxed it out yet.


text:
Q: select pages with condition on page title using rest api I am using rest api to filter pages and fetch their title and url
//_api/search/query?querytext='Path:http:sharepointpath owstaxIdTaxKeyword:81394a-cedb-4c19
AND
Title<>sometitle'&rowlimit=5& selectproperties='Title'&enablequeryrules=false

Its fetching from the paths that I specify, but the problem is I want to select pages that do not have title that I give ( Title<>sometitle ). But the query is still returning results with title sometitle
What have I missed?

A: Try with this syntax instead:
NOT Title="sometitle"
So your query becomes
//_api/search/query?querytext='Path:http:sharepointpath owstaxIdTaxKeyword:81394a-cedb-4c19
AND NOT Title="sometitle"'&rowlimit=5& selectproperties='Title'&enablequeryrules=false


text:
Q: download_html() Error in basename(url) : path too long in R I'd like to download some html code from sites web, but my R code retuns me this: Error in basename(url) : path too long
An example of url is: https://www.amazon.com/VIZIO-1080-Smart-LED-D43-D1/dp/B01A0LGU3O/ref=sxin_3_osp20-8d5e1b7c_cov?ascsubtag=8d5e1b7c-b3a8-4018-9315-b01e2602c1af&creativeASIN=B01A0LGU3O&cv_ct_id=amzn1.osp.8d5e1b7c-b3a8-4018-9315-b01e2602c1af&cv_ct_pg=search&cv_ct_wn=osp-search&keywords=televisore&linkCode=oas&pd_rd_i=B01A0LGU3O&pd_rd_r=6ebe627b-37f8-4a8d-8d6b-e9b1fbb561f2&pd_rd_w=Sc4pX&pd_rd_wg=KAdJs&pf_rd_p=43ba9e17-96f5-4491-b054-e546013f7dc4&pf_rd_r=SR4SDFVDJP5YP89J9F7R&qid=1559599142&s=gateway&tag=bestcont06-20")
if I use the function download_html() R returns back this Error in basename(url) : path too long
The url works, why R returns me an error?
Is there a way to bypass the problem?
Thank you in advance

A: The issue here is that download_html() uses basename() to generate a name for the output file:
download_xml(url, file = basename(url))

and basename() doesn't like the long URL - it's trying to use everything after the last / for a file name.
The easiest solution is to supply your own name for the output file:
download_xml(your_very_long_url, file = "myfile.html")


text:
Q: Was the White Guardian involved in the Key to TIme at all? In the "Key to Time" epic, covering the whole of season sixteen of Doctor Who, the Doctor is sent on a mission to retrieve the six pieces of the Key, ostensibly by the White Guardian.  However, he is not the only person looking for the pieces.
The third story, "The Stones of Blood," begins with a warning voice:  "Beware of the Black Guardian," which is the first mention of the Guardians since Romana's arrival in "The Ribos Operation."  The Doctor then visits contemporary Earth, where the third segment has been held by the alien criminal Cessair** of Diplos, having brought it there thousands of years earlier.  And Cessair knows both how to use the segment's shape-changing powers to alter her appearance, and that the Doctor is there looking for the segment.  The natural conclusion is that she is an agent of the Black Guardian, who is seeking the key.
In the last story, "The Armageddon Factor," the main villain, the Shadow, makes no attempt to hide the fact that he is a servant of the Black Guardian, and that he has been waiting for the Doctor to arrive with the first five segments of the Key.  ("I am the Shadow.  Your adversary, shall we say.  It is not important.  You come in quest of a key.")  At the end, with Shadow, in death, calls out to his master for help, but the Black Guardian disguises himself as the White and goes to claim the complete Key to Time from the Doctor and Romana.
My inference, from the first time I saw the stories, was that the whole storyline was entirely the work of the Black Guardian, that the figure who gave the Doctor his assignment in the first story was not the White Guardian, but again the Black in disguise.  So the Doctor, Cessair, and the Shadow were all working for the same power, knowingly of not.  This explains, for example, the curious fact that Cessair of Diplos had captured one of the segments and brought it to the Doctor's favorite planet; it was there waiting for him to swing by and claim it.
However, in a number of online discussions of the season-long plot, I have seen the suggestion that the White Guardian really did put the Doctor on the job, and that he completed his adjustments to correct the coming chaos in spacetime while the Key was complete, before it was nearly stolen by the Black Guardian.  My ultimate question is whether there is there any evidence for this idea in the stories?  Or is this just a product of people misunderstanding a somewhat subtle plot?
** Only today, as I was researching this question, did I learn that "Cessair," like several the villainess's other identities, is the name of a Celtic heroine/goddess.

A: I am not fully aware of what is considered accepted canon sources in the Who'verse, but everything that I can find corroborates that it is the White Guardian that sets the doctor the task originally.
From a transcript of the show (Admittedly the Guardian could be lying):

GUARDIAN: I am the White Guardian. In order to maintain the universal balance, there is also a Black Guardian, and he also requires the Key to Time, but for a different purpose. An evil purpose. He must not get it. Doctor, at all costs, you must prevent that.

From The Doctor Who guide:

The Doctor and K-9 Mark 2 are sent on a mission by the immensely powerful White Guardian. The six segments of the Key to Time, currently disguised and scattered throughout the cosmos, need to be brought together. Once assembled, the Key will allow the Guardian to restore balance and good to a universe that is descending into evil and chaos. It will also thwart the plans of the fearsome Black Guardian!

From TvTropes:

A godlike guy in a casual white suit, the White Guardian, interrupts the Doctor's puttering around in the TARDIS to give him a quest: find all six segments of the Key To Time. Why and how and what the thing does isn't explained just yet, but the Black Guardian apparently wants it too.

From The Den of Geek:

If you really want to break out the big guns, you can argue that Season 16, during Tom Baker's tenure, was the longest story in the show's history, running for twenty-six episodes.
The Doctor is enlisted by the White Guardian to find the six separate segments of the object through time and space, and assigned a Time Lady companion, Romana, to help.

Probably one of the stronger corroborations is from a book titled The Doctor Who Programme Guide by Jean Marc Lofficier (I was unable to find the actual episode excerpt in google books, this is from a synopsis on this site):

SEASON SIXTEEN
  The Ribos Operation                    9/2/78    9/23/78    4

Sent to seek out the Key To Time by the White Guardian, the Doctor and
his fellow Time Lord Romana, find themselves sucked into a botched
mineral scam on the planet Ribos.

A: It's not a full confirmation, but the Black Guardian himself actually gives us the best indication that the White Guardian was able to fix things while the Key was assembled.
The Doctor is able to confirm that he is really talking to the Black Guardian at the end by asking about Astra, and pointing out that, as part of the key, if it were to be kept assembled, she would be trapped within.  The Guardian admits this to be the case, but dismisses it, as 'the fate of the universe' is at stake.  As the Doctor then points out to Romana, the White Guardian would not have been so cavalier about Astra's fate, and would have complete his work and dispersed the key.
But right before that, while acting as if he believes he is talking to the White Guardian, the Doctor has the following conversation with him.

Doctor:  "What happens now, sir?  You said, if I remember our first conversation, that once it was assembled it would stop the entire universe and enable you to restore the natural balances of good and evil through out the whole of the universe."
Guardian: "That is correct Doctor.  So will you release the key to me that I may do this?"
[The Doctor starts to command the Key to time, but then stops and asks another question]
Doctor: "It's just that, well, the key is already assembled, sir, couldn't you restore the balances now?"
Guardian: "Yes, Doctor.  But I must have the key... for safekeeping."

As I read it, that 'Yes, Doctor' is confirmation that the White Guardian's task just requires the key assembled; the Black Guardian, however, has further plans for it.  The Black Guardian could, perhaps, have interfered, but he was working a long-con on the Doctor and trying to get permanent possession on the key, while the White Guardian just needed it activated with the Black Guardian distracted by his attempt to get the key from the Doctor allowing him to complete his tasks unopposed.
Follow-up
Checking back to the Doctor's original encounter with the White Guardian, he, too, indicates that time need be stopped 'For a brief moment, only.'  I don't know why the Black Guardian would say that, were he to be impersonating the White Guardian at that point, as it undermines his need for the key to be given to him, but it's possible he is trying to use as much truth as possible, with the single lie of his identity set to reverse everything. This is supported by the fact that he indicates a moment later that the pieces need to be returned to him, which is untrue.

All said, I don't know if we ever saw the White Guardian; it could well have been the Black Guardian the entire time.  If so, the White Guardian seems to have been betting on the Doctor's perception to allow the White Guardian to complete his task while the Black Guardian engaged in a fruitless attempt to gain the key for himself.
Very genre-savvy of the White Guardian.


text:
Q: Logical migration from one DB structure to another I am currently in the process of creating a SQL Server CE database application in C# and I am having some logic issues that I thought maybe someone could help with.
Objective: to be able to supply an XML file to the end user, which tells the program to create a new set of tables using the supplied structure (new tables with tmp_ prefix). Existing data then needs to be moved from the old tables to the new ones (with new structure), then the old tables need to be dropped.
I've written too much code to be able to paste it here, so I'm going to break it down into logical steps (as it is a logical issue, not a compiler issue).

*

*Get new database structure from supplied XML file, read into datatable [DONE]

*Dynamically concatenate a SQL query to create new table with tmp_ prefix [DONE]

*Compare new structure with old structure, move relevant data across [NOT DONE]
I am having problems with the logical approach to step 3. Basically I need to move data from an old structure to the new structure - ignoring old columns which do not appear in the new set of columns, and entering blank data for new columns which do not appear in the list of old columns. I have need to adhere to the new column schema, such as datatype, max length, etc etc. This is seriously making my head hurt as I'm very new to C#. Does anyone have ideas as the best way to approach this?
Thanks in advance!


text:
Q: By convention, does 'make install' copy header files to /usr/include? I do make install on a certain library I should be using. I see .so files are copied to /usr/lib, but .h are not copied to /usr/include. Is that right by convention?

A: By convention, files should be copied to
headers  -> $DESTDIR$PREFIX/include
libs     -> $DESTDIR$PREFIX/lib
binaries -> $DESTDIR$PREFIX/bin

where DESTDIR variable is empty by default. And PREFIX is usually set to something like /usr or /usr/local, depending on your intentions. Usually, software which is managed by your system's native package manager is installed to /usr, while software which is not supposed to be managed by operating system's package manager usually goes to /usr/local. So, in your case it should go to /usr/local, but what your makefile actually does is under question.

A: There is no "default" for Makefiles and install pathes. But there is a more or less common file system hierarchy which can be found e.g. here:
https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
From a user perspective I expect that any manual installation will go to /usr/local/...
/usr/... is managed by the distribution and as this it is dangerous to put own files there by default. Maybe your file will conflict with others from the distribution management.
There are a lot of conventions around with different linux ditributions and there is a "standard" which gives more rules also for file system organization:
https://en.wikipedia.org/wiki/Linux_Standard_Base http://www.pathname.com/fhs/
So you can check your requirements against this standards.

A: Another place they may be installed is the /opt directory.
/opt/include/*.h
/opt/lib/lib*.so
/opt/bin/*

In general the top-level directories (/bin, /lib) are for the system commands and libraries (eg. /bin/bash). The /usr directories for applications software and libraries (eg. /usr/bin/libreoffice). The /opt directories for in-house software. Also, if an app needs an older library, it may be store in /opt so it won't interfere with other apps.


text:
Q: SAPUI5, How to: Create a Label/Text that is inline with a RadioButton Group (the Buttons also inline) I am working with SAPUI5, i just wondered how can i make the Text/Label be inline with a RadioButtonGroup,
with the Buttons that also inline.
Summarized: Text/Label inline with Buttons, that are also displayed inline.
What i tried:
<FlexBox alignItems="Start"
justifyContent="Center">

<Text text="An example of a group in warning state"/>
            <RadioButtonGroup valueState="Warning">
                <buttons>
                    <RadioButton id="RB4-1" text="Option 1"/>
                    <RadioButton id="RB4-2" text="Option 2"/>
                </buttons>
            </RadioButtonGroup>

</FlexBox>

What it does: It makes the Label/Text be inline with the RadioButtonGroup, however the Buttons are displayed as a block.
How do i achieve the formatting that i described?
This how it should look like

A:
<FlexBox alignItems="Center"
    justifyContent="Center">

    <Text text="An example of a group in warning state" />
    <RadioButtonGroup columns="4"
        valueState="Warning">
        <buttons>
            <RadioButton id="RB4-1"
                text="Option 1" />
            <RadioButton id="RB4-2"
                text="Option 2" />
            <RadioButton id="RB4-3"
                text="Option 3" />
            <RadioButton id="RB4-4"
                text="Option 4" />
        </buttons>
    </RadioButtonGroup>

</FlexBox>

RadioButtonGroup has the property columns. Multiple columns are displayed next to each other and not beneath.
If you set alignItems to Center the label and the radio buttons text are (more or less) vertically aligned.


text:
Q: Ubuntu on login shows messages from the linux boot process I face this weird problem when it comes to login to my Ubuntu system.

It doesn't happen all the time.When it happens I press the Enter button and after that the system shows the normal login screen.
Does anybody have any idea why is this happening?
I do not understand what the system is trying to tell me with all these messages that it shows.

A: the messages you sent are part of the standard linux boot processes. When the system boots, it do this normally (but Ubuntu displays it logo instead).
The strange part is the "enter" you have to press....you always can press CTRL+ALT+2 (for example), log in to console and try finding out what's happening in the /var/log/syslog log file.
Maybe there will be some hint which will help us finding out what's wrong...
I guess that it will be related to so filesystem check/message or something.


text:
Q: Fade in and Fade Out Text in DIV - Remove Loop I have created a DIV with 3 different quotes fade in and fade out.
I am using below jQuery code for the same.
(function() {
var quotes = $(".changetxt");
var quoteIndex = -1;
function showNextQuote() {
    ++quoteIndex;
    quotes.eq(quoteIndex % quotes.length)
        .fadeIn(1000)
        .delay(4000)
        .fadeOut(500, showNextQuote);
}
showNextQuote();
})();

HTML CODE

        "The simple act of paying positive attention to

        people has a great deal to do with productivity"

- Tom Peters

        "If you deprive yourself of outsourcing and your competitors
 do not, you are putting yourself out of business"

- Lee Kuan Yew

        "Focus on being  PRODUCTIVE

        instead of busy"

- Tim Ferris

It is working perfect but I don't want to loop, There are 3 quotes, so as soon as it shows last (third) quote it should stop animation and no loop.
How can I achieve this?

A: Inside of showNextQuote, instead of return set the quoteIndex back to zero.
function showNextQuote() {
        quoteIndex += 1;
    **if (quoteIndex === 3) quoteIndex = 0;**

    quotes.eq(quoteIndex % quotes.length)
    .fadeIn(3000)
    .delay(4500)
    .fadeOut(500, showNextQuote);
}

A: Check if quoteIndex is in the third execution. If it is, then return
(function() {
    var quotes = $(".changetxt");
    var quoteIndex = -1;

    function showNextQuote() {
        if (quoteIndex == 2) {
            return;
        }
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeIn(1000)
            .delay(4000)
            .fadeOut(500, showNextQuote);
    }
    showNextQuote();
})();

Update
To have the last quote stay, you can use a different approach in which you conditionally call fadOut
(function() {
    var quotes = $(".changetxt");
    var quoteIndex = -1;

    function showNextQuote() {
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeIn(1000)
            .delay(4000);
        if(quoteIndex < 2){
            quotes.eq(quoteIndex % quotes.length).fadeOut(500, showNextQuote);
        }
    }
    showNextQuote();
})();

A: Just don't call the function after the third time, like so:
(function() {
    var quotes = $(".changetxt");
    var quoteIndex = -1;

    function showNextQuote() {
        quoteIndex += 1;

        if (quoteIndex === 3) return;

        quotes.eq(quoteIndex % quotes.length)
        .fadeIn(1000)
        .delay(4000)
        .fadeOut(500, showNextQuote);
    }

    showNextQuote();
}());


text:
Q: In which cases is finalize() actually USED? I've found multiple posts stating when finalize() should NOT be used and that it shouldn't be used in general because nobody guarantees the the object will be garbage collected during the lifetime of the application (unless you actually need the object throughout the lifetime of the application, this is a memory leak in my book). But let's say I have a Java class that initializes something (does memory allocation and initialization) in native space through JNI. As far as I'm concerned, there two ways I can implement this:
1. Implement an init() and deinit() method in the class to do the native initialization and deinitialization. This has a down side that I have to take care of the object life cycle and can't leave that to the garbage collector (which is not very Java-like).
2. Do the initialization in the constructor and deinitialization in the finalize() method. This basically enables the objects to be automatically garbage collected like with any other Java class.
What I'm asking is - is there a reason for me not to go with number 2?
Thanks,
Nenad

A:
What I'm asking is - is there a reason for me not to go with number 2?

Well one reason would be that the native resource won't be release until the GC has reclaimed the Java object whose finalize method will reclaim it.
Whether this reason is actually relevant depends on the nature of the native resource.

Really, when you think about it, this is the same debate that the Java designers would have had about closing streams.

*

*They could have not provided a close() method, and left it entirely to a finalize method ... except that that would lead to problems with output stream not being flushed soon enough, and running out of "file descriptors".

*They could have left it entirely to the close() method ... except that if you did forget to close() a file (and there wasn't a finalize method) you would leak file descriptors ... permanently.

*Instead, they implemented both close() and finalize, and they implemented the latter to call the former.  Thus you get the advantage of closing when the program says so, and something to clean up1 if it neglects to call close().
1 - Of course, there can be problems if you rely on the stream finalize method for cleanup; e.g. if the stream remains reachable by accident, or if it doesn't get garbage collected soon enough, and you run out of file descriptors anyway.  And non-deterministic flushing out output could be a problem too.

OK. What about when the resource in question is purely memory? Isn't that the same as garbage collecting then?

I don't see that.  True  garbage collection doesn't rely on you implementing a finalize method, or a close method, or something else that explictly releases stuff.

A: Code execution doesn't necessarily release resources when the latter should be released. Therefore, I would use finalize as soon as you know that resources are no longer needed if these resources are significant. If resources are small don't use finalize because it comes with an overhead.


text:
Q: For what value of $m$ the is sum $\sum_{i = 0}^{m} {10 \choose i}{20 \choose m - i}$ where ${p\choose q} = 0$, if $pFor what value of $m$ the is sum
$$\sum_{i = 0}^{m} {10 \choose i}{20 \choose m - i}\text{where ${p\choose q}$} = 0\text{, if $p<q$, a maximum}$$
My approach
$$\sum_i^{m} {10 \choose i}{20 \choose m - i} = {10 \choose 0}{20 \choose m} + {10 \choose 1}{20 \choose m - 1} + \dots + {10 \choose m}{20 \choose 0}$$
$$(1 +x)^{20} = {20 \choose 0} + {20 \choose 1}x + \dots + {20 \choose m-1}x^{m-1} + {20 \choose m}x^{m} + \dots + {20 \choose 20}x^{20}$$
$$(1 +x)^{10} = {10 \choose 0} + {10 \choose 1}x + \dots + {10 \choose 10}x^{10}$$
Later what to do??
Any other method or hint will be greatly welcomed.

A: Vandermonde's Identity says that
$$
\sum_{i=0}^m\binom{10}{i}\binom{20}{m-i}=\binom{30}{m}\tag1
$$
The central binomial coefficient is the greatest. Therefore, the maximum of $(1)$ is when $m=15$; that is, $\binom{30}{15}$.

A: Here's how I'm gonna to approach it. Hopefully, it'll give some intuition into the Vandermonde identity that you can read up on later.
Consider a jar of $r$ red marbles and $b$ blue marbles. We need to find the number of ways to pick $m$ marbles.
Well we can pick $1$ red and $m - 1$ blue marbles or $2$ red and $m - 2$ blue marbles or $3$ red and $m - 3$ and so forth...
We need to find the sum total of the number of ways to pick $i$ red and $m - i$ blue marbles, which is exactly the RHS of:
$$ {r+b \choose m} = \sum_i^m {r \choose i}{b \choose m - i}$$
And the LHS is exactly as we described previously: the number of ways to choose $m$ marbles from all $r + b$ marbles. Does this make sense? We are essentially a combinatorial trick called "counting by two ways".
Now where does ${r+b \choose m}$ achieve its maximum? Well Pascal's triangle has it's maximums of every row down it's center column, so ${r+b \choose m}$ is maximized at $\left\lfloor {\frac{r+b}{2}}\right\rfloor$

A: $$(1+x)^{10}= 10_{C_{0}}+10_{C_{1}} x+\cdots+10_{C_{10}} x^{10} \ldots \ldots \ldots \ldots \ldots .(1)$$
$$(1+x)^{20}= 20_{C_{20}}x^{20}+20_{C_{19}} x^{19}+\cdots+20_{C_{0}} \ldots \ldots \ldots \ldots \ldots .(2)$$
On multiplying these two...
$$(1+x)^ {30}= (\cdots)x^{30}+(\cdots)x^{29}+\cdots$$
The largest coefficient would be that of $x^{15}$ and that would be equal to ...
$$\sum_{i=0}^{m}\left(\begin{array}{l}10 \\ i\end{array}\right)\left(\begin{array}{l}20 \\ 15-i\end{array}\right),$$
Hope this helps!

A: Write the (3) expansion as $$(1+1/x)^{10}=~^{10}C_0 + ~^{10}C_1 (1/x)+ ~^{10}C_2(1/x^2)+......+ ~^{10}C_n(1/x^{10})~~~~~(3)$$
Now multiply (2) and (3) mainly collecting the  terms independent of $x$ in the product $$S=\text{coefficient of $x^0$ in} (1+x)^{20}(1+1/x)^{10}$$


text:
Q: given a hex number, how to recover the bytes? upperByte = 4c
lowerByte = 02

4c << 8 = 4c00
4c00+02 = 4c02

4c02 >> 8 = 4c
4c02 & 7f = 2
2 << 8 = 200

(4c | 200)+1 = 24D which is 589 in hex
I have tried to figure it out but get stumped on the first step after -1.  Basically though I'm trying to figure out the 2 bytes from the hex number
some people are having problems figuring out the question, so I will reiterate it (hopefully clearer).
this equation takes 2 bytes 4c and 02 and turns them to a hex number 24d.
i need the reverse, figuring out what the 2 bytes are from the hex number.

A: If I understand your question, your "formula" is:
$$y=x_{up}|(x_{low} \ll 8)+1$$
and the "reverse" would be
$$\left\{\begin{array}{l}x_{low}=(y-1) \gg 8\\x_{up}=y-x_{low}\end{array}\right.$$
with, in your example, $$x_{up}={\tt 4C},\; x_{low}=2\quad \text{and}\quad y={\tt 24D}.$$
However, this only makes sense if $y$ is two bytes long, and it's not clear to me if you mean the original operation to be performed in this order or permuting the values for "lower" and "higher" bytes.
This is similar to asking for the units and tens in decimal number 42, which is more of a programming question than a maths question.
(edited to correct typo in the example value of y)

A: Since this is more of a programming question,
I'm going to use "C notation" for the hex values.
Combining 2 bytes to get a 16-bit integer:
theInteger = (upperByte << 8) + lowerByte;

For example,
upperByte = 0xfc
lowerByte = 0x92
theInteger = (upperByte << 8) + lowerByte
           = (0xfc << 8) + lowerByte
           = ( 0xfc00 ) + 0x92
           = 0xfc92

dissecting a 16-bit integer into two bytes:
upperByte = theInteger >> 8;
lowerByte = theInteger & 0xff;

For example,
theInteger = 0xfc92
upperByte = theInteger >> 8
          = 0xfc92 >> 8
          = 0xfc
lowerByte = theInteger & 0xff
          = 0xfc92 & 0xff
          = 0x92.

formula
I suspect the "& 7f" in that formula should be something more like "& ff".
If it were really "& ff", then reversing the formula is easy -- subtract one from the integer, and then dissect the integer into two bytes.
However, if the "& 7f" is correct, then it's a little more complicated -- no matter what initial byte values we have, that formula (with the "& 7f") will never generate certain integers. In particular, it will never generate the integer 0x8000.
Also, there are two different byte pairs that that formula (with the "& 7f") will generate the same final value. In particular, the byte pair upperByte=0x4c and lowerByte=0xff gives the final integer value 0x7f4d, the same as upperByte=0x4c and lowerByte=0x7f.
Is that really what you wanted?


text:
Q: What RoundingMode constant works 100% like Math.round? I mean is there any RoundingMode constant describing exactly what Math.round(arg) does? I understand that Math.round does not formally use any RoundingMode class/object.
So far I found no analogy. There is a partial analogy - in situations like 1.5, -1,5 etc ties are broken just as in RoundingMode.CEILING ("towards positive infinity"). But RoundingMode.CEILING analogy cannot work for other arguments (1.7, -1.1), so it cannot be a 100% analogy.
So I found absolutely no 100% analogy in all RoundingMode constants which makes me think I was inattentive somewhere. List of constants in RoundingMode class shall have constants for all widely-used rounding modes, right?
So why there is no 100% analogy in RoundingMode class?
Here is the comparison table for RoundingMode class constants and their behaviour.
P.S. Math.floor(arg) method behaves exactly like RoundingMode.FLOOR, Math.ceil(arg) behaves exactly like RoundingMode.CEILING.

A: Math.round() works like RoundingMode.HALF_UP for positive numbers and like RoundingMode.HALF_DOWN for negative numbers.
The reason is that Math.round() rounds ties toward positive infinity and there is no mode that does that.
To clarify, both modes will work exactly like round(), except for ties (i.e. numbers like xxx.5), such as 5.5 and -5.5, which will round to 5 and -5 for HALF_DOWN, 6 and -6 for HALF_UP, but -5 and 6 for round().
What you are looking for is RoundingMode.HALF_CEILING but it doesn't exist.


text:
Q: AngularJS update output of ngRepeat I have a table and with ngRepeat I am showing the products and details
I also have a directive
.directive('onFinishRenderFilters', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    }
})

that I use to fix the html css style
$scope.$on('ngRepeatFinished', function (ngRepeatFinished) {

if($(".row0_fixed").outerHeight()>($(".row0").outerHeight())){
  $(".row0").outerHeight($(".row0_fixed").outerHeight());
}else{
  $(".row0_fixed").outerHeight($(".row0").outerHeight());
}

if($(".row1_fixed").outerHeight()>($(".row1").outerHeight())){
  $(".row1").outerHeight($(".row1_fixed").outerHeight());
}else{
  $(".row1_fixed").outerHeight($(".row1").outerHeight());
}

if($(".row2_fixed").outerHeight()>($(".row2").outerHeight())){
  $(".row2").outerHeight($(".row2_fixed").outerHeight());
}else{
  $(".row2_fixed").outerHeight($(".row2").outerHeight());
}

if($(".row3_fixed").outerHeight()>($(".row3").outerHeight())){
  $(".row3").outerHeight($(".row3_fixed").outerHeight());
}else{
  $(".row3_fixed").outerHeight($(".row3").outerHeight());
}

if($(".row4_fixed").outerHeight()>($(".row4").outerHeight())){
  $(".row4").outerHeight($(".row4_fixed").outerHeight());
}else{
  $(".row4_fixed").outerHeight($(".row4").outerHeight());
}

if($(".row5_fixed").outerHeight()>($(".row5").outerHeight())){
  $(".row5").outerHeight($(".row5_fixed").outerHeight());
}else{
  $(".row5_fixed").outerHeight($(".row5").outerHeight());
}

if($(".row6_fixed").outerHeight()>($(".row6").outerHeight())){
  $(".row6").outerHeight($(".row6_fixed").outerHeight());
}else{
  $(".row6_fixed").outerHeight($(".row6").outerHeight());
}

if($(".row7_fixed").outerHeight()>($(".row7").outerHeight())){
  $(".row7").outerHeight($(".row7_fixed").outerHeight());
}else{
  $(".row7_fixed").outerHeight($(".row7").outerHeight());
}

if($(".row8_fixed").outerHeight()>($(".row8").outerHeight())){
  $(".row8").outerHeight($(".row8_fixed").outerHeight());
}else{
  $(".row8_fixed").outerHeight($(".row8").outerHeight());
}

if($(".row9_fixed").outerHeight()>($(".row9").outerHeight())){
  $(".row9").outerHeight($(".row9_fixed").outerHeight());
}else{
  $(".row9_fixed").outerHeight($(".row9").outerHeight());
}
});
}])

The problem is if I delete a product from the scope, the directive doesn't run again, and the style is broken
Thanks in advance

A: The solution was to add a $watch to the $scope and with jquery see if the outerHeight is changing and fixit
here is part of the code I used to fix the problem
$scope.$watch(function(){
   return $(".row0").outerHeight();
},function(){
  fixTable();
});


text:
Q: Set top boxes - database of 'tv programme/channel' I am currently researching the construction and functionality of set top boxes for services such as Sky + and Freeview.
I need to understand if and how a database structure would be used in terms of the operation of such hardware.
As these devices are accessing libraries of 'tv programme/channel' data I can only imagine that a database must form part of the set up, not least to query to achieve an on screen result.
I cannot find anything in these box technical specification to suggest that though. I have found out a little about IMDs, In-memory databases but I don't really understanding the workings of these - can anyone help?

A: Sky and Freeview adhere to the DVB standard. You want to read ETSI EN 300 468 and learn about decoding SI tables to construct an EPG.


text:
Q: Loop through several text files with a multiple line regex in PowerShell I'm trying to seach through several textfiles with a regex. I've managed to get it working when the regex matches on a single row but when I test with a regex that match on one row and end of another row, it doesn't work.
I've read that you first need to read the entire file to a variable/array and then do the regex search. I've not managed to get this to work.
The structure of the folders and files are

Root Folder
├─17-11-01
│ ├─trace-0.log
│ └─trace-1.log
└─17-11-02
  ├─trace-0.log
  └─trace-1.log

I have managed to get the full path to the files but I'm not sure how I read the content of the file. I found [IO.File]::ReadAllText($Path) but am not sure how I add it to the command below.
Get-ChildItem $Path -Filter $Filter -Recurse |
    Select FullName |
    ft -HideTableHeaders

To summarize what I'm trying to do.

*

*Do a regex search where the matched text will span multiple lines.

*Multiple files in multiple paths under the same root.

*Count each of the regex matches.

I'm currently using PowerShell v2 on Windows 7 but I can upgrade to v4. The script will mostly be used on Windows 10 and Windows Server 2012 R2 and later.
Edit 1
Here is an example of the log file and the regex.

FINER: Entering service: ABC
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: Some info.
2017-11-03T08:22:18.557+0100 - INFO: The request has been completed.

(2017-10-.*FINER\: Entering service: (ABC |ABC1|ABC2))[\s\S]*?(INFO: \d\d\d\d\d\d\d\d\d\d\d\d The request has been completed)

A: Edit 2 Solution
Here is the final code. The regex is in my example didn't match the the example log.
$Files = (Get-ChildItem $Path -Filter $FilterFile -Recurse | Get-Content | Out-String)

(Select-String -inputObject $Files -pattern $Regex -AllMatches).Matches.Count

The expression worked just fine, that was not the issue.
Thanks!


text:
Q: How do I fix this error in my double loop? I am trying to compute the following:

def E_inc_j(tilde_k, x, vecinc):
    n = x.shape[0]
    e = np.zeros((n, 3))

    for i in range(n):
        for j in range(3):
            e[i] = np.exp(1j * tilde_k * x[i]) * vecinc

    return e

def x(n):
    return np.random.randint(100, size=(n, 3))

lam = 0.5
k = (2 * np.pi)/lam
theta = 0
K = k * np.array([[0], [np.sin(theta)], [np.cos(theta)]])
vecinc = np.array([[1], [0], [0]])

E_inc_j_test = E_inc_j(K, x(5), vecinc)
print(E_inc_j_test)

I am getting the error "could not broadcast input array from shape (3,3) into shape (3)" at the line e[i] = np.exp(1j * tilde_k * x[i]) * vecinc.
***** The end result should be a 3N by 1 vector. *****

A: There is no need for a for loop at all:
import numpy as np

k = 10.
theta = 0.3
K = k * np.array([0, np.sin(theta), np.cos(theta)])

x = np.random.randint(100, size=(7, 3))
vecinc = np.array([1, 0, 0])

e = np.exp(1j * K * x) * vecinc
# array([[ 1.+0.j,  0.+0.j,  0.-0.j],
#        [ 1.+0.j,  0.-0.j,  0.-0.j],
#        [ 1.+0.j,  0.+0.j,  0.+0.j],
#        [ 1.+0.j,  0.-0.j, -0.+0.j],
#        [ 1.+0.j,  0.+0.j, -0.+0.j],
#        [ 1.+0.j,  0.-0.j,  0.+0.j],
#        [ 1.+0.j, -0.+0.j, -0.+0.j]])


text:
Q: Civilization 6 turn timer for single player Can you set a turn timer in Single Player in Civ 6, preferably in the Gathering Storms pack. All posts mention turn timer for multiplayer only.

A: They haven't had single player turn timers in the Civilization series for a while now. Your only options for single player turn limiting is to set up the Score Victory or Turn Limit options.
Score Victory - At the end, highest score wins.
Turn Limit - After a set amount of turns 200, 250 (whatever), the game ends.
As you mentioned, turn timers exist in Multiplayer. I'm not sure if this works, you'd have to test it:
You could try to set up a multiplayer game privately, add a bunch of AI and yourself, and start the game without any other human players.


text:
Q: What's better in the following context "let's move to" / "let's go to" / "let's pass to"? What's more appropriate to be written in the presentation (PowerPoint) when I want continue to the next / following slide with a new subject (or sub-subject)?

1) Let's go to (the next issue, the following slide)
2) Let's move to (the next issue, the following slide)
3) Let's pass to (the next issue, the following slide)

A: Go or move or even continue are fine. (Pass sounds unnatural in American English.)
While giving the presentation, you could also say go on, move on or continue on when you have stayed on one point for a long time (maybe there was some discussion about it by the audience) and need to move on to the next slide.


text:
Q: org.apache.tomcat.dbcp.dbcp2.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to oracle.jdbc.OracleConnection connection file
InitialContext initialContext = new InitialContext();
Context context = (Context) initialContext.lookup("java:comp/env");

//The JDBC Data source that we just created
DataSource ds = (DataSource) context.lookup("connpool");
this.con = ds.getConnection();
this.des=ArrayDescriptor.createDescriptor("ARRAY_INT",this.con);

System.out.println("in set array1");
this.arr_to_pass=new ARRAY(this.des,this.con,arr);
this.csmt.setArray(index, this.arr_to_pass);

but i got the following exception

java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp2.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to oracle.jdbc.OracleConnection

A: I guess ClassCastException is thrown at this line
this.con = ds.getConnection();

Your code doesn't show the type of this.con, but it must be an OracleConnection. You can't do that, because connection is a wrapped dbcp connection.
If you want to take Oracle Connection, you have to unwrap it before with BasicDataSource.unwrap(Class<T> iface). You can also use BasicDataSource.isWrapperFor(Class<?> iface) before, to check if the wrapped connection is of Oracle Connection type, to avoid casting exception :)
For example:
if (ds.getConnection().isWrapperFor(OracleConnection.class)) {
    this.con = ds.getConnection().unwrap(OracleConnection.class);
}

A: If you get below error ,make sure you have got connection with database
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to oracle.jdbc.OracleConnection at
If there is no connection then you may get this error.


text:
Q: Hide div and don't show it again I have this code that shows and hides two divs when "onmouseover".
   function hide_visibility(id) {
       var e = document.getElementById(id);
       if (e.style.display == 'none') e.style.display = 'block';
       else e.style.display = 'none';
   }

What I want is: when I do the mouseover it hides the div permanently and when I go over again it won't show anymore.
http://codepen.io/anon/pen/XmXjmx
THANKS!

A: You can just remove any code that sets e.style.display to block.
function hide_visibility(id) {
   var e = document.getElementById(id);
   e.style.display = 'none';
}

http://codepen.io/anon/pen/ojbzbK

A: You could just set the html code to blank like so:
$(document).ready(function() {

    $( "#item" ).mouseover(function() {
        $( "#item" ).html(""); //Set html contents of #item to empty
    });

});

Of course you will not be able to unhide this content again as you have removed the html code. This will not matter though if there will not be a need for the element to be made visible again.


text:
Q: can not print the complete modal body i create a modal with jquery and make it printable but i can't figure out how to print the complete modal body. it only prints a part of it. i tryed to use inline page breaks(i saw it in another post) with jquery every few divs but it doesn't work. Anyone had the same problem? I would like some help
Here is the css i use, which i found from another post
css:
@media print {
    body.modalprinter * {
        visibility: hidden;
    }

    body.modalprinter .modal-dialog.focused {
        position: absolute;
        padding: 0;
        margin: 0;
        left: 0;
        top: 0;
    }

    body.modalprinter .modal-dialog.focused .modal-content {
        border-width: 0;
    }

    body.modalprinter .modal-dialog.focused .modal-content .modal-header .modal-title,
    body.modalprinter .modal-dialog.focused .modal-content .modal-body,
    body.modalprinter .modal-dialog.focused .modal-content .modal-body * {
        visibility: visible;
    }

    body.modalprinter .modal-dialog.focused .modal-content .modal-header,
    body.modalprinter .modal-dialog.focused .modal-content .modal-body {
        padding: 0;
    }

    body.modalprinter .modal-dialog.focused .modal-content .modal-header .modal-title {
        margin-bottom: 20px;
    }
}

The jquery that goes with it
jquery:
    $('.modal.printable').on('shown.bs.modal', function () {
        $('.modal-dialog', this).addClass('focused');
        $('body').addClass('modalprinter');

        if ($(this).hasClass('autoprint')) {
            window.print();
        }
    }).on('hidden.bs.modal', function () {
        $('.modal-dialog', this).removeClass('focused');
        $('body').removeClass('modalprinter');
    });

i Create the modal in html with the modal body empty and on print button i use onClick() The modal body fills from jquery and its content isn`t always the same

Firma etairias

Πελατης:

<button class='close' data-dismiss='modal'>×</button>

              <button id="btnPrint" class='btn btn-default'  type='button' onclick="window.print();">Print</button>  <button class='btn btn-default' data-dismiss='modal' type='button'>Close</button> <button class='btn btn-primary' type='button'>Save changes</button>


text:
Q: Is it possible to write header file without include guard, and without multiple definition errors? Just out of curiosity I wanted to know if is there a way to achieve this.
In C++ we learn that we should avoid using macros. But when we use include guards, we do use at least one macro. So I was wondering if there is a way to write a macro-free program.

A: It's definitely possible, though it's unimaginably bad practice not to have include guards.  It's important to understand what the #include statement actually does: the contents of another file are pasted directly into your source file before it's compiled. An include guard prevents the same code from being pasted again.
Including a file only causes an error if it would be incorrect to type the contents of that file at the position you included it. As an example, you can declare (note: declare, not define) the same function (or class) multiple times in a single compilation unit. If your header file consists only of declarations, you don't need to specify an include guard.
IncludedFile.h
class SomeClassSomewhere;
void SomeExternalFunction(int x, char y);

Main.cpp
#include "IncludedFile.h"
#include "IncludedFile.h"
#include "IncludedFile.h"

int main(int argc, char **argv)
{
    return 0;
}

While declaring a function (or class) multiple times is fine, it isn't okay to define the same function (or class) more than once.  If there are two or more definitions for a function, the linker doesn't know which one to choose and gives up with a "multiply defined symbols" error.
In C++, it's very common for header files to include class definitions.  An include guard prevents the #included file from being pasted into your source file a second time, which means your definitions will only appear once in the compiled code, and the linker won't be confused.
Rather than trying to figure out when you need to use them and when you don't, just always use include guards. Avoiding macros most of the time is a good idea; this is one situation where they aren't evil, and using them here isn't dangerous.

A: It is possible to do so if you ensure the same header file is not being included in the same translation unit multiple times.
Also, you could use:
#pragma once

if portability is not your concern.
However, you should avoid using #pragma once over Include Guards because:

*

*It is not standard & hence non portable.

*It is less intuitive and not all users might know of it.

*It provides no big advantage over the classic and very well known Include Guards.

A: In short, yes, even without pragmas. Only if you can guarantee that every header file is included only once. However, given how code tends to grow, it becomes increasingly difficult to honour that guarantee as the number of header files increase. This is why not using header guards is considered bad practice.
Pre-processor macros are frowned upon, yes. However, header include guards are a necessary evil because the alternative is so much worse (#pragma once will only work if your compiler supports it, so you lose portability)
With regard to pre-processor macros, use this rule:
If you can come up with an elegant solution that does not involve a macro, then avoid them.

A: It is definitely doable and I have used some early C++ libraries which followed an already misguided approach from C which essentially required the user of a header to include certain other headers before this. This is based on thoroughly understanding what creates a dependency on what else and to use declarations rather than definitions wherever possible:

*

*Declarations can be repeated multiple times although they are obviously required to be consistent and some entities can't be declared (e.g. enum can only be defined; in C++ 2011 it is possible to also declare enums).

*Definitions can't be repeated but are only needed when the definition if really used. For example, using a pointer or a reference to a class doesn't need its definition but only its declaration.

The approach to writing headers would, thus, essentially consist of trying to avoid definitions as much as possible and only use declaration as far as possible: these can be repeated in a header file or corresponding headers can even be included multiple times. The primary need for definitions comes in when you need to derive from a base class: this can't be avoided and essentially means that the user would have to include the header for the base class before using any of the derived classes. The same is true for members defined directly in the class but using the pimpl-idiom the need for member definitions can be pushed to the implementation file.
Although there are a few advantages to this approach it also has a few severe drawbacks. The primary advantage is that it kind of enforces a very thorough separation and dependency management. On the other hand, overly aggressive separation e.g. using the pimpl-idiom for everything also has a negative performance impact. The biggest drawback is that a lot the implementation details are implicitly visible to the user of a header because the respective headers this one depends on need to be included first explicitly. At least, the compiler enforces that you get the order of include files right.
From a usability and dependency point of view I think there is a general consensus that headers are best self-contained and that the use of include guards is the lesser evil.

A: Does the non-portable, non-standard
#pragma once

work sufficiently well for you?  Personally, I'd rather use macros for preventing reinclusion, but that's your decision.


text:
Q: Magento2 - catalog product listing collection sort by price with dynamic price calculation product price is calculated dynamically based on certain conditions. while sorting with price it takes only default price not dynamically calculated price. the same issue with the price filter.
I can able to set the calculated price for product using event catalog_block_product_list_collection observer but not able to get products ordered by dynamic price.
<event name="catalog_block_product_list_collection">
    <observer name="product_price_change" instance="[vendor]\[module]\Observer\ProductCollectionDynamicPrice" shared="false" />
</event>

Observer - [vendor][module]\Observer\ProductCollectionDynamicPrice
<?php
namespace [vendor]\[module]\Observer;

use Magento\Framework\Event\ObserverInterface;

class ProductCollectionDynamicPrice implements ObserverInterface
{
    /**
     * set dynamic price
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return $this
    */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
       $productCollection = $observer->getEvent()->getCollection();
       if ($productCollection instanceof \Magento\Framework\Data\Collection) {
          $productCollection->load();
          $this->calculatePrice($productCollection);
       }

       return $this;
    }

    /**
     * set dynamic calculated price to product collection
     *
     * @param ProductCollection $collection
     * @return $this
    */
    public function calculatePrice($collection) {

     foreach ($collection as $key => $item) {
        $price = 100;  // here my cuustom logic to calculate dynamic price based on conditions
        $item->setMinPrice($price);
     }

     return $collection;

   }
 }

If I echoing min_price then able to get updated min_price but not able to get correct product orders collection sort by price.
Please anyone can help for the issue?

A: I assume, In Category page you are trying to sort by the price and not getting the correct order while you want your prices to be displayed as well as used in sorting.
etc/frontend/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
        <plugin name="sortby_extend_default_sort_filters" type="Vendor\Module\Plugin\Toolbar" sortOrder="99" />
    </type>
</config>

Vendor\Module\Plugin\Toolbar
namespace Vendor\Module\Plugin;

use Zend\Filter\Boolean;
use Magento\Store\Model\StoreManagerInterface;

/**
 * Product list toolbar plugin
 */
class Toolbar
{
    protected $test;
    protected $storeManagerInterface;
    protected $_flag = true;

    public function __construct(StoreManagerInterface $storeManagerInterface)
    {
        $this->storeManagerInterface = $storeManagerInterface;
    }

    public function aroundSetCollection(\Magento\Catalog\Block\Product\ProductList\Toolbar $subject,
                                        \Closure $proceed,
                                        $collection
    )
    {
        $currentOrder = $subject->getCurrentOrder();
        $result = $proceed($collection);
        $pageSize = $collection->getPageSize();
        if ($pageSize) {
            $collection->clear();
        }
        if ($currentOrder && $currentOrder == 'price' && $this->_flag == false) {
            //Get current store information
            $currentStore = $subject->getCollection()->getStoreId();
            $currency = $this->storeManagerInterface ->getStore($currentStore)->getCurrentCurrencyCode();

            //add you custom calculation here in the result/collection
            $subject->getCollection()->getSelect()->columns(
                array(
                    'new_price' => new \Zend_Db_Expr("IF (
                    YOURCONDITION IN DB QUERY,
                    TRUE Value,
                    False Value)"))
            );
            //to reset sorting order
            $subject->getCollection()->getSelect()->reset(\Zend_Db_Select::ORDER);
            $subject->getCollection()->getSelect()->order(new \Zend_Db_Expr('`new_price` ' . $subject->getData('_current_grid_direction')));
        }
        $this->_flag = false;
        return $result;
    }
}

You've to add your logic using SQL Query/Operators.


text:
Q: Will the plane of oscillation of a pendulum change if I rotate the suspension point I'm having trouble understanding Foucault pendulum and from that I've extracted one of my doubt and here it goes:
A pendulum on a fixed platform is shown
Now if we rotate the platform as shown

Will the plane of oscillation change or be the same? ( The suspension point doesn't coincide with the axis of rotation)?

A: Actually, the idea for the setup we call 'Foucault pendulum' occurred to Leon Foucault in the following manner: he had clamped a long rod in the chuck of a lathe, he twanged it, and when he rotated the chuck the plane of vibration did not rotate. Foucault surmised that the momentum of the vibrating motion is not in any way bound to the physical orientation of the rod. In effect the momentum of the vibrating rod was behaving in accordance with Newton's first law. Unless acted upon by a force the momentum vector of a moving object keeps pointing in the same direction.
I did a search on youtube, and much to my delight I discovered a youtube video for this subject, titled: 'Scientic contributions of Leon Foucault', by dr Matt Nehring. Dr Nehring clamps the vibrating rod in the chuck of a drill
I assume that the reason that Foucault ended up with a gravity pendulum was that a gravity pendulum allows a setup with a large amplitude and large period of oscillation.
Any oscillation will have the property that the orientation of the momentum of the oscillation is not in any way bound to the physical matter that is vibrating.
The rotation state sensor in a smartphone has this type of rotation state sensing as its operating principle. It's not necessarily a vibrating rod, but some elastic part is oscillating, and the momentum of the oscillation tends to keep pointing in the same direction. (Depending on the build quality there will be some drift, but for the purpose of assisting navigation the sensors are quite sufficient.) The rotation state sensor in a smartphone is generally referred to as 'the gyroscope' but it isn't a gyroscope in the sense of consisting of some spinning wheel, suspended in gimbal mounting. The rotation state sensor of a smartphone is of the vibration type.

About why a larger Foucault setup is better:
The Foucault effect is very small, it's easily swamped by other effects. For instance, if the wire has a direction of bending where it is less bendable - and hence will have a direction of bending perpendicular to that where the wire is more bendable - then the force that tends to push/pull the pendulum bob back to midpoint will not be exactly the same in all directions, which would mean that the period of oscillation would not be the same in all directions, and that has the potential to swamp the Foucault effect. All the effects that unless prevented will swamp the intended effect are collectively referred to as 'parasitic effects'. In the case of a Foucault pendulum: the larger the pendulum, the less troublesome the parasitic effects.


text:
Q: Can you explain this method of finding prime numbers in javascript function getPrimes(max) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
    if (!sieve[i]) {
        // i has not been marked -- it is prime
        primes.push(i);
        for (j = i << 1; j <= max; j += i) {
            sieve[j] = true;
        }
    }
}
return primes;
}

I understant that i keeps track of all numbers.
i don't understand...!sieve[i],j = i << 1; & what is really happening.
Just to be Clear.. Prime Number is something that is only divisible by itself or by one.

A: It's called the Sieve of Erathestenes and it's an efficient way of finding all prime numbers between zero and some upper limit integer.
j = i << 1

This is a bit shift operation. It shifts an integer 1 bit to the left. Because binary is base two, this is equivalent to multiplying by two. In decimal, the equivalent operation would be shifting, say, 1 to the left and bringing in a zero to the right. It's base ten, so you end up with 10 (ten times one.)
I don't believe the implementation you show is optimal. The limit to the i value can be lower -- something like sqrt(max).
You can easily find some really nice animations online of this algorithm that show you what's going on in quite an intuitive way.

A: It uses the Sieve of Eratosthenes.
From Wikipedia ( http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes )

A prime number is a natural number which has exactly two distinct
  natural number divisors: 1 and itself.
To find all the prime numbers less than or equal to a given integer n
  by Eratosthenes' method:

*

*Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).

*Initially, let p equal 2, the first prime number.

*Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of
  p: 2p, 3p, 4p, etc.; note that some of them may have already been
  marked.

*Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal
  this number (which is the next prime), and repeat from step 3.

  When the algorithm terminates, all the numbers in the list that are
  not marked are prime. The main idea here is that every value for p is
  prime, because we have already marked all the multiples of the numbers
  less than p.


text:
Q: How to auto refresh a section of a page I have a part of a page that has live data in it, I was thinking of just refreshing the page every couple of minutes, but that isn't right because of other elements of the page.
How can I do it? What language can I use to do this, what's easy to do and what isn't, what works well and what doesn't. Maybe some clear tutorials or even code examples.
I'd live to do this in something like PHP, but don't have a clue where to start, from a bit of research i see that Javascript and Ajax seem to be the standard for this but my knowledge of these languages aren't up to scratch.
Thanks for the time and help people.
Oh, the data that is being displayed is coming from a database if that's any help.
Thanks again.

A: The easiest method doesn't even involve PHP or JavaScript.  You can do it with an <iframe> in plain HTML.  The iframe loads an HTML or PHP page with the appropriate refresh header and it refreshes itself.
Main HTML page:
<html>
<head></head>
<body>
   static content

    <iframe id='dynamic-content' src='refreshing.php' />
</body>
</html>

refreshing.php page:
<html>
<head>
  <!-- refresh every 5 seconds -->
  <meta http-equiv="refresh" content="5">
</head>
<body>
  dynamic content
</body>
</html>

Note that <meta http-equiv="refresh">  is discouraged for general refreshing a whole page, but it is pretty safe to use inside an iframe which must be constantly refreshing itself.

A: You cant really execute a live refresh for page components in PHP, AJAX is the most common means (Asynchronous Javascript And Xml)- which uses Javascript to poll other scripts (can be .php pages) which then return predefined output based on the request- this output can be content to inject into a page, or data which can then be interpreted by your page for another action.
In this instance, your .php page would include JS (javascript) in the head, whether linked or inline, which would contain details for launching an AJAX request- namely, how often or on what trigger (button press etc), by what means (POST or GET), what is sent (any other variables you wish), what the target script is (the script which will handle the request and output your required content/data), and what to do when the response is recieved (i.e. which element on the page should be updated with the response).
A little about AJAX:
http://webdesign.about.com/od/ajax/a/aa101705.htm
http://webtrends.about.com/od/web20/a/what-is-ajax.htm
Likely the simplest way to begin is to use a pre-existing Javascript library like the ubiquitous jQuery (jquery.com), there are thousands of tutorials out there for it, and though you will need to do some Javascript programming, the library has meant that you can rely on fairly simple syntax to do so (as simple as $('#myelement').load('mypage.php')):
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
http://www.sitepoint.com/ajax-jquery/
http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
In simple terms:

*

*You have your php page with the element that needs updating (page A)

*Build another php script which outputs the content you want 'refreshing', e.g. the latest news stories, each time it is run (page B)

*Link to the jQuery library in your header section (page A)

*Write a simple jquery function in the header section of page A, which says every X seconds/minutes, run an AJAX request to fetch the content of page B and insert into an element (DIV) within page A

A: You could use a Javascript library such as jQuery and do something like the following simplified example:
$("document").ready(function(){
  var interval = setInterval(refresh_box(), 60000);
  function refresh_box() {
    $("#myDiv").load('path/to/databasepage.php');
  }
} /*<= The closer ) bracket is missing in this line*/

and in your path/to/databasepage.php page you can have your select query and echo the results out.
What this does is sets a timeout to call a function (in this case, refresh_box() ) every 60 seconds (which is 60,000 miliseconds) and loads the data from path/to/databasepage.php in to your div with the id myDiv.
edit:
If you want to stop the auto-refresh you can bind an element to clear the interval by doing the following:
// assuming you have a clickable element
// (typically a button or so) id called 'stop_refresh'
$("#stop_refresh").click(function(){
  clearInterval(interval);
}

A: it's really a large question.
The most common way would be to use AJAX but you can also use a javascript database as TaffyDB - The JavaScript Database (never used it so i can't really speak about it).
Anyway, the easiest way would be to use JQUERY.


text:
Q: Reducing expression to simplest form involving variables in radicals In my notebook, I obtain an expression that I can't figure out how to reduce to it's simplest form. I've recreated it below to show what I am trying to simplify.
Iratio2to1 = -(L1/Sqrt[L1 L2])
L2=(N2/N1)^2*L1
Assuming[{L1, L2} > 0 && {L1, L2} \[Element] Reals,Cancel[Iratio2to1]]

this returns:
$$-\frac{L1}{4\sqrt{L1^2}}$$
I cannot figure out how to have Mathematica reduce this to $-\frac{1}{4}$.
I've tried Simplify, FullSimplify, Cancel, now Assuming... I dont' get it!

A: Because it's equal to:
$$-\mathrm{sgn}(L1)\frac{1}{4}$$
You can approach in multiple ways:
Simplify for real L1:
FullSimplify[Iratio2to1, Element[L1, Reals]]
(* -(Sign[L1]/4) *)

Or for positive L1:
FullSimplify[Iratio2to1, L1 > 0]
(* -(1/4) *)

But for complex L1 it won't cancel:
FullSimplify[Iratio2to1, Element[L1, Complexes]]
(* -(L1/(4 Sqrt[L1^2])) *)

A: Not sure why your Assuming doesn't work, but this works:
$Assumptions = L1 > 0

Simplify[-L1/(4 Sqrt[L1^2])]
(* -(1/4) *)


text:
Q: Errors while compiling Varnish 3 on ubuntu 14.10 I am new to linux and ubuntu and it is my first time to compile anything on linux. I am trying to compile varnish on ubuntu 14.10, but i got the following errors:
   Traceback (most recent call last):
  File "/usr/bin/rst2man", line 21, in <module>
    from docutils.core import publish_cmdline, default_description
  File "/usr/lib/python2.7/dist-packages/docutils/core.py", line 20, in <module>
    from docutils import frontend, io, utils, readers, writers
  File "/usr/lib/python2.7/dist-packages/docutils/frontend.py", line 41, in <module>
    import docutils.utils
  File "/usr/lib/python2.7/dist-packages/docutils/utils/__init__.py", line 20, in <module>
    import docutils.io
  File "/usr/lib/python2.7/dist-packages/docutils/io.py", line 18, in <module>
    from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput
  File "/usr/lib/python2.7/dist-packages/docutils/utils/error_reporting.py", line 47, in <module>
    locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
  File "/usr/lib/python2.7/locale.py", line 543, in getdefaultlocale
    return _parse_localename(localename)
  File "/usr/lib/python2.7/locale.py", line 475, in _parse_localename
    raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8
Makefile:735: recipe for target 'vmod_std.3' failed
make[3]: *** [vmod_std.3] Error 1
make[3]: Leaving directory '/home/altaf/Desktop/varnish3/Varnish-Cache/lib/libvmod_std'
Makefile:389: recipe for target 'all-recursive' failed
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory '/home/altaf/Desktop/varnish3/Varnish-Cache/lib'
Makefile:489: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/altaf/Desktop/varnish3/Varnish-Cache'
Makefile:397: recipe for target 'all' failed
make: *** [all] Error 2

I have read the following article, but it did not helped.
Unable to compile latest Varnish on Debian 6
For installation, i followed these steps:
https://www.varnish-cache.org/docs/3.0/installation/install.html#compiling-varnish-from-source
Kindly help me with this issue.
Thank you

A: You are probably not using a UTF-8 locale on your system.
You can temporarily work around this in your shell by setting your locale to a UTF-8 locale, for instance:
export LC_ALL=ur_PK.UTF-8
export LANG=ur_PK.UTF-8


text:
Q: Tomcat webapp can't find file in WebContent? I've lots of jsp files in the WebContent folder and also a user folder there.
When the user navigates to a a file in the user folder and then tries to navigate to a file in the WebContent folder again the app crashes.
I've tried getRealPath() but no good.
Any help would be much appreciated.


text:
Q: XSLT nested selects I am relatively new to xslt I need to select the comments elements from according to which post using pid of the current post
The part XSLT I am having problem with
<xsl:for-each select="posts/post">

<xsl:value-of select="ptitle"/>

        <xsl:value-of select="ptext"/>
        <xsl:variable name="pid" select="@pid" />

</xsl:for-each>

The XML code
    <posts>
         <post pid="p2">
            <ptitle>APPLICATIONS OF THE FUTURE</ptitle>
            <pfeatureimage>aig.jpg</pfeatureimage>
            <ptext xml:lang="en">just text </ptext>
            <pdate>25062013</pdate>
            <pimg>future.jpg</pimg>
            <pimg>future.jpg</pimg>
            <pimg>future.jpg</pimg>
            <pauthorid>a3</pauthorid>
        </post>
    </posts>

    <comments>
        <comment cid="c1">
            <pid>p2</pid>
            <uid>u2</uid>
            <ctext>other t</ctext>
            <likes>5</likes>
            <dislikes>1</dislikes>
        </comment>
                <comment cid="c2">
            <pid>p3</pid>
            <uid>u2</uid>
            <ctext>bogsg</ctext>
            <likes>5</likes>
            <dislikes>1</dislikes>
        </comment>
  </comments>

A: The way to approach any cross-referencing problem like this in XSLT is to use a key.  You put the key definition at the top-level of your stylesheet (outside any templates):
<xsl:key name="commentsByPid" match="comment" use="pid" />

The match expression determines which nodes to look at, and the use is a path that is evaluated relative to each matched node to determine the key value (so in this case it will take the string value of the pid element inside each matched comment).
With this key definition you can efficiently look up all the comments that match the current post's pid attribute using the key function:
<xsl:for-each select="posts/post">

<xsl:value-of select="ptitle"/>

        <xsl:value-of select="ptext"/>
        <xsl:for-each select="key('commentsByPid', @pid)">

        </xsl:for-each>

</xsl:for-each>

A: For a single comment, replace your variable definition
<xsl:variable name="pid" select="@pid" />

by
<xsl:value-of select="//comments/comment[pid=current()/@pid]/ctext" />

If you have multiple comments, you can try
<xsl:variable name="pid" select="@pid" />
<xsl:for-each select="//comments/comment[pid=$pid]">
    <xsl:value-of select="ctext" />
</xsl:for-each>


text:
Q: How to add array by hidden type in cake php? I want to carry an array from one form to another form by hidden data type in cake php.
I don't know how many number will come. So, I can not know how many number.
e.g.
Example in PHP:
foreach($rNo as $no){
    echo "<input type='hidden' name='no[".$no."]' value='".$no."'>";
}

How do I translate this code to CakePHP $form->hidden()?

A: Serialize the array and store it.

A: For hidden input types you just use
$form->input('Model.field', array('type' => 'hidden'));
In your controller you just set the data eg $this->data['Model']['field'] = 'value';
For multiple fields you could loop through the $this->data array.
Your this->data would look like $this->data['Model'][0]['field'], $this->data['Model'][1]['field']
foreach($this->data['Model'] as $key => $data){
    $form->input('Model.'.$key.'.field', array('type' => 'hidden'));
}

It doesn't have to be $this->data, you could use any variable. But $this->data would automatically fill the input fields.
But you could just pass the value too if you wanted to. $form->input('Model.field', array('type' => 'hidden', 'value' => 'myvalue'));


text:
Q: Convergence of the arguments of a convergent sequence Prove that if the sequence $z_{n}$  converges to a nonzero limit $A$ which is not a negative real number, then $\arg z_{n}\to \arg A$, where finite number of terms of $z_{n}$ which may wanish are ignored and $\arg z $ is $-\pi< Arg z \le \pi$
My solution:
by definition, there is $n_{0}=N(\epsilon)$ for which $|z_{n_{0}}-A|\le\epsilon$. So there is a neighborhood $N(A,\epsilon)$ which intersection with real negative axis is empty. So all $z_{n}$ with $n\ge n_{0}$ will be in this neighborhood. Let $\theta=|\arg z_{n}-\arg A|$ and $\epsilon<|A|$ . So $\epsilon=|A|\sin\theta$ or $\theta=\arcsin\frac{\epsilon}{|A|}$. And it goes to $0$ togehter with $\epsilon$.
Not sure if this is ok.

A: You have the assumption that $z_n$ converges to $A$ and $A$ is not the origin or on the negative real axis. You need to show that given $\epsilon>0$ there is $N$ such that $n>N$ implies $\arg(a_n)$ is within epsilon of $\arg(A)$. It's equivalent to show there is a $\delta$ such that if $z$ is within $\delta$ of $A$ then $\arg(z)$ is within $\epsilon$ of $\arg(A)$.
To do this the actual delta you use might need to be the min of some things. So first we can draw a circle around $A$ of radius say $\epsilon_1 <= \epsilon$, but such that the entire disk inside the circle is also away from the negative x axis. Next consider all the angles formed by points in this disk; a diagram reveals they will be within $\arcsin(\epsilon_1/|A|)$ of arg(A).
So if z is within $\arcsin(\epsilon_1/|A|)$ of A, we have the desired closeness
$|arg(z)-arg(A)|<\epsilon$.
We do need to use monotonicity of $\arcsin(x)$ here at the end, and continuity, and $\arcsin(0)=0$.