text:
Q: Airport Time Capsule port forward magic packet (Wake-on-LAN) I have an Airport Time Capsule connected to my internet service provider and a Linux server wired to one of the LAN ports on my airport. I want to be able to use the Wake-on-LAN feature to wake my Linux box from sleep/suspend from anywhere -- not just from my local network.
First approach that partially works
I've gone into Airport Utility and set up a stable IP based on the MAC address of my Linux box's Ethernet controller. I then set up port forwarding for magic packets on public UDP port 29999 to private port 9 and the 10.0.1.x address I assigned to my linux box.
This works from both outside and inside my network, but only for about 15 minutes after the linux box sleeps. After that I guess the Airport loses track of it and doesn't know where to route the packet.
Second approach that seems like it would work
If I forward the magic packet to the broadcast IP for my network, 10.0.1.255, then the box does wake even after a long time has passed...at least that works from my local network where I can tell the wake program on my Mac or WOL app on my phone which address to send the packet to.
But I can't test it from outside my network because the Airport Utility won't let me forward to .255.
Fix for this
I found several posts (which I can't find again today) that say if you can't forward to the broadcast IP at 10.1.0.255 to set the subnet mask to 255.255.255.128 and then forward to 10.1.0.127, but Airport Utility doesn't have anywhere to set the subnet mask.
I found another post yesterday (which I can't find today) which suggested exporting the Airport Utility configuration file and editing the subnet mask in there and reuploading. I did that, but it didn't work.
TL;DR
I need to port forward a Wake-on-LAN magic packet from the Internet, through my Airport Time Capsule to the broadcast IP of my private local network.
The broadcast address is 10.0.1.255, but Wake-on-LAN won't let me enter 255.
How can I wake my Linux box from the Internet? Is there a way to send the packet to the broadcast IP? Is there some other solution that changing the subnet mask?
Is there some other solution that I should be thinking about?

A: The configurability of the Apple routers is (for some advanced use cases like the one you describe) perhaps a bit lacking. I hope someone else can provide a definitive answer as to whether it will be possible to actually broadcast that WOL packet using only the router!
I propose to you an alternative that is slightly more complex (and therefore not ideal), but to me feels like a robust approach that will work in all home network environments, so that you can avoid relying on any advanced capabilities of the network hardware.
The idea would be to set up a machine on the LAN (such as a $5 Raspberry Pi whose power draw will likely be comparable to that of your linux server in S3 suspend) that is always running and which you may access remotely. However this is done is entirely up to you, you may connect them via WiFi or Ethernet and with static or DHCP addressing, and this is what I mean by flexibility, you may have to do specific configuration to deal with the NAT traversal and security aspects. As it applies to your situation (similarly to you, I have an Apple router as well) you'd probably just assign this machine's MAC to a static IP and forward the ports needed for remote access, such as port 22 for SSH, port 3389 for Windows RDP, port 5900 for VNC, and that's about it. It's hard to beat something like using SSH with a private key for passwordless secure access.
The other piece that will be relevant is if you have residential service from your ISP, your router's IP will be dynamic, and a service should be set up to periodically check that this address has not changed. I implement this myself using a cronjob and a python script that sends emails to me, but you can readily find tools to handle that job. Indeed, this aspect of residential internet service is hard to address without a programmable client machine, although I'd imagine that highly configurable routers might offer equivalent functionality.
Once you set things up to allow you to reliably and securely access your machine from the wider internet, you can now use that to broadcast the WOL packet on the LAN, at which point you may connect to the woken-up host via the usual means (which may also require configuration).
I just like this approach because it's so powerful and you can administer many more aspects of your home remotely once you have this kind of setup.
I have more than enough raspberry pi's but I already have desktops (which happen to run Windows) that I keep running 24/7 at home, so when I need to send a WOL to my macbook (if it's at home, it will be sleeping) I can just use any of those machines to do the job since they're going to be up all the time.
But if you have a small and low power machine you can just set it and forget it on the network and it will just always be there for you, that peace of mind is really great.


text:
Q: User input in PHP Im new to PHP and I am trying to read user input in my code but im getting the error: Use of undefined constant STDIN - assumed 'STDIN'
<?php
    echo "
Armstrong number
";
    echo "Enter number: ";

   fscanf(STDIN, "%d", $input); //Error Line

    $n=$input;
    $sum=0;
    while($n != 0)
   {
       $rem = $n % 10;
       $sum = $sum + $rem*$rem*$rem;
       $n = $n / 10;

   }
    if ($input == $sum)
    echo $input." entered is an armstrong no.";
    else
    echo $input." isnt an armstrong no.";
?>
``

A: Because your conts "STDIN" isn't defined. For example, you can try this:
    $handle = fopen("your_file.txt", "r");

    define('STDIN', $handle);

and your code below

A: You are trying to check Armstrong number through browser.
Run your code through CLI.

redpajama_set_name: RedPajamaStackExchange


text:
Q: in eclipse, how to distinguish "run configurations" and "debug configurations" when adding self-define UI I'm a eclipse plugin developer. I have added a new tab in both "Run Configurations" and "Debug Configurations" (code is at one place for the two configurations). But I want to make a textbox invisible in "Run Configurations" and visible in "Debug Configurations". Right now, I have found one way: "parent.getShell().getText()" can return "Run Configuraions" or "Debug Configuratios" Strings for me. But are there any better ways to distinguish whether I'm in "Run Configurations" or "Debug Congurations"? The "getText()" way seems to be very not formal.

A: This is the current 'mode' of the configuration represented by an id (and also by the ILaunchMode interface).
You can get the current mode id string from the ILaunchConfigurationDialog by calling the getMode() method. For debug the value will be the string defined by ILaunchManager.DEBUG_STRING.
In a launch configuration tab extending AbstractLaunchConfigurationTab you get the launch configuration dialog by calling getLaunchConfigurationDialog.


text:
Q: How to open new window with backing bean? I am using JSF for my project front end.
How I can I open a new window with backing bean?

A: Set target="_blank" on the <h:commandLink> or <h:form>.
E.g.
<h:form>
    <h:commandLink value="Open in new window" action="#{bean.action}" target="_blank" />
</h:form>

or
<h:form target="_blank">
    <h:commandButton value="Open in new window" action="#{bean.action}" />
</h:form>

A: In addition to BalusC answer.
Kind of hacky solution in situation when:

*

*commandLink cannot be used in UI (because of page styling or any other reason)

*target of the form cannot be changed
<!-- Group and render them together.-->
<h:panelGroup rendered="#{mybean.showButton}">

<!-- Visible and clickable commandButton. No action, just onclick js event.-->
<h:commandButton value="My Commandbutton"
onclick="document.getElementById('myForm.realTargetBlankLink').click();"/>

<!-- Invisible link. Action, target _blank.-->
<h:commandLink id="realTargetBlankLink" action="#{myBean.myDesiredAction}"
target="_blank"/>

</h:panelGroup>


text:
Q: Ubuntu 18.04.1 Freezes randomly I use a Asus P553M processor Intel® Celeron(R) CPU N2940 @ 1.83GHz × 4, Graphics intel Bay Trail, Memory 3,7 GiB.
It freezes randomly, I've tried ubuntu gnome, ubuntu 18.04, Xubuntu....
I don't have any windows installed. I erase everything and install linux only...
I need help!!!
Thanks!


text:
Q: JavaScript binding and callbacks I'm trying to calculate instantaneous velocity of the mouse.
To do that, I'm creating x1 = e.pageX to store starting coordinate, and t1 = new Date()... to get starting time. I then want to do a callback after 100 m/s when the mouse has stopped moving, and calculate the new pageX and t2... This was I can get the slope for that given time interval... x2 - x1/t2 - t1
Issue: When I call the callback, I'm trying to use bind to bind the context of the event e (mousemove(function(e)) to the callback. Am I doing it incorrectly?
        var mY = 0,
            mX = 0,
            slope = 0,
            vel = 0,
            thread;

        $(document).ready(function(){

            $(".box").mousemove(function(e) {
                getDirection(e);

                var x1 = e.pageX,
                    t1 = new Date().getTime();

                clearTimeout(thread);
                thread = setTimeout(callback.bind(this), 100);

            });
        });

        function callback(e) {
            var x2 = e.pageX,
                t2 = new Date().getTime(),
                xDist = x2 - x1,
                time = t2 - t1;

            log(x2 + ", " + x1);
            slope = xDist/time;
            log("mouse has stopped");
        }

A:
Am I doing it incorrectly?

Yep, you are never passing e to the callback. Looks like you want
callback.bind(this, e)

Inside the event handler, this refers to the DOM element the handler is bound to, not the event.


text:
Q: Изменение переменной в методе с @property python Пытаюсь создать простой файл setting, в котором при изменении переменной GLOBAL_VAR_property сразу идет запись в базу данных, можно ли решить эту задачу с @property?
# settings.py
class Global_Settings:
    def __init__(self):
        self.GLOBAL_VAR = 'test'

    @property
    def GLOBAL_VAR_property(self):
        # запись в базу
        return 'test2'

settings = Global_Settings()

как мне теперь изменить переменную для @property?
# other.py
from settings import settings

settings.GLOBAL_VAR = 'new'
# могу ли я так же сделать для проперти метода, чтобы менялась переменная и сразу запись была?
settings.GLOBAL_VAR_property = 'new'

A: Используйте property setter:
class Global_Settings:
    def __init__(self):
        self.GLOBAL_VAR = 'test'

    GLOBAL_VAR_property = property()

    @GLOBAL_VAR_property.getter
    def GLOBAL_VAR_property(self):
        return self.GLOBAL_VAR

    @GLOBAL_VAR_property.setter
    def GLOBAL_VAR_property(self, value):
        # Сюда вставьте запись в базу
        print('Новое значение: ' + str(value)
        self.GLOBAL_VAR = value

https://pythonz.net/references/named/property/ (См. последнюю часть статьи. А в первой части есть альтернативный вариант реализации)


text:
Q: Dynamic Routing and Component creation based on route I want to have a couple of "overview" pages for sections my app, that will all be triggered on the root of that section.
so localhost/hi should display component HiOverview
localhost/he should display component HeOverview
as there are multiple of those, i want to avoid assigning the component to a const, then reusing it in a route. instead i want to handle all that in a single dynamic route.
BUT i'm struggling with the creation of the Components in the beforeEnter hook.
each route object expects a component... but i just want to decide the component depending on route. (sectionsWithOverview is a simple array of strings containing the names of routes where i want an overview displayed
const router = new Router({
  linkActiveClass: 'active',
  mode: 'history',
  routes: [
    { path: '/:section',
      component: Placeholder,
      beforeEnter: (to, from, next) => {
      const section = to.params.section

      // how can i use this in the next() call?
      // const View = () => import(/* webpackChunkName: 'sectionView' */ `Components/${section}/${section}Overview`)

      if (sectionsWithOverview.includes(to.params.section)) {
        next({ name: `${to.params.section}Overview` })
      } else {
        next()
      }
    },
}

can you guys help me? how can i conditionally assign a component onBeforeEnter, and then route to that exact Component?
it works if i declare each SectionOverview beforehand, but that makes my whole idea pointless.
Thanks for any help :)

A: I made something similar with a project but instead I used beforeRouteUpdate
Here is an example of how it works. On route.js simply define your dynamic route
const router = new Router({
  linkActiveClass: 'active',
  mode: 'history',
  routes: [
    {
      path: '/:section',
      component: Placeholder,
      name: 'placeholder'
    },
}

Then in your component (I assume Placeholder.vue) in your HTML add this line of code
<transition name="fade" mode="out-in">
    <component :is="section" key="section"></component>
</transition>

then in your JS add the beforeRouteUpdate hook and define all your components that will match your route section param.
import he from './heOverview.vue'
import hi from './hiOverview.vue'

beforeRouteUpdate (to, from, next) {
  // just use `this`
  this.section = to.params.section
  next()
},
components: {
  he,
  hi
},
data () {
  return {
    section: ''
  }
}

So when a user navigate to localhost/he the heOverview.vue component will be loaded. The only thing you have to make sure is that the section param's value should match an specific view if not an error will be produced
If you need more info about how this work, read
https://v2.vuejs.org/v2/guide/components-dynamic-async.html
https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards


text:
Q: set Date to DatePicker and listener for value changing and removing AR prefix I'm using DatePicker with my country timeZone year month day are okay but there is AP prefix on picker which I don't need how can I get ride of it ?
I have searched a lot but there is nothing about it
update :
    override func viewDidAppear(_ animated: Bool) {
        datepicker2.datePickerMode = .date
        datepicker2.timeZone = TimeZone(identifier: "IRST")
        datepicker2.calendar = Calendar(identifier: .persian)
        datepicker2.locale = Locale(identifier: "fa_IR")
        datepicker2.date=self.minDate
        datepicker2.addTarget(self, action: Selector("datepickerAction"), for: .valueChanged)
}

I need my native date and my time zone and this is datePicker initializing
func datepickerAction(){

     let date = self.datepicker2.date

let components = Calendar.current.dateComponents([.month, .day,.year], from: date)
let hour = components.month
let minute = components.day
    let yr=components.year
    print(hour,minute,yr)
}

this is the listener which is not working properly not change the date. each time print the same date.
screenshot
http://uploadkon.ir/2Ui

A: I think you have to pass the parameter in the function like this...
override func viewDidAppear(_ animated: Bool) {
        datepicker2.datePickerMode = .date
        datepicker2.timeZone = TimeZone(identifier: "IRST")
        datepicker2.calendar = Calendar(identifier: .persian)
        datepicker2.locale = Locale(identifier: "fa_IR")

        datepicker2.addTarget(self, action: #selector(datepickerAction(_:)), for: .valueChanged)
}

So, now you can get the date every time that change in the picker...
func datepickerAction(_ sender: UIDatePicker){

     let date = self.datepicker2.date

let components = Calendar.current.dateComponents([.month, .day,.year], from: date)
let hour = components.month
let minute = components.day
    let yr=components.year
    print(hour,minute,yr)
}


text:
Q: Adding Soft and Hard Deadlines to the Linux Scheduler I am trying to create two new system calls for the Kernel, to set and get deadlines.
I know the general concept, but I am struggling as to what the .c files will look like.
Could anyone give me some examples as to how, given a process's pid, give it a soft/hard deadline.
Also, if possible I'd like to know how I can examine if a process is child of another process or not.


text:
Q: "Recent Badges" list is displayed without margins on "Home" page When the "Hide Hot Network Questions" preference is enabled (i.e. HNQ sidebar is hidden), we see "Recent Tags" and "Recent Badges" in the homepage instead of the HNQ.
However, the "Recent Badges" list is displayed with no margins.
ex.) https://meta.stackexchange.com/

I think that the appropriate margins were set in the past.
cf.) Where did the hot network questions go? Are they gone forever, or is this just A/B testing?

A: This has been fixed and the fix is live in production. Thanks for the report!


text:
Q: Failed to start Disk Manager, System Logined service, etc Связано с темой Удалил rfremix-relese при попытке обновления
Мне удалось добиться следующего:
Я скачал с другой ОС некоторые файлы: репозитории типа fedora-release и тому  подобное, установил их, также сделал:
dnf install anaconda

как и предполагалось она потребовала много зависимостей включая lmv. После установки перегрузил систему, загрузка пошла, но... так и не закончилась - система висла на этом экране. Более детальный анализ показал, что выводятся сообщения о невозможности загрузить некоторые сервисы: Disk Manager, System Logined service и многие другие. Я так понимаю, что причина в этом.
SELinux отключён, по крайней мере в файле конфига стоит disabled
Да, если важно: RFRemix 64 bit, 28 version


text:
Q: Text appears in higher part of a div I currently have the following html.

ASDF

The css for .customOnePreviewText is:
.customOnePreviewText {
  margin: 0;
  position: absolute;
  top: 50%;
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
  font-size: 48px;
}

The challenge I'm having is that the text appears in the upper part of the div.  I'd like the type to be centered in the div meaning not a bottom part off or the entire div to just be the size of the text.  This is what I have now.

the black area is the div highlighted.

A: Instead of using the translate within the inner div, you could adjust the margin from 0 to 0 25% (0 top/bottom, 25 left/right) to center the writing. (see snippet - although you can't see the image in the snippet, you get the idea)

.customOnePreviewText {
  margin: 0 25%;
  position:absolute;
  top: 50%;
  font-size: 48px;
}

ASDF

An alternative to the above would be to use translateX(50%), but I think the above is a simpler solution. Your code seems to show confused usage of translateY (which moves the text down rather than across).
Yet another solution would be to set a left position.
I would highly recommend switching to using relative position as you may find the task of positioning the text and image a lot simpler - just my tuppence.
Good luck!

A: Are you sure there's no more html/css that might be affecting it? I copied the code you've provided and can't seem to reproduce the issue.
Have you tried using flexbox? Hard to say if this will solve your problem as I couldn't reproduce it but should make your life easier in any case.

.customOnePreviewText {
  margin: 0;
  position: absolute;
  font-size: 48px;
  background-color:white;
}

#img_preview_text_container {
  position: absolute;
  font-family: Oklahoma;
  width: 376px;
  height: 75px;
  color:rgb(255, 0, 0);
  background-color:black;
  display:flex;
  align-items: center
}

ASDF


text:
Q: How to stop a stream after .pipe()? const speaker = new Speaker({
          channels: 2,
          bitDepth: 16,
          sampleRate: 44100,
          device: null,
        });

stream.pipe(speaker);

I need it for break playing sound. Stream is instance of Readable.

A: stream.pipeline which claims to handle "forwarding errors and properly cleaning up and provide a callback when the pipeline is complete."
Syntax
stream.pipeline(...streams, callback)

*

*…streams: These are two or more streams which are to be piped together.

*callback: This function is called when the pipeline is fully done and it shows an 'error' if the pipeline is not accomplished.

Here is a link to documentation.


text:
Q: How to use ANativeWindow_setBuffersDataSpace in NDK? When I use ANativeWindow_setBuffersDataSpace in NDK,it prompts no error.But I build the project,the logcat shows that
"undefined reference to ANativeWindow_setBuffersDataSpace'clang++: error: linker command failed with exit code 1 " . However I can find this API in native_window.h "__INTRODUCED_IN(28);"and I set minsdk 28.

A: Add libnativewindow.so to linked libraries, e.g. if you use CMake:
add_library(MainActivity SHARED MainActivity.cpp)
target_link_libraries(MainActivity
        android
        native_app_glue
        EGL
        GLESv1_CM
        nativewindow
        )


text:
Q: How to set Dom Storage Enabled is TRUE with webview_flutter I has problem with DomStorageEnabled [webview_flutter], i can't set command: settings.setDomStorageEnabled(true);
I has been implement website React JS and use cookies, Local Storage, How to enable in webview_flutter?
Thanks you.


text:
Q: onClick inside post_content does not appear in post tinymce editor I'm doing a migration.
I made a PHP script to generate posts in the new WordPress database.
The post content contains an HTML link containing href="javascript:" and onClick="trackOutboundLink('url')".
post_content in the new database

  ▷ Text link

For some reason, the href and onclick attributes did not show in the admin post editor. Why? How can I fix this?

A: By default, TinyMCE sets allow_script_urls to false, which is what is causing the href attribute and value in the link to be removed.
Also in the interest of best practices, TinyMCE does not allow the onlcick attribute on links by default. This can be changed too.
The tiny_mce_before_init hook can be used to change TinyMCE's options so that this content is not removed:
/**
 * Filters the TinyMCE config before init.
 *
 * @param array  $mceInit   An array with TinyMCE config.
 * @param string $editor_id Unique editor identifier, e.g. 'content'.
 */
add_filter( 'tiny_mce_before_init', 'wpse_tiny_mce_before_init', 10, 2 );
function wpse_tiny_mce_before_init( $mceInit, $editor_id ) {
    // Allow javascript: in href attributes.
    $mceInit['allow_script_urls'] = true;

    // Allow onclick attribute in anchor tags.
  if ( ! isset( $mceInit['extended_valid_elements'] ) ) {
        $mceInit['extended_valid_elements'] = '';
    } else {
        $mceInit['extended_valid_elements'] .= ',';
    }
    $mceInit['extended_valid_elements'] .= 'a[href|rel|class|id|style|onclick]';

    return $mceInit;
}


text:
Q: Can't silence audio errors using Chromedriver with selenium in python I'm running a python script to scrape some webpages and am using selenium + chromedriver. The script is working fine and doing what it's meant to do without crashing, howver chromedriver is logging audio errors that I can't silence.

I'm using log-level 3 so that only fatal errors should print, but I'm still getting the above. I also tried the option to disable logging and again I still got the same output as above.
options = webdriver.ChromeOptions()
options.add_argument('--disable-gpu')
options.add_argument('--start-maximized')
options.add_argument('--log-level=3')
#options.add_argument('--disable-logging')

driver = webdriver.Chrome(chrome_options = options)
driver.get(link)

Any help to get round this would be greatly appreciated!

A: Just try using the --mute-audio argument this should disable the audio.
like this:
options = webdriver.ChromeOptions()
options.add_argument('--disable-gpu')
options.add_argument('--start-maximized')
options.add_argument('--log-level=3')
# options.add_argument('--disable-logging')
options.add_argument("--mute-audio")

driver = webdriver.Chrome(chrome_options = options)
driver.get(link)

EDIT:
Try using logging (this is based on this answer):
import logging
from selenium.webdriver.remote.remote_connection import LOGGER

LOGGER.setLevel(logging.WARNING)
options = webdriver.ChromeOptions()

options.add_argument('--disable-gpu')
options.add_argument('--start-maximized')
options.add_argument('--log-level=3')
# options.add_argument('--disable-logging')
options.add_argument("--mute-audio")

driver = webdriver.Chrome(chrome_options = options)
driver.get(link)

Hope this helps you!


text:
Q: Convert static imports to IIFE and dynamic import to AMD in rollup Is it possible to convert static imports to IIFE and dynamic imports into AMD in a single file with Rollup?
// x.js
export default function () {
    console.log('x.js');
}

// y.js
export default function () {
    console.log('y.js');
}

// main.js
import x from './x.js';

x();

import('./y.js').then(y => y());

into
// bundle.js

function x () {
    console.log('x.js');
}

x();

require(['./y.js'], function (y) {
    y();
});

How can I achieve this?


text:
Q: Getting Error:java.lang.NoSuchMethodError: com.datastax.driver.core.ColumnMetadata.isStatic()Z Getting following error when using spark-cassandra connector in java:
Exception in thread "main" java.lang.NoSuchMethodError: com.datastax.driver.core.ColumnMetadata.isStatic()Z
    at com.datastax.spark.connector.cql.Schema$$anonfun$com$datastax$spark$connector$cql$Schema$$fetchRegularColumns$1.apply(Schema.scala:95)
    at com.datastax.spark.connector.cql.Schema$$anonfun$com$datastax$spark$connector$cql$Schema$$fetchRegularColumns$1.apply(Schema.scala:94)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)

A: Means you build file is wrong. You have probably pulled in the wrong version of the driver.


text:
Q: Harsh azure key-vault secret.name when requested o print I have checked for all related questions but have not found a suitable answer.
I have a keyvault secret successfully set and I am able to access and parse it into my ArcGIS online service using python without any problem using the following code;
from arcgis.gis import GIS
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url="vaulturl", credential=credential)
secret = secret_client.get_secret("papa-mama-Secret")

gis = GIS("urlGIS", "AGOLaccountname", secret.value)

The issue is when I print secret.value, the secret key is displayed. I dont want this to happen for security reasons. Is there away to ensure it can be passed into the service but when printed the key comes out as special characters say ***** or ####?

A: It seems that you could not change the print method just for secret.value. So, disabling the print method is better.
You could use blockPrint() to disable print.
def blockPrint():
    sys.stdout = open(os.devnull, 'w')

A: Here is a code sample to print out the value of your secret.
## CALL TO KEY VAULT TO GET SECRET
secret = client.get_secret("test").value

## OUTPUT SECRET VALUE TO CONSOLE
print(secret)


text:
Q: Parsing Arraylist of type Class I'm using arraylist to hold my result set data from the database. My result set contains four rows. I'm using arraylist of object type. I'm able to save my data to arraylist. But when I tried to print the data from arraylist it is printing the data from last object that is saved. But when I tried to print the arraylist as it is it is printing four different objects. Please help me in printing the arraylist data.
My Servlet:
List<FMB_BOOKS> books = FMB_BOOKS.getBooks();
System.out.println("List from Books: " + books);
PrintWriter out = response.getWriter();
Iterator<FMB_BOOKS> itr = books.iterator();
FMB_BOOKS results = new FMB_BOOKS();
out.println(books.toString());
for (FMB_BOOKS book : books)
{
    System.out.println("Book ID from Books: " + book.getBookid());
    out.println(book.getBookid());
    out.println(book.getBookname());
    out.println(book.getAuthorname());
    out.println(book.getCategory());
    out.println(book.getLanguage());
    out.println(book.getYear());
    out.println(book.getPublisher());
    out.println(book.getCaption());
    out.println(book.getImage());
}

My Java Class:
while (rs.next())
{
    FMB_BOOKS Obj_Books = new FMB_BOOKS();
    System.out.println("Inside While Result Set");
    FMB_BOOKS.setBookid(rs.getString("BOOK_ID"));
    FMB_BOOKS.setBookname(rs.getString("BOOK_NAME"));
    FMB_BOOKS.setAuthorname(rs.getString("AUTHOR_NAME"));
    FMB_BOOKS.setCaption(rs.getString("CAPTION"));
    FMB_BOOKS.setCategory(rs.getString("CATEGORY"));
    FMB_BOOKS.setYear(rs.getString("PUBLISHED_YEAR"));
    FMB_BOOKS.setPublisher(rs.getString("PUBLISHER"));
    FMB_BOOKS.setLanguage(rs.getString("LANGUAGE"));
    FMB_BOOKS.setImage(rs.getString("IMAGE"));
    books.add(Obj_Books);

}


text:
Q: Diferença de horário TimeSpan em formato 24hrs Estou fazendo essa pergunta pois não localizei nenhum tópico com o meu problema, que é bem semelhante a outros.
Eu tenho 2 campos TimeSpan? sendo que um é referente ao horário de entrada e o outro ao horário de saída.
Eu quero saber a diferença de hora, então se a pessoa trabalha das 08:00 as 10:00, ele trabalhou 2 horas.
Isso é bem simples, talvez com um Compare ou um sub eu consiga extrair esse valor total, porém quando eu informo que a pessoa entrou as 17:00 e saiu as 16:00 ele me retorna 1, sendo que ele trabalhou 23 horas
Como eu posso fazer esse calculo?

A: Há uma confusão aí.
Você precisa como resposta de um período, um intervalo de tempo, então a resposta será um TimeSpan.
A entrada de dados é a hora de entrada e hora de saída, portanto são dois pontos no tempo, ou seja, devem ser DateTime.
Quando começa errado fica difícil fazer certo. Transforme essas horas em DateTime e aí basta fazer uma subtração.
using System;
using static System.Console;

public class Program {
    public static void Main() {
        var objeto = new AlgumaClasse();
        objeto.HoraEntrada = DateTime.Now;
        objeto.HoraSaida = DateTime.Now.AddHours(1).AddMinutes(43).AddSeconds(22);
        WriteLine($"Permaneceu {(objeto.TempoPermanencia().ToString(@"hh\:mm"))}");
    }
}

class AlgumaClasse {
    public DateTime HoraEntrada { get; set; }

    public DateTime HoraSaida { get; set; }

    public TimeSpan TempoPermanencia() => HoraSaida - HoraEntrada;
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.

A: O TimeSpan tem a opção de ter os dias também. No construtor dele tem uma sobrecarga que você informa (days, hours, minutes, seconds) e se você informar a quantidade de dias o calculo ficará mais preciso.
Exemplo:
    TimeSpan t1 = new TimeSpan(0,17,0,0);
    TimeSpan t2 = new TimeSpan(1,16,0,0); //Repare que aqui tem um dia.

    var result = t2-t1;
    Console.Write(result.ToString()); // Resultado será 23:00:00

Se na variável t2 instânciar passando o primeiro parametro como zero, verá que o resultado será -01:00:00. O código acima pode ser verificado aqui https://dotnetfiddle.net/tUO2AI
Assim se você persiste esses campos em algum lugar, no momento de persistir você deveria considerar a quantidade de dias no seu timespan.


text:
Q: ServiceConfigurationError caused by LinkageError in WebSphere I have an application that is deployed on WebSphere 9.0.5.2 where I want to use CXF for webservice calls and I'm getting this This ServiceConfigurationError
WrapperedException { java.util.ServiceConfigurationError: javax.xml.ws.spi.Provider: Provider org.apache.cxf.jaxws.spi.ProviderImpl could not be instantiated

Further down the stacktrace, I see that this is caused by a LinkageError
Caused by: java.lang.LinkageError: loading constraint violation when overriding method
  "javax/xml/ws/spi/ServiceDelegate.createDispatch(Ljavax/xml/namespace/QName;Ljavax/xml/bind/JAXBContext;Ljavax/xml/ws/Service$Mode;)Ljavax/xml/ws/Dispatch;" during creation of class
  "org/apache/cxf/jaxws/ServiceImpl": loader
  "com/ibm/ws/classloader/CompoundClassLoader@832133d2" of class
  "org/apache/cxf/jaxws/ServiceImpl" and loader
  "com/ibm/oti/vm/BootstrapClassLoader@2eec706a" of class
  "javax/xml/ws/spi/ServiceDelegate" have different types for the method signature

I understand that this could be caused by multiple libraries that have different definitions for QName or JAXBContext, but I think I've ruled those out.
I also understand that WebSphere has it's own JAX-WS with it's own method signature for ServiceDelegate.createDispatch and I've tried setting DisableIBMJAXWSEngine to true in WebSphere as instructed here
Using a third-party JAX-WS web services engine
I still haven't been able to get rid of the error and am pretty much at a loss as to what to try next.  Any suggestions is appreciated!!!

A: The issue here is a cross-linkage between the application and server's copies of the JAXB API, JAX-WS API, and JAX-WS implementation. The application (configured with parent-last class loading delegation, so it searches locally before delegating to parents) contains a JAX-WS implementation and JAXB API/impl, but it does not contain the JAX-WS API. Since JAX-WS references JAXB, we get the following linkage pattern:
1) Some application class references the JAX-WS API. Because it's not packaged in the application, it's loaded from the server libraries.
2) When the API class is linked, it uses its local class loader to find the JAXB API. That, in turn, links it to the server's version as well.
3) JAX-WS uses the thread context class loader to load its implementation. It finds it in the parent-last application.
4) When the implementation class is linked, it uses its local class loader to find the JAXB API, which finds it locally in the application.
5) The implementation now is linked to two versions of the same class:
JAXWSImpl -> JAXWSAPI -> JAXB (server)
JAXWSImpl -> JAXB (app)
The JVM can't tolerate that, and a LinkageError is thrown.
The solution can be approached one of two ways:
1) Add the JAX-WS API to the application - this prevents the initial delegation in #1 above
2) Remove the JAXB API (and implementation, if provided) from the application - this causes the linkage in #4 to delegate down to the server for JAXB, so it's always loaded from the same place.
Either way, the trick is to ensure that all the necessary classes are available to the application through the same class loader.


text:
Q: Wierd behavior with unusable index - oracle I do have a big migration process where there is a scenario in which its trying to insert a row into a table which has a primary key constraint and unique index for it. Before inserting the constraint is disabled (checked it with SQL developer) and the index is marked unusable (checked it again with SQL developr). But still when inserting its giving an error
01502. 00000 -  "index '%s.%s' or partition of such index is in unusable state"

So I wanted to try out executing the query manually from SQL developer and still the same result. I even explicitly tried to set the session (and system) skip unusable index like this
BEGIN
EXECUTE IMMEDIATE 'ALTER SESSION SET SKIP_UNUSABLE_INDEXES = TRUE';
single row insert line
END;

But still the same error. My understanding is that if constraints are disabled; indexes are unusable and we skip the unsusable index we should be able to insert. Is it correct? Am i missing something very trivial here? Any suggestions/help appreciated.
PS: Oracle 11.2.0.1.0

A: If the index is not UNIQUE, you can set SKIP_UNUSABLE_INDEXES = true and it should work.
However, in your case, as the index is unique, I dont think you can do this.
http://docs.oracle.com/cd/B28359_01/server.111/b28320/initparams229.htm

A: Create a surrogate key for all rows with unusable primary keys.


text:
Q: Sprite-Kit category bitmask is wrong for Physics body This is really annoying me, I have a player and a scene, and collision detection. When I go into didBeginContact the if condition returns false.
I stopped to debug, and the secondBody (which should be the scene in this case) has a categoryBitMask of some random number , not the one I assigned it from the PhysicsCategory struct, so it won't go into the if condition. Is it because the scene is an edgeLoopFromRect?
Here's the code:
struct PhysicsCategory {
    static let None      : UInt32 = 0
    static let Player    : UInt32 = 0b1
    static let Scene     : UInt32 = 0b10
    static let All       : UInt32 = UInt32.max
}
class GameScene: SKScene, SKPhysicsContactDelegate {
    var canJump = true
    var touchStart = CGPoint()
    var touchEnd = CGPoint()
    var squaresArray = NSMutableArray()
    var player = SKSpriteNode(imageNamed: "craft.png")
    override func didMoveToView(view: SKView) {
        physicsWorld.contactDelegate = self
        physicsBody?.categoryBitMask = PhysicsCategory.Scene
        physicsBody?.contactTestBitMask = PhysicsCategory.Player
        physicsWorld.gravity = CGVectorMake(0, -2)
        physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
        physicsBody?.usesPreciseCollisionDetection = true
        setUpPlayer()
    }
    func setUpPlayer() {
        player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
        player.physicsBody?.categoryBitMask = PhysicsCategory.Player
        player.physicsBody?.contactTestBitMask = PhysicsCategory.All
        player.physicsBody?.mass = 1
        player.physicsBody?.restitution = 0
        player.xScale = 0.5
        player.yScale = 0.5
        player.position = CGPoint(x: 600, y: 700)
        addChild(player)
    }

    func didBeginContact(contact: SKPhysicsContact) {
        var firstBody: SKPhysicsBody?
        var secondBody: SKPhysicsBody?
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
            firstBody = contact.bodyA
            secondBody = contact.bodyB
        } else {
            firstBody = contact.bodyB
            secondBody = contact.bodyA
        }
        if (firstBody!.node != nil && secondBody!.node != nil) {
            println("not nil")
            if ((firstBody!.categoryBitMask == PhysicsCategory.Player) &&
                (secondBody!.categoryBitMask == PhysicsCategory.Scene)) {
                    println("collision")
                    canJump = true
            }
        }
    }

A: Can I have a second please...

WTTTTFFFFFFF

ok now that I got that out, the problem was that I declared the physicsBody AFTER setting the categoryBitMask. so switching this:
override func didMoveToView(view: SKView) {
    physicsWorld.contactDelegate = self
    physicsBody?.categoryBitMask = PhysicsCategory.Scene
    physicsBody?.contactTestBitMask = PhysicsCategory.Player
    physicsWorld.gravity = CGVectorMake(0, -2)
    physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)//this line moves up
    physicsBody?.usesPreciseCollisionDetection = true
    setUpPlayer()
}

to this:
override func didMoveToView(view: SKView) {
    physicsWorld.contactDelegate = self
    physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)//to here
    physicsBody?.categoryBitMask = PhysicsCategory.Scene
    physicsBody?.contactTestBitMask = PhysicsCategory.Player
    physicsWorld.gravity = CGVectorMake(0, -2)
    physicsBody?.usesPreciseCollisionDetection = true
    setUpPlayer()
}

fixed this issue...


text:
Q: Get tag attribute in Onclick event <div style='padding:10px;border:1px solid #888;width:150px;' id='btnTest' data-id='1'>
    <label>
      <input type='checkbox' name='test1' />
      TEST1
    </label>
    <label>
      <input type='checkbox' name='test2' />
      TEST2
    </label>
</div>

<script>
$(function() {
  $('#btnTest').click(function(e){
    console.log($(e.target).attr('data-id'));
  })
});
</script>

In that test code, if I click the label area, I can not get the data-id value,
Is there any way I can get the data-id even I click the other element in that DIV tag?

A:  $(this).attr('data-id');

e.target refers to the element clicked, this to the element where the handler is binded.

A: Use 'this':
$(function() {
  $('#btnTest').click(function(){
    console.log($(this).attr('data-id'));
  })
});

However if you want the checkbox's 'name':
Do:
$(function() {
  $('#btnTest label input').click(function(){
    alert($(this).attr('name'));
  })
});

A: Yes you can simply do:
$(function() {
  $('#btnTest').click(function(e){
    console.log($(e.target).parent('#btnTest').attr('data-id'));
  })
});


text:
Q: prove that in a cyclic group of even order, there is exactly one element of order 2. prove that in a cyclic group of even order, there is exactly one element of order 2. Please prove the requirements.

A: Let $G$ be a cyclic group of even order, that is, a group with an order of $2n$ where $n$ is a natural number. We know that every cyclic group G verifies the inverse of Lagrange's Theorem, that is, there exists a unique subgroup H of G with order m, for every divisor $m$ of $n$.
Now, considering that $G=<g>$ where $g$ is a generator of the cyclic group $G$, we have that $g^n$ is an element of order $n$ in $G$, because $(g^n)^2=g^{2n}=1$. This element generates the subgroup $<g^n>=\{1,g^n\}$ of $G$, which has order 2, and is therefore the only subgroup of $G$ with order two (according to the inverse of Lagrange's Theorem, and because $n$ is a divisor of the order $2n$ of our group $G$).
Now let's suppose that there exists another element $x\neq g^n$, $x\in G$, such that the order of $x$ is 2. Then, $<x>=\{1,x\}$ would be a subgroup of order 2 of $G$, which would be different than $<g^n>$, contradicting the uniqueness stated above. This means that $g^n$ is the only element of $G$ with order 2.
Edit: Would anyone mind explaining the downvote? I think my answer is correct and solves the problem.


text:
Q: Игра Коровы и Быки, но бот подменивает цифры в числе Программа должна играть с игроком в игру Коровы и Быки, но с одним нюансом, бот после каждого хода, основываясь на истории отгадок должен менять в числе цифры.
import random

def generate_answer():
    n = [i for i in range(10)]
    number = []
    for _ in range(4):
        a = n.pop(random.choice(range(len(n))))
        number.append(str(a))
    return ''.join(number)

def cows_bulls(num, answer):
    cows = 0
    bulls = 0
    for i in range(4):
        # Проверка на быка
        if str(num)[i] == str(answer)[i]:
            bulls += 1
        # Проверка на корову
        elif num[i] in str(answer):
            cows += 1
    return [bulls, cows]

def cheat():
    changer = True
    new_answer = None
    history = []
    # Пока не найдётся новый ответ
    while changer:
        new_answer = generate_answer()
        if new_answer == answer:
            changer = True
            break
        else:
            if history:
                for i in history:
                    # Проверка на совпадение с историей
                    if cows_bulls(i[0], new_answer) != [i[1], i[2]]:
                        changer = True
                        break
                    else:
                        changer = False
            else:
                changer = False
    return new_answer

def play():
    global answer
    bulls = 0
    history = []
    # До победы
    while bulls < 4:
        attempt = input('Введите четырёхзначное число, цифры не повторяются: ')
        bulls, cows = cows_bulls(attempt, answer)
        if bulls >= 2 or cows >= 3 or bulls + cows == 4:
            # Подмена ответа
            answer = cheat()
        bulls, cows = cows_bulls(attempt, answer)
        # Запись истории
        history.append([attempt, bulls, cows])
        print(cows, 'коровы, ', bulls, 'быка.')
    print('Вы выиграли!')

answer = generate_answer()
play()

Все работает, кроме функции cheat(), она противоречит предыдущим ответам...


text:
Q: Date Input not being set on selecting a date I am trying to create a function that automatically calculates a person's age based on a selected date of birth.

      DOB
      <date-input name="{{member.MemberID + 'Birthdate'}}" max="controller.today" ng-model="member.NoServicesProvided.birthDate" ng-change="controller.calcAge(member)"></date-input>

      Age
      <input name="{{member.MemberID + 'Age'}}" type="text" maxlength="2" class="form-control input-sm" ng-model="member.NoServicesProvided.age" required valid-number>

function calcAge(member) {
     if(member.NoServicesProvided.birthDate) {
           var deltaDate = Date.now() - member.NoServicesProvided.birthDate.getTime();
           var ageDate = new Date(deltaDate);
           member.NoServicesProvided.age = Math.abs(ageDate.getUTCFullYear() - 1970);
           console.log(member.NoServicesProvided.age);
     }
}

The problem comes when entering a date for the first time. When I select a date, for some reason it says member.NoServicesProvided is undefined. This NoServicesProvided property is being used elsewhere on the page with no issue. Then, when I select another date, it suddenly works but with the first date entered rather than the second.
Is there something I'm missing? Please know that I need to keep it in this kind of format. Any help is appreciated though!

A: Found the solution:
Inside the calcAge function, wrap the code inside a $timeout( function() { ... } );


text:
Q: Trying to Filter Html table using array to check string I am trying to filter an HTML table and show me the rows that exist that have ALL of the matches of my keywords -
For instance. I have my html table as follows

    ID
    Name
    Tags

    1
    Test1
    AIRPORT TERMINAL,AVIATION,HANGAR,MAINTENANCE BUILDING,NEW CONSTRUCTION,OFFICE

    2
    Test2
    HIGHER EDUCATION,OFFICE,RENOVATION,SCHOOLS - COLLEGE

    3
    Test3
    HIGHER EDUCATION,REMODEL,SCHOOLS - COLLEGE

    4
    Test4
    APARTMENT,HIGHER EDUCATION,NEW CONSTRUCTION,SCHOOLS - COLLEGE

From here I am trying to do JQuery or JavaScript to filter and only show me the rows that contain atleast ALL of the specific words.
So for instance.
If I send an array
const Keywords = ["HIGHER EDUCATION", "RENOVATION"];

it should show me rows with ID 2 only
If I send an array
const Keywords = ["HIGHER EDUCATION", "SCHOOLS-COLLEGE"];

it should show me rows with ID 2 and 3 as they both contain those words it should not show me 1 or 4 as it does not contain all those words plus extras.
I plan on using this that I currently use to filter my columns on other items -
 var jo = $("#" + tablename).find("tr:not(:first)");
        jo.filter(function (i, v) {
            var $t = $(this).children(":eq(" + indexColumn + ")");
            for (var d = 0; d < data.length; ++d) {
                if ($t.is(":not(:containsIN('" + data[d] + "'))")) {
                    return true;
                }
            }
            return false;
        }).hide();

I am getting column index by
  $("#" + tablename).find('th').each(function () {
            if ($(this).find('span').text() == 'tags') {
                d = $(this).index();

                var e = $("#" + tablename).find('tr:eq(' + row.index() + ')').find('td:eq(' + d + ')');

            }
        });

I hope I am making sense on this.

A: In this example, we just use the :last-child to find the tag column.  I think the crux of your question relates to being able to filter the rows based on matching a string or set of strings.
<button class="filter" filter="HIGHER EDUCATION,RENOVATION">filter 1</button>

we will use this filter attribute later to split() on , and then match all the whole filter and hide those that do not match.
var filter = $(this).attr("filter").split(",");
  $("table.tg").find("tbody > tr").filter(function(i, r){
    var txt = $(r).find(":last-child").text();  //get the text in the last cell
    var match = filter.every(s=>(new RegExp(s)).test(txt)); //does the text match all the filters?
    return !match;  //if it doesnt match return it to be filtered (hidden)
  }).hide();

$("button.filter").on("click", function(e){
  //show all hidden rows
  $("table.tg").find("tbody > tr").show();
  //split the filter attribute into an array by commas
  var filter = $(this).attr("filter").split(",");
  $("table.tg").find("tbody > tr").filter(function(i, r){
    var txt = $(r).find(":last-child").text();  //get the text in the last cell
    var match = filter.every(s=>(new RegExp(s.trim())).test(txt)); //does the text match all the filters?  trimmed just in-case
    return !match;  //if it doesnt match return it to be filtered (hidden)
  }).hide();
});

<button class="filter" filter="HIGHER EDUCATION,RENOVATION">filter 1</button>
<button class="filter" filter="HIGHER EDUCATION,SCHOOLS-COLLEGE">filter 2</button>
<button class="filter" filter="">reset</button>

    ID
    Name
    Tags

    1
    Test1
    AIRPORT TERMINAL,AVIATION,HANGAR,MAINTENANCE BUILDING,NEW CONSTRUCTION,OFFICE

    2
    Test2
    HIGHER EDUCATION,OFFICE,RENOVATION,SCHOOLS-COLLEGE

    3
    Test3
    HIGHER EDUCATION,REMODEL,SCHOOLS-COLLEGE

    4
    Test4
    APARTMENT,HIGHER EDUCATION,NEW CONSTRUCTION,SCHOOLS - COLLEGE

A: The following example are agnostic plain JavaScript functions. The only things you must know is if there's a
 with text in a specific column. In OP:
// USAGE
const dataArray = tableData('table', 2);
// EITHER
filterTerms(dataArray, "HIGHER EDUCATION", "renovation");
// OR
const keywords = ["HIGHER EDUCATION", "RENOVATION"];
filterTerms(dataArray, keywords)

Details are commented in example below
HTML is condensed and valid

//Utility function
const log = data => console.log(JSON.stringify(data));

/**
 * Extract text from a given tbody at a given column.
 * @param {string} selector - CSS selector of

 * @param {number} column - index number of  within each row that has
 * the text to extract (@default - 0)
 * @returns {array<mixed>} contents of returned array:
 * [DOM Object of
, [[Strings], [Strings],...]]
 */
const tableData = (selector, column = 0) => {
  // Reference

  const T = document.querySelector(selector).tBodies[0];
  /*
  Collect all
 in
 into a HTML Collection then convert it into
  an array
  */// Get qty of rows
  const rows = [...T.rows];
  const rQty = rows.length;
  // Define empty array outside of loop
  let data = [];
  /*
  On each
 get the text of the  located at the index of @column
  */// Convert text into array and add array to >data<
  for (let r = 0; r < rQty; r++) {
    let tags = rows[r].cells[column].textContent;
    tags = tags.split(/,\s*/);
    data.push(tags);
  }
  //log(data);
  // Return mixed array (see @returns)
  return [T, data];
};

/**
 * Filter a given
 by completely matching a given string array or
 * string(s) vs. the data extracted by tableData()
 * All non-matching rows are removed.
 * @param {array<mixed>} tData - (see tableData @returns)
 * @param {array<string> OR string(s)} terms - Strings to search for
 */
const filterTerms = (tData, ...terms) => {
  /*
  Check >terms< is an array or strings.
  If it's an array, flatten it.
  If it's strings put them in an array.
  */
  //log(terms);
  let keywords = Array.isArray(terms) ?  terms.flat() : [...terms];
  // Ensure strings are uppercase
  const keys = keywords.map(str => str.toUpperCase());
  /*
  >tData<
  [ tbody, [[text of row 0], [text of row 1],...] ]
  >tData[0]< = tbody
  >tData[1]< = the extracted text of each row at the cell at
  >column< index
  */
  tData[1].forEach((row, idx) => {
    /*
    Return true if .every() word of >keys< is present in the current
    array in >tData[1]< If it is true...
    */
    if (keys.every(term => row.includes(term))) {
      //... remove .hide from
..
      tData[0].rows[idx].classList.remove('hide');
    } else {
      // ...otherwise add .hide to

      tData[0].rows[idx].classList.add('hide');
    }
  });
};

// Save return of tableData() in a variable
const dataArray = tableData('table', 2);

// Each array is for the second @param
const keywords1 = ["HIGHER EDUCATION", "RENOVATION"];
const keywords2 = ["HIGHER EDUCATION", "SCHOOLS-COLLEGE"];

/*
The second @param >terms< can be an array of strings OR
one or more strings (see next line)
*/
filterTerms(dataArray, "HIGHER EDUCATION", "renovation");

//filterTerms(dataArray, keywords1);

//filterTerms(dataArray, keywords2);
html {
  font: 2ch/1.15 'Segoe UI';
}

table {
  border-collapse: collapse;
  border-spacing: 0;
  border: black solid 1px;
}

td,
th {
  border: black solid 1px;
  overflow: hidden;
  padding: 10px 5px;
  text-align: left;
  vertical-align: top
}

td:first-of-type {
  text-align: center;
}

.hide {
  display: none;
}

IDNameTags

1Test1AIRPORT TERMINAL,AVIATION,HANGAR,MAINTENANCE BUILDING,NEW CONSTRUCTION,OFFICE
2Test2HIGHER EDUCATION,OFFICE,RENOVATION,SCHOOLS-COLLEGE
3Test3HIGHER EDUCATION,REMODEL,SCHOOLS-COLLEGE
4Test4APARTMENT,HIGHER EDUCATION,NEW CONSTRUCTION,SCHOOLS-COLLEGE


text:
Q: Send variable from php to python Here is my problem, I need to send a variable to a python script from php which isn't really that hard but I just found out that they are not on the same server. The php file is on server A and can be accessed at server-a.com and the python is on a different server that can be accessed at server-b.com.
This is my current code for the php and python which works when they are on the same server:
PHP:

// Call to the python script test.py with the JSON data
$result = shell_exec('python test.py ' . escapeshellarg(json_encode($data)));

// get data back from python, decode it and display it
$resultData = json_decode($result, true);
//var_dump($resultData);
echo $result;
?>

Python:
    import sys, json

# Load the data that PHP testv2.php sent us
try:
    data = json.loads(sys.argv[1])
except:
    print "ERROR"
    sys.exit(1)

# Generate some data to send to PHP
result = {'status': 'Yes!'}

# Send it to PHP
print json.dumps(data)

A: Since you are on different servers you probably want to communicate via HTTP.
If your code is really THAT simple like shown in your example and will never become more complex, consider invoking Python via CGI.
For anything else (or if you simply prefer doing it properly) consider using WSGI and a framework such as Flask which allows you to define multiple endpoints using an url routing system.


text:
Q: remove the dot after Theorem while using the cleveref package I want to remove the dot after the numbering of theorems, definitions etc. within the amsthm package. (So I get Theorem 1.1 instead of Theorem 1.1.) (EDIT: I want to remove the dot from the theorems themselfs)
I am using both the hyperref and the cleveref packages, both of which pose problems.
I already found a solution to the hyperref package here Remove dot after theorem with amsthm and hyperref, but when using the cleveref package, the dot reappears.
MWE:
\documentclass[a4paper,12pt,oneside]{scrbook}
\usepackage{amsthm}
\usepackage{hyperref}
\usepackage{cleveref}

\newtheorem{theorem}{Theorem}[chapter]

\usepackage{xpatch}
\makeatletter
\AtBeginDocument{\xpatchcmd{\@thm}{\thm@headpunct{.}}{\thm@headpunct{}}{}{}}
\makeatother

\begin{document}

\chapter{Hello}

\begin{theorem}
    World
\end{theorem}

\end{document}

which outputs

How can i remove that dot?

A: cleveref changes \@thm making the linked solution not work anymore. Adding \tracingpatches before you attempt to patch \@thm will reveal that the "search pattern [is] not found in [the] replacement text."
The following updates the patches when using cleveref:

\documentclass{scrbook}

\usepackage{amsthm}
\usepackage{hyperref}
\usepackage{cleveref}

\newtheorem{theorem}{Theorem}[chapter]

\usepackage{xpatch}
\makeatletter
% Patch to accommodate for \begin{theorem}[...]
\AtBeginDocument{\xpatchcmd{\cref@thmoptarg}{\thm@headpunct{.}}{\thm@headpunct{}}{}{}}
% Patch to accommodate \begin{theorem} (without an optional argument)
\AtBeginDocument{\xpatchcmd{\cref@thmnoarg}{\thm@headpunct{.}}{\thm@headpunct{}}{}{}}
\makeatother

\begin{document}

\chapter{Hello}

\begin{theorem}
World
\end{theorem}

\end{document}

My (rough) process for identifying the updates patches:

*

*Add a \typeout{success} and \typeout{failure} to the <success> and <failure> in the patch:
\xpatchcmd{<cmd>}{<search>}{<replace>}{<success>}{<failure>}

This will allow you to examine the .log and see whether the patch worked or failed.

*If it failed, add \tracingpatches before the patches are made and see what the .log outputs. Is the search pattern still the same? Did the macro change?

*Look at the actual macro being patched to see what it is defined as using \show. In my case, \show\@thm.

*From there, follow any subsidiary macro definitions to see find out where the changes should be applied to your original \xpatchcmd.
In this case, \@thm conditioned on an optional argument, and it was clearly introduced by cleveref since the two subsidiary macros were \cref@thmoptarg and \cref@thmnoarg.

A: Since you're using amsthm, you would need to define a new theorem style:
\newtheoremstyle{nodot}
  {}{} % Default space above and below
  {\itshape}{} % italic body unindented
  {\bfseries}{} % bold theorem head, no dot after
  { }{} % normal space between theorem head and body, default head spec

The full details can be had by typing texdoc amsthm at a command line.


text:
Q: How can I assign a variable from one JavaScript file to other JS File? Please look at the sample scenario,
Say I have a variable called,
var myvariable;
Then in another JavaScript file I assign the value to varaiable,
myvariable = "Hi";

What I tried?
Basically, what I did for this is the newPassword variable in Firebase's custom-email-handler. I have another page where you reset your password but I have the script where it changes the password in another JavaScript file.

A: If myvariable is in the global scope, meaning it is not enclosed in any function, then it will be available to all other scripts by default.  And, frustratingly enough, if you DO declare it inside another function, but forget to use "var" when declaring it, it will also end up in the global scope.
Consider this:
<script src="script1.js"></script>
<script src="script2.js"></script>

script1.js:
var myvariable = "hi";

script2.js:
console.log(myvariable);
// "hi"

When the page loads, "hi" will be printed to console, because script1.js was listed first
As opposed to this:
<script src="script1.js"></script>
<script src="script2.js"></script>

script1.js:
function() {
    var myvariable = "hi";
}

script2.js:
console.log(myvariable);
// Uncaught ReferenceError: myvariable is not defined

When the page loads, script2.js will throw an error, because it can't see myvariable, since it is locked inside a function scope.
One last case
<script src="script1.js"></script>
<script src="script2.js"></script>

script1.js:
var myFunc = function() {
    //notice I'm not going to use "var" in front of myvariable
    myvariable = "hi";
}
//As soon as you call the function, myvariable is now global. Oops!
myFunc();

script2.js:
console.log(myvariable);
// "hi"

If you want to know more about this subject, just search "javascript scope", "javascript global scope", or "javascript implicit global".
And, to address what I think was your original point of confusion, just remember that all scripts are run in the context of the browser window. There's no concept of "how do I make this script talk to that script?". To help visual how it works, imagine taking the contents of your scripts and dumping it in one large script file. That's conceptually what happens after the browser is finished loading everything, (barring advanced topics like asynchronous loading)

A: You should make it global by adding it to the window object.
script1.js
window.myvariable="Hi";

script2.js
alert(myvariable);

Note that script1.js will have to load first.


text:
Q: Using a push button to switch between a stacked tab in python using PyQt I am writing a program that requires a user switch from a page to another with a push button (using next and previous buttons). How do I connect the push button to the next page.

A: IMHO, the simpliest way is to subclass QStackedWidget like this:
class MyStackWidget(QtGui.QStackedWidget):

    def forward(self):
        self.setCurrentIndex(self.currentIndex() + 1)

    def backward(self):
        self.setCurrentIndex(self.currentIndex() - 1)

and then use it like this:
class MyWin(QtGui.QWidget):

    def __init__(self):
        super().__init__()
        self.stack = MyStackWidget(self)
        ...
        self.btnBackward.clicked.connect(self.stack.backward)
        self.btnForward.clicked.connect(self.stack.forward)


text:
Q: Ubuntu themes directory I downloaded a few themes from various ppa's, and i don't like the button for closing, minimalizing etc. Are those themes stored in some kind of directory where i can edit their files? I'm using Unity Tweak Tool for applying them. Thank you!

A: Default themes directory is /usr/share/themes/ but it's editable only for root. If You want to edit themes the default directory for current user would be ~/.themes/ I believe.

A: locate themes|grep Ambiance| grep png|more
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-button-active-disabled.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-button-active-hover.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-button-active.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-button-disabled.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-button-hover.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-button-toolbar-active.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-button-toolbar.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-button.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-check-mixed-alt.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-check-mixed-disabled-alt.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-check-mixed-disabled.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-check-mixed-hover-alt.png
/usr/share/themes/Ambiance/gtk-3.0/assets/backdrop-check-mixed-hover.png
 ...

You can find the others in the same directory /usr/share/themes/ with their respective names.

A: If you want to find out the location of some app, file or anything else in the terminal type:
whereis 'name_you_search' - for example ''whereis firefox''
It will give you the directory in  which the file is located.
When you type ''whereis themes'' you should get something like this:
themes: /usr/share/themes
So the themes are inside /usr/share directory


text:
Q: Error in form validation using Javascript in email field

<!DOCTYPE html>

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

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

     <link rel = "stylesheet" type = "text/css" href = "form.css" />

<form name="myForm" onsubmit="return validateForm()" method="post">

SignUp

       Email
       <input type="text" class="form-control" placeholder="Enter Email" name="email">

        User Name
       <input type="text" class="form-control" placeholder="Enter User Name" name="userid" required>

        Password
       <input type="password" class="form-control" placeholder="Enter Password" name="pwd" required>

        Re-enter Password
       <input type="password" class="form-control" placeholder="Re-Enter Password" name="pwd1" required>

        Enter DOB
       <input type="date" class="form-control" name="dob" required>

      <input type="reset" class="cancelbtn" value="Reset">
      <input type="submit" class="signupbtn" value="Submit">

</form>

I have tried beginner level javascript validation to ensure that email field cannot be left blank.However on running the code, no validation is being performed for the email field. That is, no popup appears and directly the required attribute of userid gets displayed. Can anyone point out the errors in the code?

A: In the email input box, you don't have required condition mentioned, hence form will get submitted if you try to submit without entering any values.
If you don't want this, you need to add required.

<!DOCTYPE html>

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

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

     <link rel = "stylesheet" type = "text/css" href = "form.css" />

<form name="myForm" onsubmit="return validateForm()" method="post">

SignUp

       Email
       <input type="text" class="form-control" placeholder="Enter Email" name="email" required>

        User Name
       <input type="text" class="form-control" placeholder="Enter User Name" name="userid" required>

        Password
       <input type="password" class="form-control" placeholder="Enter Password" name="pwd" required>

        Re-enter Password
       <input type="password" class="form-control" placeholder="Re-Enter Password" name="pwd1" required>

        Enter DOB
       <input type="date" class="form-control" name="dob" required>

      <input type="reset" class="cancelbtn" value="Reset">
      <input type="submit" class="signupbtn" value="Submit">

</form>

A: You have added the HTML5 validation on each field except the email field.
Look at here:
placeholder="Enter User Name" name="userid" required>
                                            ^^^ this require attribute

So first your HTML5 validation will execute and after that your javascript will work.
required attribute is validation in HTML5 and most of browser support that.
To check your javascript, first fill the form except the email field and after that the alert will work.

A: The standard HTML5 validation is always performed before the form gets submitted. That means that if that validation fails, i.e. any of your required fields don't have a valid value, the submit event is never even triggered and your custom validation doesn't run at all.
This makes sense, because why would your custom validation need to run if the form isn't ready to be submitted to begin with?
In other words, there are no errors in your code, it behaves as expected.
If you always want your custom validation to run, you need to remove the required attributes on all the other fields so that there's no standard validation and instead validate those fields in your custom validation.

A: First of all, you should include you JS code at the end of the  section, not in the .
Second, you should use jQuery to perform that just including the CDN resource link at the end of the body. You can see here that is really simple:

  <form id="myForm" action="" method="POST">
    Email
    <input type="text" id="email">
    <button type="submit">Submit</button>
  </form>

Or just adjust yours:

<!DOCTYPE html>

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

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

     <link rel = "stylesheet" type = "text/css" href = "form.css">

<form name="myForm" onsubmit="return validateForm()" method="post">

SignUp

       Email
       <input type="text" class="form-control" placeholder="Enter Email" name="email" id="email">

        User Name
       <input type="text" class="form-control" placeholder="Enter User Name" name="userid" required>

        Password
       <input type="password" class="form-control" placeholder="Enter Password" name="pwd" required>

        Re-enter Password
       <input type="password" class="form-control" placeholder="Re-Enter Password" name="pwd1" required>

        Enter DOB
       <input type="date" class="form-control" name="dob" required>

      <input type="reset" class="cancelbtn" value="Reset">
      <input type="submit" class="signupbtn" value="Submit">

</form>

Good Luck!


text:
Q: Firebase StartAt Query With Deletions If I have a query that looks like:
orderByChild("updated_at").startAt(mostRecentUpdatedAt + 1)

to implement caching without having to download the whole data set every time I connect, is there a way that I can get child remove events if the child is removed without updating the updated_at field?

A: You can create a addChildEventListener and implement the public void onChildRemoved(DataSnapshot dataSnapshot) method.


text:
Q: Facebook Open Graph posts layout switches between small image and large image We are currently integrating Facebook Open graph with our web and mobile applications. We have couple of stories created in the open graph sections.
Each story has a custom action and a custom object.
The object contains an image thats getting shared when an action is posted.
All images are of type png and width:201px height 201px.
We found that the minimum allowed image size is 200px. So this should be acceptable.
Open graph layout for both stories are "item" layout in "Edit Attachment" section.
Objects are posted to the facebook API as opengraph objects.
graph.facebook.com/objects/{appname}:{object_name}/{accesstoken}
This endpoint returns an opengraph object id which then is sent as part
Opengraph action post.
graph.facebook.com/{appname}:{action_name}/{accesstoken}
The content is getting posted without a problem. The issue is only with the way the posts are getting displayed.
The layout switches between large image and small image(preferred) layouts.
The layouts displayed in Facebook:

Layout switching is completely Random. Sometimes all posts comes in the small image layout but then for another Facebook user they display as large image layouts.
We are trying to find out how to force Facebook to show the small image layout.
Any help will be much appreciated.


text:
Q: Define symbol as property using lazy initialization I have this:
export const symbols = {
  toString: Symbol('@xml.js.toString')
};

export class Node {

  [key: string]: any;

  [symbols.toString] = function(){

  };

}

but I get this error:

Which is:

A computed property name in class property declaration must refer to
  an expression whose type is a literal type or unique symbol type.

Anyone know what's going on?
If I put it in the constructor, I don't get an error:

A: As the error states, only unique symbols can be used as computed property names.
As described in the reference,

To enable treating symbols as unique literals a new type unique symbol is available. unique symbol is are subtype of symbol, and are produced only from calling Symbol() or Symbol.for(), or from explicit type annotations. The new type is only allowed on const declarations and readonly static properties, and in order to reference a specific unique symbol, you'll have to use the typeof operator. Each reference to a unique symbol implies a completely unique identity that's tied to a given declaration.

Due to listed limitations, object property cannot be unique.
Instead, it can be:
export namespace symbols {
  export const toString = Symbol('@xml.js.toString');
};


text:
Q: Use glob node.js to know if a file exists in the parent folder using wildcard I need to search in the parent folder of where a node.js yeoman generator script is running to see if a file exists, but I won't know the file name - only the extension.
Glob:  https://www.npmjs.com/package/glob
Folder Structure:

*

*C:\Work\

*C:\Work\Company\

*C:\Work\Company\Project\

Assume that the Project folder is where the command prompt is...  I want to run a Yeoman generator that looks into the Company folder first to see if a specific file exists.  It could be any file name, ending in .sln.
There are plenty of beginner resources, but I can't find any examples that show:

*

*How to look in the parent folder successfully; and

*How to work with the output (true/false?) to use in a variable for logic later in the function.

Here's what I tried to do, but I am admittedly much more adept in C# than I am in JS.
var globbed = glob("../*.sln", function(err, files){
    this.log(chalk.yellow("err = " + err));
    this.log(chalk.yellow("files = " + files));
});

and this...
var gOptions = { cwd: "../" };
var globbed = glob("*.sln", gOptions, function(err, files){
    this.log(chalk.yellow("err = " + err));
    this.log(chalk.yellow("files = " + files));
});

In both examples, globbed is an object, but I don't know what its properties are, and I am not able to access the internal function.
Essentially, I need to know if the file exists so that I can run an If/Then statement on it.

A: Use glob.sync:
const files = glob.sync("*.sln", { cwd: "../" });

or simply
const files = glob.sync("../*.sln");

files will be an array of *.sln files, if any, in the parent directory.  Obviously, glob.sync is synchronous.

A: Try this.
const path = require('path');
const glob = require('glob');

glob(
 '*.sln',
 { cwd: path.resolve(process.cwd(), '..') },  // you want to search in parent directory
 (err, files) => {
   if (err) {
     throw err;
   }

   if (files.length) {
     // File exists. All matched filenames are inside files array.
   } else {
     // File does not exist. files array is empty.
   }
 }
);

glob is an asynchronous function so results are provided in a callback and not returned synchronously.
You can also test you glob expressions using globster.xyz

A: Haven't used golb.Hope this will help you.
var fs=require('fs');
var pattern=RegExp('.md$');//Enter file extension here
fs.readdir('..//',(err,files)=>{
      //console.log(files);
      if(files.find((file)=>{return pattern.test(file)==true;})){
          //console.log('file found');  your code
        }
       else{
         //console.log('file not found'); your code
        }
    });


text:
Q: Auto-fitting panels with CSS Is there any CSS rule that will render a widget to fit on the browser page even if the browser window is resized?
I mean so I wont have to do handlers to monitor window resize events?


text:
Q: Como iniciar un proyecto JSP con una ruta en particular? Tengo un proyecto JSP antiguo para el cual uso eclipse como ide.
Una vez que todo esta configurado y pruebo que funciona, quiero que el mismo se inicie en otra ruta distinta a la ruta por defecto que lanza eclipse.
cuando lanzo el proyecto, el mismo se ejecuta en http://localhost:8080/miapp/. Pero yo quiero que al ejecutar, el mismo se ejecute en http://localhost:8080/miapp/menu/mijsp.jsp
Como bonus, quiero pasarle parametros para que quede de la forma: http://localhost:8080/miapp/menu/mijsp.jsp?param1=aaa?param2=bbb
Cuando lo ejecuto, y escribo la ruta a mano va a esa pagina, con lo cual el proyecto funciona.
La estructura de carpetas de mi proyecto es asi:

Yo supongo, que tengo que modificar algo en Deployment Descriptor, pero para variar no encuentro nada que me diga que modificar ni como...
Bonus extra: si alguien sabe como modificar la ruta para que donde dice miapp pueda cambiarlo, se lleva un cafe extra...

A: Empiezo con el bonus extra:
Tomcat por defecto usa el nombre del fichero war como nombre de la aplicación. Al desplegar desde eclipse tienes que decirle al IDE que use otro nombre, lo que significa cambiar el "contexto" de miapp a algún otro:

Ahora la otra pregunta:
¿Cómo usar /menu en lugar de /? Pues básicamente redirigiendo: mueve el fichero jsp que quieres cargar al directorio /menu y en raíz puedes poner un fichero index.jsp que reenvíe al navegador a donde quieres:
<c:redirect url="/menu/mijsp.jsp"/>

Una pega es que si quieres usar parámetros aquí, no se pasarán al destino.
Por tanto se podría hacer un forward, haciendo que ambas URLs sean equivalentes (en este caso no se envía al cliente a una nueva URL, sino que un JSP delega en otro:
<jsp:forward page="/menu/mijsp.jsp" />


text:
Q: Internet disconnects intermittently using Realtek RTL8111 The broadband Ethernet connection stops to work or rather stays connected but stops loading pages and showing content on the Internet with a server not found error. The connection information states the Internet is connected with a correct IP configuration but still the surfing problems occur quite frequently and suddenly starts working after few minutes.
How can this be resolved?
On running: sudo lshw -C network
 *-network
       description: Ethernet interface
       product: RTL8111/8168B PCI Express Gigabit Ethernet controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:07:00.0
       logical name: eth0
       version: 07
       serial: d4:be:d9:2a:16:09
       size: 100Mbit/s
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=full firmware=rtl8168e-3_0.0.4 03/27/12 ip=115.252.220.236 latency=0 link=yes multicast=yes port=MII speed=100Mbit/s
       resources: irq:42 ioport:2000(size=256) memory:c1404000-c1404fff memory:c1400000-c1403fff
  *-network
       description: Wireless interface
       product: Centrino Wireless-N 2230
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:08:00.0
       logical name: wlan0
       version: c4
       serial: 68:5d:43:45:67:4e
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlwifi driverversion=3.8.0-6-generic firmware=18.168.6.1 latency=0 link=no multicast=yes wireless=IEEE 802.11bgn
       resources: irq:47 memory:c1500000-c1501fff


text:
Q: Ayuda para migrar Laravel 5.2 a Producción He estado buscando en internet y he encontrado diferentes respuestas pero ninguna se acerca a lo que busco. Necesito migrar una aplicación de Laravel 5.2 de mi servidor local a uno remoto y para eso, necesito crear su correspondiente base de datos.
Mi problema concreto es que no sé cómo instrumentar las migraciones de Laravel para recrear las tablas en la nueva BD.
He probado con php artisan migrate:reset y php artisan migrate:truncate y siempre se crean un par de tablas, pero no todas...
¿Cómo debería hacer?

A: Me ha pasado que no se crean mis tablas cuando tienen relaciones.
Para solucionar el problema primero creo las tablas que no reciben la relación y después las que si tienen la llave foránea.
Para regresar las tablas usa
php artisan migrate:rollback

A: Has probado con:
php artisan migrate

Desde el server de producción debes ejecutar este comando, con la base de datos vacía, esto ejecuta todas las migraciones programadas.

A: Debes utilizar el siguiente comando:
php artisan migrate:refresh

Si tienes seeders que ejecutar a continuación de la migración, lo puede hacer de la siguiente manera:
php artisan migrate:refresh --seed

A: Mi solución fue utilizar composer dump-autoload, php artisan optimize y luego php artisan migrate:refresh --seed.
Esto solucionó problemas que tenía con migrate:rollback y migrate:reset. Gracias de todas formas...

A: Como ya tienes tu base de datos completa y funcionando en local, la forma fácil de llevarla al servidor de producción, y de paso guardar una copia de seguridad, será hacer un volcado del SQL desde un gestor como phpMyAdmin y usar ese mismo SQL para recrearla en el servidor, nuevamente con ayuda de un gestor.


text:
Q: Pass PHP variable to .js file (jQuery) Let's say i have a variable in a php-file (index.php):
$PHP_variable = "string";

And i want to pass it to my JS file (functions.js) that's currently being read within the php-file. Is that possible?
For example, i have this in my php-file:
 <input type="text" name="textfield" value="'.$PHP_variable.'" />
 <input type="button" id="actionButton" />

And in the js-file:
$('#actionButton').click(function(){
 alert(THE_PHP_VARIABLE);
});

How is it possible to pass $PHP_variable to the js file? I'd prefer not to use the js code directly on the php-script (i know how to solve it that way).

A: It sounds like you're thinking of using PHP to generate Javascript, which is possible although it's a bit odd.  It's also curious that you really aren't passing the variable, you're using it to render a javascript variable of the same value.
Instead, I think what you'd really want to do is use JS to read the variable from the HTML element's value attribute, since you're already storing the variable's value there.
This can be done a lot of ways, but since it looks like you're using jQuery it'd just be:
$('#actionButton').click(function(){
  $value = $this.attr('value');
  alert($value);
});

A: You were almost there -
$('#actionButton').click(function(){
    var THE_PHP_VARIABLE = $('input[name="textfield"]').val();
    alert(THE_PHP_VARIABLE);
});

Since the value is echo'd out when the page loads you can get that quite easily by using val() on the correct element.
If you want to assigned variables at the time the page is loaded you could also do this in your PHP -
<script type="text/javascript">
<?php
   echo "var THE_PHP_VARIABLE = " . $PHP_variable .";";
?>
</script>

A: Thanks for all the answers, i chose to use a hidden input field with an id and the php-variable as the value for this input, then in the js-file i simply get the val() from this hidden input
$input_val = $('#hiddenInputID').val();


text:
Q: storing lines in an array awk I have a file "test"cat , below is the content of the file :
a,s,d,e,g,h,j,k,l
q,w,e,e,t,y,u,i,o,k,i
z,x,c,f,b,n,m,a,s,j
q,a,z,e,s,x,e,d,c,ty,yt
w,s,c,f,d,c,r,f,v,o,o,o,y,i
t,g,b,e,h,n,u,h,n

now with respect to $4 column, i have to keep line into array and then print the same at the last :
output should be like this :
e :: a,s,d,e,g,h,j,k,l
e :: q,w,e,e,t,y,u,i,o,k,i
e :: q,a,z,e,s,x,e,d,c,ty,yt
e :: t,g,b,e,h,n,u,h,n
f :: z,x,c,f,b,n,m,a,s,j
f :: w,s,c,f,d,c,r,f,v,o,o,o,y,i

I am doing it through awk with below command, but not getting proper output.
awk -F"," '{sessions[$4]++;event_arr[$4][sessions[$4]]=$0; } END{ for ( i in sessions) {for (j in event_arr[i]) print i,"::",event_arr[i][j]}}'  test

#output
e :: t,g,b,e,h,n,u,h,n
e :: a,s,d,e,g,h,j,k,l
e :: q,w,e,e,t,y,u,i,o,k,i
e :: q,a,z,e,s,x,e,d,c,ty,yt
f :: z,x,c,f,b,n,m,a,s,j
f :: w,s,c,f,d,c,r,f,v,o,o,o,y,i

The issue, I am getting with the command is I am not getting output in proper sequence.

A: Simple awk + sort approach:
awk -F, '{ print $4" :: "$0 }' test | sort -t,

The output:
e :: a,s,d,e,g,h,j,k,l
e :: q,a,z,e,s,x,e,d,c,ty,yt
e :: q,w,e,e,t,y,u,i,o,k,i
e :: t,g,b,e,h,n,u,h,n
f :: w,s,c,f,d,c,r,f,v,o,o,o,y,i
f :: z,x,c,f,b,n,m,a,s,j

A: If you're using GNU awk, you can control how associative arrays are traversed: https://www.gnu.org/software/gawk/manual/html_node/Controlling-Scanning.html#Controlling-Scanning
For instance, here, you want to scan through the array with the keys sorted numerically, so
 awk -F, '
      {
          sessions[$4]++
          event_arr[$4][sessions[$4]]=$0
      }
      END {
          PROCINFO["sorted_in"] = "@ind_num_asc"
          for ( i in sessions)
              for (j in event_arr[i])
                  print i,"::",event_arr[i][j]
      }
  '  test

However, that might destroy the alphabetical ordering of column 4
The issue is that you need to mix associative arrays and numerically indexed arrays. I'd head to a language like perl where that is more explicit:
perl -F, -ane '
    push @{$event{$F[3]}}, "$F[3] :: $_"
  } END {
    for $key (sort keys %event) {print join("", @{$event{$key}})}
' test

%event is a hash (an associative array).
$event{$key} is an array (numerically indexed).
In perl parlance, this is a hash-of-arrays.


text:
Q: DBUnit ignores column aliases, when creating dataset from query? I have two datasets, which I want to compare with DBUnit: one defines as XML file, the other I am trying to create using a query:
dbConnection.createQueryTable("my_table", "SELECT ...");

Select goes over couple of tables, where the few of them has the same column names, so I am using aliases to distinguish between them. The query runs fine, but seems that while creating a dataset, DBUnit ignores the column aliases and uses the original names instead. This clearly is seen in DEBUG log:
01.03.13 14:18:43,228 [ DEBUG] AbstractDatabaseConnection - createQueryTable(resultName=my_table, sql=
        SELECT `table1`.`name`
            , `table2`.`label` AS `table2_label`
            , `table3`.`label`
        FROM `table1`
            , `table2`
            , `table3`
        WHERE `table1`.`id` = `table2`.`table1_id`
            AND `table2`.`id` = `table3`.`table2_id`
    ) - start
01.03.13 14:18:43,228 [ DEBUG] DatabaseDataSourceConnection - getConnection() - start
01.03.13 14:18:43,228 [ DEBUG] DatabaseConfig$Configurator - Statement fetch size set to 100
01.03.13 14:18:43,240 [ DEBUG] DatabaseDataSourceConnection - getConnection() - start
01.03.13 14:18:43,240 [ DEBUG] DatabaseTableMetaData - The 'schemaName' from the ResultSetMetaData is empty-string and not applicable hence. Will not try to lookup column properties via DatabaseMetaData.getColumns.
01.03.13 14:18:43,240 [ DEBUG] DatabaseTableMetaData - The 'schemaName' from the ResultSetMetaData is empty-string and not applicable hence. Will not try to lookup column properties via DatabaseMetaData.getColumns.
01.03.13 14:18:43,240 [ DEBUG] DatabaseTableMetaData - The 'schemaName' from the ResultSetMetaData is empty-string and not applicable hence. Will not try to lookup column properties via DatabaseMetaData.getColumns.
01.03.13 14:18:43,240 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=0, columnName=name) - start
01.03.13 14:18:43,240 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=0, columnName=label) - start
01.03.13 14:18:43,240 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=0, columnName=label) - start
01.03.13 14:18:43,240 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=1, columnName=name) - start
01.03.13 14:18:43,241 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=1, columnName=label) - start
01.03.13 14:18:43,241 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=1, columnName=label) - start
01.03.13 14:18:43,241 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=2, columnName=name) - start
01.03.13 14:18:43,241 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=2, columnName=label) - start
01.03.13 14:18:43,241 [ DEBUG] ForwardOnlyResultSetTable - getValue(row=2, columnName=label) - start

As you see - getValue(row=X) uses label as name for table2 and table3 columns and not table2_label and label as defined in query...
How to solve this? I am using MySQL database.

A: This looks like its caused by a change in the MYSQL Java connector
Caused by DatabaseTableMetaData calling ResultSetMetaData#getColumnName() rather than #getColumnLabel()
You don't state what version of DBUnit/MySql you are using, but DBUnit 2.2 & 2.4.9 are affected with MySql connector 5.1.26.
As a workaround, the MySQL devs have included a backward compatability option, discussed in the change above.
To configure it, add a property to your JDBC url:
jdbc:mysql://host/db_name?useOldAliasMetadataBehavior=true
As per these instructions.


text:
Q: Synchronous Save in Parse using Swift Using Swift 2.1 (Xcode 7.2.) and Parse 1.12.0, I'm getting an error that PFObject.save() is unavailable in Swift.  My code is:
 let operation = NSBlockOperation { () -> Void in

        do {
            let success = try rating.save()
        }
        catch let er as NSError {
            error = er
        }
    }

In PFObject+Synchronous.h, there is this:
///--------------------------------------
#pragma mark - Saving Objects
///--------------------------------------

/**
 *Synchronously* saves the `PFObject`.

 @return Returns whether the save succeeded.
 */
- (BOOL)save PF_SWIFT_UNAVAILABLE;

/**
 *Synchronously* saves the `PFObject` and sets an error if it occurs.

 @param error Pointer to an `NSError` that will be set if necessary.

 @return Returns whether the save succeeded.
 */
- (BOOL)save:(NSError **)error;

So it seems as if Xcode can't tell which function to use:  it should try to use the one that handles the error.  Is there a way of forcing this, or am I calling the function incorrectly?

A: Although the function not marked as unavailable to swift:
-(BOOL)save:(NSError **)error

is defined to return a bool, the Swift implementation (which throws) apparently does not, so the code compiles fine if I'm not expecting to receive a return value, i.e.:
 let operation = NSBlockOperation { () -> Void in

        do {
            try rating.save()
        }
        catch let er as NSError {
            error = er
        }
    }

I'm still now sure how I could have determined this without trial and error.

A: The first overload is marked unavailable to Swift, hence it is not visible.
The second overload is made available, but as you discovered yourself, it requires a try since it returns a NSError output parameter. The BOOL return value in Cocoa is there to indicate whether the operation was successful or not. In Swift, this is handled by catching the NSError instead. This behaviour was introduced in (I think) Swift 2.0, and is documented here.
To summarize, an Obj-C method
- (BOOL) doSomething:(NSError**)error {}

maps to the following Swift method
func doSomething() throws


text:
Q: How to access any control inside Hubsection Datatemplate in Windows 8.1 store Please tell me how to access flipview control inside Hubsection *DataTemplate*

A: The best way to deal with this is to have a user control inside the DataTemplate.
And UserControl will have the Flipview, so you can easily access the flipview there.

A: I don't know if you managed to solve your problem already. If you didn't here is how.
private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
    {
        int childNumber = VisualTreeHelper.GetChildrenCount(control);
        for (int i = 0; i < childNumber; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(control, i);
            FrameworkElement fe = child as FrameworkElement;
            // Not a framework element or is null
            if (fe == null) return null;

            if (child is T && fe.Name == ctrlName)
            {
                // Found the control so return
                return child;
            }
            else
            {
                // Not found it - search children
                DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
                if (nextLevel != null)
                    return nextLevel;
            }
        }
        return null;
    }

usage is very simple, for example in my case
ComboBox cb= FindChildControl<ComboBox>(HUB_HC, "SemanaHC") as ComboBox;

Where HUB_HC is my HubSection name and SemanaHC is a combobox inside that HubSection witch is also inside of a StackPanel. It works for me and it's simple to use
Reference: How to access a Control inside the data template in C# Metro UI in the code behind

A: To access any control inside a HubSection you can do something like this:
var sec = MyHub.Sections[2];
var btn = sec.FindVisualChild("MyButton") as Button;

EDIT: in order to use FindVisualChild extension method you have to use MyToolkit project. You can download it as a Nuget Package and see the project here.
Hope it helps!
:D
EDIT 2: The code for FindVisualChild can be found here: https://mytoolkit.codeplex.com/SourceControl/latest#Shared/UI/FrameworkElementExtensions.cs

A: var sec = testHub.Sections[0];
var gridViewSelect = sec.FindName("Section4Header") as GridView;
FindName does the trick...


text:
Q: Regex website path I have a bit of an unusual question, I think.  I'm working on a project (in PHP / MySQL) where a user can supply a path written as a regular expression, and the site will load some content based off of that.  So say, for example, someone supplies this regular expression:
articles\/([0-9]+)$

When someone visits http://example.com/articles/3, it will load that particular page with its content and settings associated with it.  All of these paths are stored in a MySQL database.  When a user visits the site, it checks the URL against the database of regular expressions and finds the appropriate content to display.
Here's my problem: A user can associate any number of regular-expression paths with any number of other pages, and they can be very similar to any other regular expressions.  My immediate thought would be to narrow down a search based off of the beginning of the URL (after example.com/, of course), and peek through all of the options until it finds an exact match.  I'm concerned, though, because in the worst case it could look through dozens if not more of options before finding an exact match...and that would waste valuable resources.
Does anyone have any thoughts about how I could improve the system?
Thanks in advance.

A: If that regex match number is a primary key in your table, the performance shouldn't even be a problem (should take a fraction of a second), assuming you have less than a million articles in your website.
Also use caching to improve performance.

A: My only suggestion would be to cache the results of the matches in another mysql table. Searching that will be fast since its indexed, then if no match is found, go through your regexes and apply them. When regexes are deleted or updated, remember to remove the cache associated with that regex.


text:
Q: DNS records for both FTP/HTTP server I just registered a free domain using Freenom, that I plan to use for my single device which is both FTP and HTTP server. I have set these DNS records (not using real names):
|NAME | TYPE  |      TARGET      |
----------------------------------
| www |   A   |   99.99.99.99    |
|     | CNAME |   www.foo.tk     |

When i type either foo.com or www.foo.tk, i can access website running on my server. But when I want to access the FTP server, I always have to type ftp://foo.tk or ftp://www.foo.tk.
Now what I would like to do is that I could access my FTP server by typing for example ftp.foo.tk and HTTP server by typing web.foo.tk
Is it possible ? And if so, how can it be done ?

A: I would recommend using different IP for different services, even when running them in the same machine.
If it is possible, of course. Otherwise you can use another CNAME record for the ftp service, but:

*

*the IP will be the same for both names

*the web server can manage diferent web services for diferent names even when using the same IP (configuration depends on the server you are using)

*ftp protocol does not know about domain names, just the IP it is listening, so it will work the same way for every domain name (ftp://ftp.foo.tk, ftp://www.foo.tk and ftp://foo.tk).

So the DNS entries would look like this.
|NAME | TYPE  |      TARGET      |
----------------------------------
| www |   A   |   99.99.99.99    |
| ftp | CNAME |   www.foo.tk     |
|     | CNAME |   www.foo.tk     |

A: This setup will sometimes work but many servers will complain about it and give wrong results if they have a cache.
DNS standards don't support using CNAME records with the same name as any other record because the CNAME is supposed to represent an alias for another name (not just the "A" record type). Your zone "foo.tk" requires at least a SOA record on the name foo.tk so it can't have a CNAME.
www.foo.tk. CNAME foo.tk. is OK
foo.tk. CNAME www.foo.tk. is NOT OK

The easy fix is to set it up just opposite:
|NAME | TYPE  |      TARGET      |
----------------------------------
|     |   A   |   99.99.99.99    |
| www | CNAME |   foo.tk         |