text:
Q: How do I call a method in ir.rule domain in Odoo? I'd like to create a record rule for my app.
Here is my XML:
<record model="ir.rule" id="ir_rule_something">
    <field name="name">something</field>
    <field name="model_id" ref="model_something"/>
    <field name="domain_force">[('agent','in',function_that_return_list_of_ids)]</field>
    <field name="perm_read" eval="True"/>
    <field name="perm_write" eval="False"/>
    <field name="perm_unlink" eval="False"/>
    <field name="perm_create" eval="False"/>
</record>

I would like the function_that_return_list_of_ids to return a list of id. Where do I put the method and how do I call it?

A: The easiest way will be for you to override _eval_context  or _eval_context_for_combinations in ir.rule itself.
class MyIrRule(models.Model):
    _inherit ="ir.rule"

    @api.model
    def _eval_context(self):
        context = super(MyIrRule,self)._eval_context()
        context.update(function_of_ids=function_of_ids)

In this example, function_of_ids is not a method but a simple function.

A: I found out another method to call a function from ir.rule.
Here it is.
<record id="manager_asterisk_cdr_rule" model="ir.rule">
    <field name="name">Manager Asterisk CDR rule</field>
    <field name="perm_write" eval="1"/>
    <field name="perm_read" eval="1"/>
    <field name="perm_create" eval="1"/>
    <field name="perm_unlink" eval="1"/>
    <field name="groups" eval="[(6,0, [ref('group_barrier_manager')])]"/>
    <field name="model_id" ref="asterisk_base.model_asterisk_cdr"/>
    <field name="domain_force">user.manager.get_cdr_domain()</field>
</record>

The main part is:
<field name="domain_force">user.manager.get_cdr_domain()</field>

And here is the function:
@api.multi
def get_cdr_domain(self):
    # Used from facility_manager/security.xml to filter CDR records
    facility_ids = [f.id for f in self.facilities]
    barriers = self.env['barrier.barrier'].search(
                                        [('facility', 'in', facility_ids)])
    numbers = []
    for b in barriers:
        # Add barrier access phones
        numbers.extend([a.number for a in b.access_phones])
        # Add panels GSM number
        numbers.extend(
            [p.gsm_number for p in b.call_panels if p.gsm_number])
        # Add panels SIP number
        numbers.extend(
            [p.sip_number for p in b.call_panels if p.sip_number])
    # Add keys of type=phone
    key_numbers = [k.number for k in self.env[
        'barrier.resident_key'].search([
                                       ('facility', 'in', facility_ids),
                                       ('key_type', '=', 'phone')])]
    numbers.extend(key_numbers)
    domain = ['|', ('src', 'in', numbers), ('dst', 'in', numbers)]
    return domain

Also when you add new records to the models requested from the function you need to clear cache:
self.env['ir.rule'].clear_cache()


text:
Q: Enable Ports on Ubuntu Server - NGINX Reverse Proxy My private IP is e.g. 175.34.55.2
ubuntu@ip-175-34-55-2:~$ sudo nmap -sT -p- 175.34.55.2
Not shown: 65531 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
3128/tcp open  squid-http
8080/tcp open  http-proxy

I have working reverse proxy on port 8080. How do I open port 8181, 8282, or 3000 on Ubuntu 18.4 so that I can use it with reverse proxy in Nginx?
My Nginx default file:
location /api1 {
    proxy_pass http://175.34.55.2.7:8080;
    ...
}
location /api2 {
    proxy_pass http://175.34.55.2.7:8181;
    ...
}
location /api3 {
    proxy_pass http://175.34.55.2.7:8282;
    ...
}

A: I am not so sure, what you really want to achieve.
Normally, in general case, I do not think it is a good idea to make your webserver to listen on set of extraordinary ports.
Taking security to the game, we use Mandatory Access Control and services like SELinux or AppArmor to protect our servers to do not listen on such weird ports. It limits attack vector.
Said that, I think you can achieve the same with virtual host functionality.
Answering the question, you just need to add another set of servers for nginx.
server {
    listen      175.34.55.2.7:8282;
    ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uploading a video from the android gallery to Firebase Storage with react-native I am currently working on a react-native project where the user can upload a video from his app to firebase storage.
The user can either select a video from his library or take a new one directly in the app. I use the react-native-image-picker library.
On IOs everything is working as expected. On Android I only managed to upload videos taken directly in the app or small videos from the android gallery.

If I try to upload videos from the android gallery I encounter two problems:

*

*Error: [storage/unknown] Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/video:723 from pid=32673, uid=10226 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

This Error occurs if try to upload the video directly with the link I get from the image picker library.
   let reference = storage().ref(path);
   let task = reference.putFile(imagePickerResponse.assets[0].uri);

I managed to resolve this issue by using the RNFS library. react-native-fs
   const data = await RNFS.readFile(imagePickerResponse.assets[0].uri, 'base64');
   let task = reference.putString(data, 'base64');

But this solution only works for small files. For longer videos the app crashs and I get the following error.

*Could not invoke RNFSManager.readFile:

Could not invoke RNFSManager.readFile

null

Failed to allocate a 268435472 byte allocation with
6291456 free bytes and 116MB until OOM, target
footprint 152234472, growth limit 268435456

Unfortunately I couldnt find any solution online. Is there any way to upload large video from the Android library to firestore storage?

Image Picker Code
export const SelectVideoAction: CameraAction = {
  title: 'Select Video',
  type: 'library',
  options: {
    selectionLimit: 0,
    mediaType: 'video',
  },
};
launchImageLibrary(SelectVideoAction.options, handleResponse);

Android Upload Code
let reference = storage().ref(targetPath);
let task = reference.putFile(imagePickerResponse.assets[0].uri);
if (Platform.OS === 'android' && fromLibrary) {
  const data = await RNFS.readFile(imagePickerResponse.assets[0].uri, 'base64');
  task = reference.putString(data, 'base64');
}

task
  .then(() => {
     console.log('Image uploaded to the bucket!');
  })
  .catch((e) => console.log('uploading image error => ', e));

Dependencies
"dependencies": {
...
    "react": "17.0.2",
    "react-native": "0.66.3",
    "react-native-image-picker": "^4.0.6",
    "react-native-fs": "^2.18.0",
...
}

A: Main idea is to split the large video file into chunks, by this way it will not exceed the memory limit of the device and provide a more systematic upload process. Description for the solution sounds pretty good, but it can be very difficult to implement.
There is a package that can do chunk operation: React Native Chunk Upload. Does the default version of firebase storage allow chunk upload operations or this package compatible with firebase? I'm not sure but you can give it a try Uploading large files on web using Firebase. You have to change some configurations on firebase side and android permission, which is mentioned in documentation.
At the end of the day, you can consider using more suitable/powerful video storage/streaming service. (Google Cloud Storage (Multiple Chunk Upload), Cloudflare Stream, Mux)
I realize this isn't a complete answer, but I wanted to share it as it might help you or someone else.


text:
Q: Issue with RenderFragment in Blazor after leaving page with injected scripts So, I've been learning how to create dynamic html in Blazor using RenderFragment,
most the test have worked ok so far, except when generating html which injects javascript that modifies the end result.
In this case I'm generating the scripts for the LinkedIn button
public RenderFragment RenderButton()
{
    RenderFragment form = b =>
    {
        if (this.AddPlatformScript)
        {
            b.OpenElement(1, "script");
            b.AddAttribute(1, "src", "https://platform.linkedin.com/in.js");
            b.AddAttribute(1, "type", "text/javascript");
            b.CloseElement();
        }
        b.OpenElement(2, "script");
        b.AddAttribute(2, "data-url", $"{this.UrlToShare}");
        b.AddAttribute(3, "type", "IN/Share");
        b.CloseElement();
    };
    return form;
}

The code to render the items is the following
public RenderFragment UIFragment { get; private set; }
    protected override void OnInitialized()
    {
        this.UIFragment = this.RenderButton();
    }

The issue is that as soon as I leave that page I get the following error
**crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Cannot read property 'removeChild' of null
      TypeError: Cannot read property 'removeChild' of null
          at e (https://localhost:5001/_framework/blazor.webassembly.js:1:6918)
          at e (https://localhost:5001/_framework/blazor.webassembly.js:1:6890)
          at Object.e [as removeLogicalChild] (https://localhost:5001/_framework/blazor.webassembly.js:1:6890)
          at e.applyEdits (https://localhost:5001/_framework/blazor.webassembly.js:1:13649)
          at e.updateComponent (https://localhost:5001/_framework/blazor.webassembly.js:1:12880)
          at Object.t.renderBatch (https://localhost:5001/_framework/blazor.webassembly.js:1:1704)
          at Object.window.Blazor._internal.renderBatch (https://localhost:5001/_framework/blazor.webassembly.js:1:34784)
          at _mono_wasm_invoke_js_unmarshalled (https://localhost:5001/_framework/wasm/dotnet.3.2.0.js:1:172099)
          at wasm_invoke_iiiiii (https://localhost:5001/_framework/wasm/dotnet.wasm:wasm-function[3160]:0x9b33d)
          at icall_trampoline_dispatch (https://localhost:5001/_framework/wasm/dotnet.wasm:wasm-function[5777]:0xfe711)
Microsoft.JSInterop.JSException: Cannot read property 'removeChild' of null
TypeError: Cannot read property 'removeChild' of null
    at e (https://localhost:5001/_framework/blazor.webassembly.js:1:6918)
    at e (https://localhost:5001/_framework/blazor.webassembly.js:1:6890)
    at Object.e [as removeLogicalChild] (https://localhost:5001/_framework/blazor.webassembly.js:1:6890)
    at e.applyEdits (https://localhost:5001/_framework/blazor.webassembly.js:1:13649)
    at e.updateComponent (https://localhost:5001/_framework/blazor.webassembly.js:1:12880)
    at Object.t.renderBatch (https://localhost:5001/_framework/blazor.webassembly.js:1:1704)
    at Object.window.Blazor._internal.renderBatch (https://localhost:5001/_framework/blazor.webassembly.js:1:34784)
    at _mono_wasm_invoke_js_unmarshalled (https://localhost:5001/_framework/wasm/dotnet.3.2.0.js:1:172099)
    at wasm_invoke_iiiiii (https://localhost:5001/_framework/wasm/dotnet.wasm:wasm-function[3160]:0x9b33d)
    at icall_trampoline_dispatch (https://localhost:5001/_framework/wasm/dotnet.wasm:wasm-function[5777]:0xfe711)
  at Microsoft.JSInterop.WebAssembly.WebAssemblyJSRuntime.InvokeUnmarshalled[T0,T1,T2,TResult] (System.String identifier, T0 arg0, T1 arg1, T2 arg2) <0x2cc84f0 + 0x00046> in <filename unknown>:0
  at Microsoft.JSInterop.WebAssembly.WebAssemblyJSRuntime.InvokeUnmarshalled[T0,T1,TResult] (System.String identifier, T0 arg0, T1 arg1) <0x2cc8410 + 0x00014> in <filename unknown>:0
  at Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer.UpdateDisplayAsync (Microsoft.AspNetCore.Components.RenderTree.RenderBatch& batch) <0x2cc8318 + 0x0001e> in <filename unknown>:0
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue () <0x2b76b80 + 0x000f2> in <filename unknown>:0
f.printErr @ blazor.webassembly.js:1
f.preRun.push.window.Blazor._internal.dotNetCriticalError @ blazor.webassembly.js:1
_mono_wasm_invoke_js_unmarshalled @ dotnet.3.2.0.js:1
do_icall @ dotnet.wasm:1
do_icall_wrapper @ dotnet.wasm:1
interp_exec_method @ dotnet.wasm:1
interp_runtime_invoke @ dotnet.wasm:1
mono_jit_runtime_invoke @ dotnet.wasm:1
do_runtime_invoke @ dotnet.wasm:1
mono_runtime_invoke_checked @ dotnet.wasm:1
mono_runtime_try_invoke_array @ dotnet.wasm:1
ves_icall_InternalInvoke @ dotnet.wasm:1
ves_icall_InternalInvoke_raw @ dotnet.wasm:1
do_icall @ dotnet.wasm:1
do_icall_wrapper @ dotnet.wasm:1
interp_exec_method @ dotnet.wasm:1
interp_runtime_invoke @ dotnet.wasm:1
mono_jit_runtime_invoke @ dotnet.wasm:1
do_runtime_invoke @ dotnet.wasm:1
mono_runtime_try_invoke @ dotnet.wasm:1
mono_runtime_invoke @ dotnet.wasm:1
mono_wasm_invoke_method @ dotnet.wasm:1
Module._mono_wasm_invoke_method @ dotnet.3.2.0.js:1
call_method @ dotnet.3.2.0.js:1
(anonymous) @ dotnet.3.2.0.js:1
beginInvokeDotNetFromJS @ blazor.webassembly.js:1
s @ blazor.webassembly.js:1
e.invokeMethodAsync @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
r @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
r @ blazor.webassembly.js:1
d @ blazor.webassembly.js:1
f @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
e.onGlobalEvent @ blazor.webassembly.js:1

Does anyone knows how to prevent this from happening?

A: Blazor needs the generated html to remain unaltered or it can't find elements reliably to remove from the DOM.
If you want it to be altered you need to add it using AddMarkup passing in an instance of MarkupString that contains all the html you want your JS to be allowed to modify.


text:
Q: how to export/import websites,stores,store-views? I have a Magento install with 58 websites, and i need to recreate them in a new installation. Is there any way to export the database table which handle this?, and then import it in the new DB?.
Thanks!

A: These 3 tables needs to be exported/imported to recreate websites/stores/store-views in a different Magento install:

*

*core_website

*core_store_group

*core_store


text:
Q: Cannot boot to USB Boot-Repair stick I have W10 and 2 other Debian-based partitions on an UEFI/GPT SSD and am well used to using Boot-Repair(BR). As of this morning, without any relevant previous activity by me yesterday, my system just goes to a Grub2 > prompt when I turn my system on.
So as usual, I get out my trusted BR USB stick, however this time I could not  boot from it, although I have recreated the BR stick several times using all possible MBR/GPT options using Rufus, with no luck.
If I interrupt the Boot process with F12, I get a choice of Samsung EVO SSD, Windows Boot Manager, and various EFI boot options(USB HDD, USB CD-ROM etc.). Selecting anything but WBM gets the same GRUB2> prompt, but selecting WBM gets at least W10 loaded. I also turned Safe Boot off
Suspecting a BIOS problem, I reflashed the BIOS without any change.
So my status is now:

*

*Grub obviously damaged, no Linux system can be started

*Cannot do a Boot Repair as no boot from USB stick possible.

Has anyone any ideas?

A: Not exactly an answer so please treat this as a comment. I had an almost similar problem yesterday which is solved this afternoon.
My system has 3 primary partitions (Recovery, System Reserved, W7) and logical partitions for, among of which, W10 and Xubuntu 17.04. The W10 partition got erroneous and I deleted it, I thought it will be okay since I believed I can still boot to W7 or Xubuntu. I didn't ran update-grub nor grub-install. But, when I restarted, it is showing GRUB2> prompt.
Fortunately I have a couple of USB sticks with live/persistent USBs (Ubuntu 16.10 and Tahrpup), so I plugged each one of them, but the screen kept showing GRUB2> prompt. I did noticed, however, a couple of days ago when it's a cold boot (turned off laptop, plugin the USB, and press the power on), the laptop skips the USB drives (it's an old laptop so the ports are probably rusty).
So when the screen shows the infamous GRUB2> prompt, I plugged in one bootable USB, restart the laptop (instead of turned it off), and voila! The laptop reads from USB again. Next step involved update-grub nor grub-install and boot is good again.
Another workaround would probably booting a GNU/Linux ISO from Windows. I haven't tested it, so I can't comment much, but from a quick research it seems doable using third-party bootloader, or even better: using Windows own Disk Management GUI to create/attach VHD containing GNU/Linux ISO.

A: Try putting my rEFInd boot manager on a USB flash drive or CD-R. (Download links for both types of images are on that page.) If Secure Boot is disabled on the computer, rEFInd should boot and give you options to boot both Windows and Ubuntu, and if Ubuntu boots properly, you'll then be able to perform better diagnosis and repair in Ubuntu. You could also try Ubuntu on one USB drive and your Ubuntu installation/emergency disk on another one. That combination might enable you to boot the Ubuntu emergency disk, if you can get rEFInd to start.
If rEFInd won't start from the external medium, then Secure Boot might be enabled, or there might be something weird going on that's preventing the computer from booting from external media. This could be a physical problem (a loose wire, corroded contact, etc.) or some obscure firmware setting to prevent it from booting external media. You might use the Windows reboot-to-firmware feature to boot into the firmware to check its options (or enter the firmware settings using whatever keystroke does that for your computer as you power on). In case it's a physical problem, switching your USB drive from one USB plug to another one might help. Removing any USB hubs is also worth trying; a hub might have developed a fault or simply worked its cable loose.
You might also try using the GRUB shell (that grub> prompt you're seeing) to locate the GRUB configuration file and continue the boot process. This article I wrote a few years back describes how to do this; see the "Using the GRUB 2 Shell" section. Here's another article on this subject, that goes into more detail.
Yet another final and desperate approach is to install rEFInd from Windows. The Windows installation process for rEFInd is a bit tedious (see the documentation), but it can be done; and if this works, it should enable you to boot both Windows and Ubuntu. Don't bother with this if rEFInd starts up from a USB drive but can't boot Ubuntu, though; this is intended as a solution if you can't get the USB drive to boot at all.
Note that one possible reason for some of the symptoms you're seeing is that the Ubuntu partition may have been damaged or even deleted. If so, recovery is likely to be difficult or even impossible. You can check some of the basics using Windows partitioning tools; however, unless you install filesystem drivers, you won't be able to dig into the Ubuntu installation, just verify that the partition(s) still exist. You may want to try this before you invest too much effort into getting past the GRUB hurdle; if your Ubuntu filesystem is wiped out, you won't clear that hurdle without re-installing or doing some major repair work.


text:
Q: How to navigate between Stack navigators Reactnative v5 In my App stack i have the following code:
const Stack = createStackNavigator();

const FStack = ({navigation}) => (
    <Stack.Navigator>
      <Stack.Screen
        name="Doc Types"
        component={HomeScreen}
        options={{ header :() => null}}
      />
      <Stack.Screen
        name="P"
        component={PScreen}
      />
       <Stack.Screen
        name="W"
        component={WScreen}
      />

    </Stack.Navigator>
  );

const LStack = ({navigation}) => (
    <Stack.Navigator>
        <Stack.Screen
        name="L"
        component={LScreen}
        options={{ header :() => null}}
      />
      <Stack.Screen
        name="X"
        component={XScreen}
        options={{ header :() => null}}
      />

    </Stack.Navigator>
  );

When I try to run navigation.navigate('X'); from a screen in Fstack to the XScreen in the LStack it returns an error claiming I have no screen with the name XScreen.
Is there a way to solve this or do I have to put the XScreen in the Fstack as well.


text:
Q: How to join two sql select statements side by side I have two select statements and would like to join the results(cat and dog) side by side. Could someone please explain to me how I could do it. I've been trying for a while but can't get it to work.
SELECT kernel.dog_id, animal.name as dog
FROM appointment
LEFT JOIN animal
ON  kernel.dog_id=animal.animal_id;

SELECT kernel.cat_id, animal.name as cat
FROM appointment
LEFT JOIN animal
ON  kernel.cat_id=animal.animal_id;

A: Try this
SELECT kernel.dog_id, D.name as dog , C.name as cat
FROM appointment A
LEFT JOIN animal D ON  kernel.dog_id=D.animal_id;
LEFT JOIN animal C ON  kernel.cat_id=C.animal_id;


text:
Q: Java: Hibernate @OneToOne mapping I'm trying to get Hibernate @OneToOne annotations working and not having much success here...
Let's say I've got a table called status that looks like this:
+------------------------------------------------+
|                     status                     |
+------------------------------------------------+
| id | frn_user_id | frn_content_id |   status   |
+----+-------------+----------------+------------+
|  1 |     111     |        0       |  "active"  |
+----+-------------+----------------+------------+
|  2 |      0      |       222      | "inactive" |
+----+-------------+----------------+------------+

And I've got an entity for User that looks like this:
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "userId")
    private Status status;

    // getters and setters
}

And a similar one for Content, and another entity for Status that looks like this:
@Entity
@Table(name = "status")
public class Status {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;

    @Column(name = "frn_user_id")
    private Integer userId;

    @Column(name = "frn_content_id")
    private Integer contentId;

    @Column(name = "status")
    private String status;

    // getters and setters
}

When I perform a read on User, I expect that User.getStatus() will return a Status object with id=1. Instead, I get an AnnotationException: "Referenced property not a (One|Many)ToOne: Status.userId in mappedBy User.status"
I've poured through docs, tutorials and examples here on SO, but everything I've tried so far has failed.
Also worth noting: This should support a one-to-zero-or-one relationship, as some user and content records will not have a reference in the status table.
Any help would be greatly appreciated!

A: Your Status entity must not have properties userId and contentId of type Integer, mapped with @Column. It must have properties user and content of type User and Content, mapped with @OneToOne:
public class User {
    @OneToOne(mappedBy = "user")
    private Status status;
    // ...
}

public class Status {
    @OneToOne
    @JoinColumn(name = "frn_user_id")
    private User user;
    // ...
}

A user has one status. A status has one user.

A: use this way. Add below field in Customer entity.
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "customer")
private Status status;

and don't add getter and setter for status field in Customer entity.
And add below code to Status Entity.
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer;

Here add the getter and setter for customer field in Status Entity class.
You can see one working example here.


text:
Q: Custom asset compilation in ember.js My project structure is:
myProject
              |
              - ember app
              |
              - my addon

I am developing a product where I have to integrate with 3 or more products. Each integration requires only specific functionalities.I have all my features as components in my addon. Now I have installed my addon in my ember app. So there is an entry in package.json. So the whole addon will be available in the vendor.js file. For example, if my 1st product integration requires only 3 components from my addon , I am expected to give only those 3 components dependencies. But since I have entry in package.json,I am  giving the whole addon. I want to take the entry of my addon from my app package.json, and write only the 3 components in to one file viz..., product1.js etc...For the next integration I will pick only the components required for that integration and write it as produc2.js. In this way I can remove the unnecessary things in the script.And respective integration will include it as a script from their end. So is there any way to satisfy my requirement?

A: Yes, there is, but you'll have to work a bit to make it happen. You'll need to pass flags from the consuming app to your addon using the ember-cli-build.js file. And then in your addon's index.js file you'll need to watch for those flags and use Broccoli to filter down to the appropriate files that you want included in the vendor file.
It's not overly complicated to do, but the Broccoli documentation is relatively sparse at the moment. Would suggest watching videos on this from various conferences and consulting other addons that do it similarly.


text:
Q: How to implement MINUS operator in Google Big Query I am trying to implement MINUS operation in Google Big Query but looks like there is no documentation in Query Reference. Can somebody share your thoughts on this. I have done it in regular SQL in the past but not sure if Google is offering it in Big Query. Your inputs are appreciated. Thank you.

A: Just adding an update here since this post still comes up in Google Search. BigQuery now supports the EXCEPT set operator.
https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#except
select * from t1
EXCEPT DISTINCT
select * from t2;

A: If BigQuery does not offer minus or except, you can do the same thing with not exists:
select t1.*
from table1 t1
where not exists (select 1
                  from table2 t2
                  where t2.col1 = t1.col1 and t2.col2 = t1.col2 . . .
                 );

This works correctly for non-NULL values.  For NULL values, you need a bit more effort.  And, this can also be written as a left join:
select t1.*
from table1 t1 left join
     table2 t2
     on t2.col1 = t1.col1 and t2.col2 = t1.col2
where t2.col1 is null;

One of these should be acceptable to bigquery.

A: What I usually do is similar to Linoff's answer and works always, independently of NULL fileds:
SELECT t1.*
FROM table1 t1 LEFT JOIN
     (SELECT 1 AS aux, * FROM table2 t2)
     ON t2.col1 = t1.col1 and t2.col2 = t1.col2
WHERE t2.aux IS NULL;

This solves the problems with nullable fields.
Notice: even though this is an old thread, I'm commenting just for sake of completeness if somebody gets to this page in the future.


text:
Q: Observed LiveData doesn't really update after first fetch I'm building an offline-first app with the database setup as the single source of truth. I am using Room to simplify the database handling, and LiveData to simplify observable data patterns.
I am also using Retrofit to make any network calls required to populate the database with new data.
I have set up an observer in my Fragment as follows:
private void setUpObserver() {
        tfViewModel = ViewModelProviders.of(getActivity()).get(TFViewModel.class);
        tfViewModel.getAllPosts().observe(getActivity(),
                newPosts -> {
                    if (newPosts != null && newPosts.size() > 0) {
                        lottieAnimationView.setVisibility(View.INVISIBLE);
                        mPostsAdapter.updateItems(newPosts);
                    }
                });
        tfViewModel.fetchNextData(currentPage);
}

When my app first starts, I'm deleberately truncating each table in my database using Room callbacks so that new data is fetched every time. (For testing. This beats the offline-first experience and must not be done in production.)
Anyway, so when it first starts, it calls the fetchNextData method of the viewmodel which in turn asks the Repository to fetch the data.
Here's my ViewModel:
public class TFViewModel extends AndroidViewModel {
    private TFRepository mRepository;
    private LiveData<List<Post>> mPostList;

    public TFViewModel(Application application) {
        super(application);
        mRepository = new TFRepository(application);
        mPostList = mRepository.getAllPosts();
    }

    public LiveData<List<Post>> getAllPosts() {
        return mPostList;
    }

    public void fetchNextData(int page) {
        mRepository.fetchNextPosts(page);
    }

}

In the repository, I use my DAOs to insert posts into the database. To fetch new data, I use a Service Class to fetch new data for me. When the fetch call returns, I use an AsyncTask to insert the new posts to my database. (Details omitted for brevity):
public class TFRepository {

    private PostDao postDao;

    private LiveData<List<Post>> postList;

    private RetrofitSingleton retrofitSingleton;

    public TFRepository(Application application) {
        TFRoomDatabase db = TFRoomDatabase.getDatabase(application);

        postDao = db.postDao();
        retrofitSingleton = RetrofitSingleton.getInstance(application.getApplicationContext());
        postList = postDao.getAllPosts();

    }

    public LiveData<List<Post>> getAllPosts() {
        return postList;
    }

    public void fetchNextPosts(int page) {
        getPostList(page);
    }

    private void getPostList(int page) {

        APICaller.getInstance(retrofitSingleton).getFeed(page,
                new NetworkResponseListener<BaseResponse<FeedResponse>>() {
                    @Override
                    public void onResponseReceived(BaseResponse<FeedResponse> feedResponseBaseResponse) {

                        if (feedResponseBaseResponse == null) return;

                        List<Post> posts = feedResponseBaseResponse.getData().getPosts();
                        new insertAllPostsAsyncTask(postDao).execute(posts);
                    }

                    @Override
                    public void onError(String errorMessage) {
                    }
                });

    }
}

The OBSERVER I had setup in my fragment gets an empty list the first time around. The API call returns with the first page of posts and it receives 10 posts the second time. The view is popualted. Everything is good.
Problem: As the user scrolls down, the Fragment asks the ViewModel to fetch more data. The ViewModel asks the Repository to fetch new data. The Retrofit call goes and comes back with the new data. It is inserted in the database. BUT THE OBSERVER IS NOT NOTIFIED. What am I missing?
NOTE: I do not want to use a MutableLiveData as I want to maintain the DB as the single source of truth. Also, as the docs state that LiveData is notified whenever the underlying DB changes, my implementation should work with LiveData.


text:
Q: How can I load PDF files directly from Firebase Storage in Android WebView I am making an Android App which has a feature that allows users to upload and view PDF files. And for the app, Firebase is the backbone. At the current stage of the app, the PDF files get uploaded to Firebase Storage. But I am having a hard time viewing it. I get the download URL from Firebase and use it in the method: webView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + downloadURL) But the WebView shows me a grey background with "No Preview Available" written in the centre. I've opened the download URL on my browser and it displays the file perfectly (indicating that the file exists). How can i fix this issue?

A: just write one line above
 pdf_url=getArguments().getString("pdf_url"); //Ur Firebase Url
    progressBar=view.findViewById(R.id.course_content_progress);

    webView=view.findViewById(R.id.pdfviewr);
    webView.getSettings().setJavaScriptEnabled(true);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

    });

    String url="";
    try {
        url=URLEncoder.encode(pdf_url,"UTF-8"); //Url Convert to UTF-8 It important.
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    webView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url="+url);

it's work for me.
Happy Coding


text:
Q: Highlighting parts of text document with ng2-pdf-viewer I have an application that should be able to display highlighted parts of a pdf-document. The application will be provided a certain line of text from each pdf. I want to be able to input this text-line and highlight this specific part of the pdf-document. I am currently using ng2-pdf-viewer.
I am quite new to angular and how all components interact, so I don't really get how my search()-function bellow can be connected to my acctual pdf-viewer. Right now I just get an error message saying

ERROR TypeError: Cannot read property 'pdfFindController' of undefined

since I haven't really connected the pdf-viewer to the search()-function.
In my ts file I have the following code (I have just included the relevant parts)
import {PdfViewerComponent} from 'ng2-pdf-viewer';

  pdfViewer: PdfViewerComponent;
  stringToSearch = 'hi';

  search() {
    this.pdfViewer.pdfFindController.executeCommand('find', {
      caseSensitive: false, findPrevious: undefined, highlightAll: true,
phraseSearch: true, query: this.stringToSearch
    });
  }

In my html-file I have
<div *ngIf="showPreview" (click)="search()" class="search-result-preview-
   darken">
  <div class="search-result-preview-container">
    <pdf-viewer
      [render-text]="true"
      style="display: block;"
      [src]="(staticUrl+'pdf/'+result.name)">
    </pdf-viewer>

  </div>
</div>

How can I connect these to make my application work as described above?

A: As stated in the Documentation you have to Link the PdfViewerComponent to your component by adding it as @ViewChild:
import {PdfViewerComponent} from 'ng2-pdf-viewer';

  @ViewChild(PdfViewerComponent, {static: false}) private pdfViewer: PdfViewerComponent;
  stringToSearch = 'hi';

  search() {
    this.pdfViewer.pdfFindController.executeCommand('find', {
      caseSensitive: false, findPrevious: undefined, highlightAll: true, phraseSearch: true, query: this.stringToSearch
    });
  }


text:
Q: Define folder depth for the verbose option in Copy-Item cmdlet I'm using the following command to copy a directory tree from one folder to another.
Copy-Item $SOURCE $DEST -Filter {PSIsContainer} -Recurse -Force -Verbose

The verbose option is correctly showing each folder that is copied. However, I would like to tell the Verbose option to only shows the first level of the subfolders that are copied. Hence the subfolders/subfolders/... etc wouldn't appear.
Is it possible?

A: Instead of using the -Verbose option, you could use the -PassThru option to process the successfully processed items via the pipeline. In the following example, I am assuming that $DEST is the existing directory in which the newly copied directory will appear. (You cannot call Get-Item on non-existant objects.)
$SOURCE = Get-Item "foo"
$DEST   = Get-Item "bar"

Copy-Item $SOURCE $DEST -Filter {PSIsContainer} -Recurse -Force -PassThru | Where-Object {

  # Get the parent object.  The required member is different between
  # files and directories, which makes this a bit more complex than it
  # might have been.

  if ($_.GetType().Name -eq "DirectoryInfo") {
    $directory = $_.Parent
  } else {
    $directory = $_.Directory
  }

  # Select objects as required, in this case only allow through
  # objects where the second level parent is the pre-existing target
  # directory.

  $directory.Parent.FullName -eq $DEST.FullName
}

A: Count the number of backslashes in the path and add logic to select first level only perhaps.  Something like this perhaps?
$Dirs=get-childitem $Source -Recurse | ?{$_.PSIsContainer}
Foreach ($Dir in $Dirs){
    $Level=([regex]::Match($Dir.FullName,"'b")).count
    if ($Level -eq 1){Copy-Item $Dir $DEST -Force -Verbose}
    else{Copy-Item $Dir $DEST -Force}}

*Edited to include looping and logic per requirements

A: I would suggest using robocopy instead of copy-item. Its /LEV:n switch sounds like it's exactly what you're looking for. Example (you'll need to test & tweak to meet your requirements):
robocopy $source $dest /LEV:2

robocopy has approximately 7 gazillion options you can specify to get some very useful and interesting behavior out of it.


text:
Q: How to asynchronously download 100000 urls in an efficient way URLSaveAsynchronous can download one url page, how to download 100000 urls in an efficient way?
And better to with an whole progress bar.
I've downloaded 90000 htmls a web-dictionary in mathematica this way, I think it's interesting.
progress= 0.;
progFunction[_, "progress", {dlnow_, dltotal_, _, _}]:= Quiet[progress = dlnow/dltotal]
Dynamic[ProgressIndicator[progress]]

cells = Table[Defer[URLSaveAsynchronous][urls[[i]], names[[i]], progFunction,
"Progress" -> True], {i, 10000}];

Here is the working Document.
CreateDocument[ExpressionCell[#, "Input"] & /@ cells]

Maybe can speed up it?
Another aspect is how to do the whole job in Mathematica more comfortably.
To build the download tasks took so much time in the working document which looks like I'm not downloading in an asynchronous way.

A: This is a complicated task and I believe that Mathematica is not the best tool to do it. If you want to do it only once, just go ahead with the method described in your question. Otherwise, if it is a frequent task, try to select a better tool such as Apache Nutch, which has a built in crawler. Not so easy to get used to, but it saves a lot of time afterwards.
Anyways, if you want to choose Mathematica, here is some guidelines that increase the efficiency. Writing a high-performance crawler requires a good knowledge of the TCP/IP protocol stack. Specifically, you should be familiar with the details of TCP and HTTP protocols. I am not going to write the code since testing the code requires the database of links and takes a huge amount of time.
I assume that you want to fetch the urls using a single machine. I also assume your machine has enough power so that processing/storage is not the bottleneck. There are at least two bottlenecks involved in the crawling process then. One is your network throughput (the connection between your machine and the outside world) and the other one is the server(s).
Fetching the urls one by one is not a good idea since because of the latency, the throughput of your crawler would be very low. Fetching all of the urls in parallel at once is a bad idea too. There are limits on the number of connections that any machine can handle at the same time (because of the limited amount of memory and processing power available).
Servers also disallow their clients to fetch too many pages in a short period of time to prevent denial-of-service attacks. Therefore, there must be an optimal value, say $k_t$, for the number of parallel fetches at any given time. And, this number, because of the variable condition of your network, is changing during the time.
Guideline 1: Do not open too many connections to a single server. Open at most 3-5 connections. Instead, use multiple servers to have more connections open. For example, if $k_t=40$, select 10 servers and open at most 4 connections to each of them. If you have more than 10 servers in your list, you can choose more servers, each with fewer connections.
Guideline 2: To find the optimal value of $k_t$, I propose you to use a closed loop controller. Set an initial value for $k_0$, say 10. Increase the amount of $k_t$ once every few minutes as long as increasing the amount, increases the throughput as well. Otherwise, decrease it. Knowing how TCP controls congestion helps a lot.
Guideline 3: There is another trick used by crawlers and browsers to speed up the download process of multiple files. But, I am not sure if there is a straightforward way to implement it in Mathematica (e.g., without using Java). Here is the trick: Download multiple files, back to back, with a single TCP connection to the server. I think, the URLSaveAsynchronous function by default does not do such a thing and you need a bit more effort to implement it. The reason behind this technique is that making a connection to the server takes time and has a huge overhead. Therefore, reusing the connection for several downloads, shares the overhead.


text:
Q: Why is my current stub in my RSpec test not properly stubbing the call to the method? Currently getting No such file or directory @ rb_sysopen
*

*Ruby Version 2.7.2

*Rspec Version 3.12.0

So I'm currently working through App Academy Open and I'm at the point where we're creating a tic tac toe game. I've written out all my tests and they pass except for the last few.
I have successfully stubbed method calls in the past but for whatever reason, I'm not getting it to work here.
I have 3 classes Board, HumanPlayer, and Game. The method I am currently testing is #play from within the Gameclass:
def play
  while @board.empty_positions?
    puts @board.print
    position = @current_player.get_position
    @board.place_mark(position, @current_player.mark)

    if @board.win?(@current_player.mark)
      puts "Player #{@current_player.mark} wins!"
      return
    else
      switch_turn
    end
  end

  puts "The game ended in a draw!"
end

Here is what my test looks like:
RSpec.describe Game do
  let(:game) { Game.new(:X, :O) }

  # ...

  describe "#play" do
    before :each do
      @board = game.instance_variable_get(:@board)
      @board.place_mark([0, 0], :X)
      @board.place_mark([0, 1], :O)
      @board.place_mark([0, 2], :X)
      @board.place_mark([1, 0], :O)
      @board.place_mark([2, 0], :X)
      @board.place_mark([1, 1], :O)
      @board.place_mark([2, 2], :X)
    end

    it "should call Board#place_mark" do
      @current_player = game.instance_variable_get(:@current_player)
      allow(@current_player).to receive(:get_position).and_return([1, 2])

      expect(@board).to receive(:place_mark)
      game.play
    end
  end
end

Here is the HumanPlayer#get_position method:
def get_position
  puts "Player #{@mark}, enter two numbers representing a position in the format `row col`"

  position = gets.chomp.split(" ")

  if position.length != 2 || # not 2 characters
      position.any? { |n| n.to_i.to_s != n } # not all numeric

    raise "Invalid Position"
  end

  position.map(&:to_i)
end

Here is the Board#place_mark method:
def place_mark(position, mark)
  raise "Placement Invalid" if !valid?(position) || !empty?(position)

  row = position[0]
  col = position[1]

  @grid[row][col] = mark
end

So whenever I run the tests I always get the error:
Game Instance Methods #play should call Board#place_mark
Failure/Error: position = gets.chomp.split(" ")

Errno::ENOENT:
  No such file or directory @ rb_sysopen - spec/2_game_spec.rb:85
# ./lib/human_player.rb:11:in `gets'
# ./lib/human_player.rb:11:in `gets'
# ./lib/human_player.rb:11:in `get_position'
# ./lib/game.rb:20:in `play'
# ./spec/2_game_spec.rb:92:in `block (4 levels) in <top (required)>'

I believe I'm stubbing the HumanPlayer.get_position method to return [1, 2] when called but for whatever reason, the Board.place_mark method does not successfully place the piece on the board and thus, the HumanPlayer.get_position gets called again because of the loop and when it hits the gets call, it produces that error output.
I've tried stubbing the gets call with this:
it "should call Board#place_mark" do
  @current_player = game.instance_variable_get(:@current_player)
  allow(@current_player).to receive(:gets).and_return("1 2")

  expect(@board).to receive(:place_mark)
  game.play
end

I also tired allow_any_instance_of(HumanPlayer) but it just prints the board in an endless loop:
it "should call Board#place_mark" do
  @current_player = game.instance_variable_get(:@current_player)
  allow_any_instance_of(HumanPlayer).to receive(:get_position).and_return([1, 2])

  expect(@board).to receive(:place_mark)
  game.play
end

This is my first question on SO, so if there is anything I need to add please let me know. Thanks in advance.

A: If you can't figure out the Errno::ENOENT error, you might try a slightly different design, which I think is easier to stub.
class GameCLI
  def gets
    Kernel.gets
  end
end

class HumanPlayer
  def get_position
    # ..
    cli = GameCLI.new # or, pass cli instance as argument to e.g. get_position
    position = cli.gets # ..
    # ..
  end
end

RSpec.describe HumanPlayer do
  describe '#get_position' do
    it '..' do
      allow_any_instance_of(GameCLI).to receive(:gets).and_return('..')
      # ..
    end
  end
end


text:
Q: How to get a pointer to the underlying value of an Interface{} in Go I'm interfacing with C code in Go using cgo, and I need to call a C function with a pointer to the underlying value in an Interface{} object. The value will be any of the atomic primitive types (not including complex64/complex128), or string.
I was hoping I'd be able to do something like this to get the address of ptr as an unsafe.Pointer:
unsafe.Pointer(reflect.ValueOf(ptr).UnsafeAddr())

But this results in a panic due to the value being unaddressable.
A similar question to this is Take address of value inside an interface, but this question is different, as in this case it is known that the value will always be one of the types specified above (which will be at most 64 bits), and I only need to give this value to a C function. Note that there are multiple C functions, and the one that will be called varies based off of a different unrelated parameter.
I also tried to solve this using a type switch statement, however I found myself unable to get the address of the values even after the type assertion was done. I was able to assign the values to temporary copies, then get the address of those copies, but I'd rather avoid making these copies if possible.

A: interface{} has own struct:
type eface struct {
    typ *rtype
    val unsafe.Pointer
}

You have no access to rtype directly or by linking, on the other hand, even though you'll copy whole rtype, it may be changed (deprecated) at future.
But thing is that you can replace pointer types with unsafe.Pointer (it may be anything else with same size, but pointer is much idiomatic, because each type has own pointer):
type eface struct {
    typ, val unsafe.Pointer
}

So, now we can get value contained in eface:
func some_func(arg interface{}) {
   passed_value := (*eface)(unsafe.Pointer(&arg)).val
   *(*byte)(passed_value) = 'b'
}

some_var := byte('a')

fmt.Println(string(some_var)) // 'a'

some_func(some_var)
fmt.Println(string(some_var)) // 'a', it didn't changed, just because it was copied

some_func(&some_var)
fmt.Println(string(some_var)) // 'b'

You also might see some more usages at my repo:
https://github.com/LaevusDexter/fast-cast
Sorry for my poor English.


text:
Q: Jointly Distributed Random Variables: Probability of having 1 boy, 2 girls
Suppose that $15\%$ of families in a community have no children, $20\%$ have 1, $35\%$ have 2, and $30\%$ have 3 children. Suppose that it is equally likely and independently to have a boy or a girl. If a family is chosen at random from the community, then B, the number of boys, and G, the number of girls will have the joint probability mass function values:

How did my textbook arrive at the probability $0.1125$ for having $2$ boys and $1$ girl (or $2$ girls and $1$ boy)?
I've calculated the values for the other possibilities:
$P\{B=0,G=0\}=0.15$ (given)
$P\{B=1,G=0\}=P\{B=0,G=1\}=0.2\times0.5=0.1$
$P\{B=1,G=1\}=0.35\times0.5=0.175$
$P\{B=2,G=0\}=P\{B=0,G=2\}=0.35\times0.5^2=0.875$
$P\{B=3,G=0\}=P\{B=0,G=3\}=0.30\times0.5^3=0.0375$
It seems that $P\{B=2,G=1\}=P\{B=1,G=2\}=0.30\times0.5^2=0.075$, the probability of having $2$ boys (OR $2$ girls) AND having 3 children. Shouldn't that be the same as the probability of having $1$ girl (OR $1$ boy) AND having 3 children? But $0.30\times0.5^2=0.075$ does not equal $0.3\times0.5=0.15$...

A: Given that $B+G=3$, the probability of having $B=2, G=1$ is given by the binomial coefficient:
$$P\{B=2,G=1|B+G=3\}=2^{-3}\left(\begin{array}{c}3\\2\end{array}\right)=2^{-3} 3=0.375$$
Therefore,
$$P\{B=2,G=1\}=P\{B=2,G=1|B+G=3\}P\{B+G=3\}=0.375\times0.3=0.1125$$


text:
Q: Ajax jQuery working fine in localhost XAMPP but not Working in hpanel of hostinger Ajax jQuery working fine in XAMPP but whenever I do upload in hpanel of Hostinger it doesn't work. please check my code
<script type="text/javascript">
        $(document).on('submit', '#ajax-form', function (e) {
        e.preventDefault();

        var formData = new FormData(this);
        formData.append("comment", true);

        $.ajax({
            type: "POST",
            url: "postcomment.php",
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                location.reload(true);
            }
        });

    });
    </script>

A: Try executing in console. for that you have to open your browser's inspect element. you can do it by pressing ctrl + shift + I. you might get error in console too if there is some. you can paste your ajax code over there. Also if it that doesn't work check your network tab once. you will surely get some hint what's wrong from your side.


text:
Q: Bokeh - how to set locale for datepicker and datetime axis Is there any way to localize the built-in datepicker widget and the datetime axis ?
As per this current locale should be used; but somehow, it has no effect.
Any clues ?


text:
Q: Python - Read terminal output and give input from the script itself I'm using a class from a module that on first usage asks me for some input in the terminal.
At every new instance the terminal asks for some inputs.
Example:
instance = Class()
instance.run()
## asks for input in the terminal

I thought about the subprocess module but didn't find anything regarding my use case, the best solution should allow me to read what it's asked and input some data at each step.
Thanks in advance

A: Here's an example from a fun guide I found on google just now.
I recommend you search for a few different articles on this topic to learn about the different approaches that might help you in your particular situation. Happy coding!
from __future__ import print_function, unicode_literals
from PyInquirer import prompt
from pprint import pprint
questions = [
    {
        'type': 'input',
        'name': 'first_name',
        'message': 'What\'s your first name',
     }
]
answers = prompt(questions)
pprint(answers)
)

A: Your problem is actually answered pretty well here:
Write function result to stdin
I've included an option below, but in general this is a pretty messy situation to do, and I would look for alternate solutions.  Even monkeypatching the other library to accept input as variables is likely to be cleaner.
That being said, the translation for your purposes might look like this:
import sys
import StringIO

class Foo(object):
    def run(self):
        self.x = raw_input('Enter x: ')

old_stdin = sys.stdin
instance = Foo()
sys.stdin = StringIO.StringIO('asdlkj')
instance.run()
print
print 'Got: %s' % instance.x

and running:
Enter x:
Got: asdlkj


text:
Q: Unable to fetch flickr pictures I'm using gem flickraw with rails - 4.0.0, everything is going good except , when we are fetching photos from flickr  using flikraw it is getting fetched but when I am trying to display it on screen using the url fetched from flickr it is not getting displayed but when I paste the same url in the browser it is getting displayed.
Here is the html code

Any help would be appreciated
Thanks
Rakesh

A: It looks like you are using the link to the image page on flickr, not the image url. Your img tag should look something like...

The code you have is probably using photo.id rather than photo.url_o (for example)


text:
Q: Preventing blur when user clicks on specific div not working in Firefox I am using jquery to keep the focus on a text box when you click on a specific div. It works well in Internet Explorer but not in Firefox. Any suggestions?
var clickedDiv = false;

$('input').blur(function() { if (clickedDiv) { $('input').focus(); } });

$('div').mousedown(function() { clickedDiv = true; })
        .mouseup(function() { clickedDiv = false });

A: Point to note: the focus() method on a jquery object does not actually focus it: it just cases the focus handler to be invoked! to actually focus the item, you should do this:
var clickedDiv = false;
$('input').blur( function() {
    if(clickeddiv)  {
        $('input').each(function(){this[0].focus()});
    }
}
$('div').mousedown(function() { clickedDiv = true; })
        .mouseup(function() { clickedDiv = false });

Note that I've used the focus() method on native DOM objects, not jquery objects.
This is a direct (brute force) change to your exact code. However, if I understand what you are trying to do correctly, you are trying to focus an input box when a particular div is clicked when that input is in focus.
Here's my take on how you would do it:
var inFocus = false;
$('#myinput').focus(function() { inFocus = true; })
             .blur(function() { inFocus = false; });
$('#mydiv').mousedown(function() {
    if( inFocus )
        setTimeout( function(){ $('#myinput')[0].focus(); }, 100 );
}

Point to note: I've given a timeout to focussing the input in question, so that the input can actually go out of focus in the mean time. Otherwise we would be giving it focus just before it is about to lose it. As for the decision of 100 ms, its really a fluke here.
Cheers,
jrh

EDIT in response to @Jim's comment
The first method probably did not work because it was the wrong approach to start with.
As for the second question, we should use .focus() on the native DOM object and not on the jQuery wrapper around it because the native .focus() method causes the object to actually grab focus, while the jquery method just calls the event handler associated with the focus event.
So while the jquery method calls the focus event handler, the native method actually grants focus, hence causing the handler to be invoked. It is just unfortunate nomenclature that the name of this method overlaps.

A: I resolved it by simply replace on blur event by document.onclick and check clicked element if not input or div
var $con = null; //the input object
var $inp = null; // the div object

function bodyClick(eleId){
    if (eleId == null || ($inp!= null && $con != null && eleId != $inp.attr('id') &&
            eleId != $con.attr('id'))){
        $con.hide();
    }
}
function hideCon() {
    if(clickedDiv){
         $con.hide();
    }

}
function getEl(){
var ev = arguments[0] || window.event,
origEl = ev.target || ev.srcElement;
eleId = origEl.id;
bodyClick(eleId);
}
document.onclick = getEl;

hope u find it useful


text:
Q: Position of PictureBoxes in form design window do not correspond to their position during runtime EDIT: I realized that I didn't tag this properly - I should have included vb.net as a tag, on the grounds that there could be a code based solution.  Note, that no changes to the resolution are made in my source code.
UPDATE: When the program starts execution, the left coordinate for each PictureBox is multiplied by ~0.376, whilst the top coordinate for each PictureBox.Top is multiplied by ~0.418 . This "down-scaling" applies to all picture boxes.  The source code I have is incredibly rudimentary and cannot be responsible for this.  I also looked at another project and I still face the same error.  A simple but poor fix would be to divide each coordinate by the corresponding values mentioned above.

In order to show you the issue I'm facing, please look at the images below.  Compare this image, where each PictureBox (i.e. a snake, set of arrows, etc.) has been placed so that they line up with a feature of the background image:

To this image, where the PictureBox elements are bunched together.  Their positions have been "down-scaled" closer to the origin of the form (note that all the elements are transforming horizontally during runtime, which is why the elements are in the top right corner):

In the solution I was given (developed in VS 2010 I believe), the position of each PictureBox goes beyond the background image as shown:

It is clear that each picture box has been placed in an organized fashion.  During execution, each PictureBox goes to it's intended position (i.e. lines up appropriately with the background image).

Obviously, the original developer of the solution I was given would have not faced the problem I am.  The fact that the solution works properly during runtime indicates some kind of error with my instance(s) of VB.  Does anyone know of any solutions?
I've came across this question which asks how to change the default resolution for a Windows 8 App and this question which asks why some applications appear differently on different machines, but they pose no clear solutions.  I would appreciate any help, since it's holding me back from critical work I must do.  Thank you in advance!

A: I feel a little silly now - I started carrying out a bit more research on VB forms and came came across this Microsoft documentation on form scaling.  Realizing that my issue may have been caused by having this scaling automatically carried out, I then found the AutoScaleMode property of my form and changed it from Font to None, which resolved my problem.


text:
Q: Unspecified Error when Trying to Install macOS High Sierra I have a Mac Mini (Late 2012) and a MacBook. About a week ago, I suspected that my Mini had been infected. So disconnected the Time Machine to preserve my backups, switched to the MacBook and when I had the time, downloaded the installer and tried to install High Sierra.
I created an external bootable media by downloading the installer on my MacBook, plugged in an external HDD and ran sudo /Applications/Install\ macOS\ High\ Sierra.app/Contents/Resources/createinstallmedia --volume /Volumes/MacInstall
I got to the screen with the utilities, started Disk Utility and erased my Macintosh HD and replaced it with APFS.  But of course, it's not a solid state drive, so that failed. I erased the disk again, and reformatted it as HPFS, journaled.
This time, I get 'an error occurred while preparing the installation. Try running this application again'.
I have downloaded the installer a second time, and tried again. Same result. I checked the date and it is correct. I even tried resetting the NVRAM. No luck. At this point, I have a Mac sitting here like a brick, that I can't use.
Can someone recommand how to get round this?

A: The most likely error is that the disk isn't partitioned correctly. If you have a bootable installer or can connect it in target disk mode - try erasing the entire physical volume again.

In the image above - you want the top item selected and not the volume under the physical drive. I like to click erase and then not make any changes from the defaults - leave the name Untitled or whatever the default name is - not Macintosh HD.
Then when the installer runs, you might need to look at the install log (press command 3 and command L when the install starts) or we'll need to chase down where or if your installer is saved to disk after the install aborted.
In some newer hardware - you need to be connected to the internet with no firewalls so the installer can go get the components for the hardware - perhaps that step is failing and the install log would likely show that.
Here is Apple's full steps on the erase - so choose it over my steps above if mine fail you.

*

*https://support.apple.com/en-us/HT204904


text:
Q: Can you keep the connection open between invocations of `aws s3` CLI? SSH has a useful opt-in feature that allows you to reuse a connection between invocations:
ssh host 'echo example' # this opens the connection to host, and leaves it open
ssh host 'echo example2' # this reuses the connection from the previous command

Is there something similar for the AWS S3 command-line interface?  For example:
aws s3 mv s3://bucketname/example1 s3://bucketname/example2
aws s3 mv s3://bucketname/example3 s3://bucketname/example4

It would be great if the first command would open a connection, and leave it open for the second to take advantage of it. This would speed up AWS S3 CLI tremendously when running a ton of small commands.

A: You cannot. You could always use boto3 directly, the Python SDK, or in fact any of the SDKs for any of the supported languages. It would allow you to persist a connection, but the CLI does not support that sort of thing.


text:
Q: Google Maps API blocked being blocked The company I work for uses Fujitsu Q665 tablets for a fleet managing software that is web-based.  It is called Geotab and it uses Google Maps for it's map source.
Unfortunately I receive some errors:
GET https://maps.googleapis.com/maps/api/js?v=3&language=en-US&callback=id09400674983401085&client=gme-geotab net::ERR_NAME_NOT_RESOLVED
POST https://maps.googleapis.com/maps/api/js net::ERR_NAME_NOT_RESOLVED
Failed to load provider: googlev3 RequiredScripts?i=GCU.map&x=geotab.default:541
Uncaught (in promise)
Object {url: //maps.googleapis.com/maps/api/js?v=3&langua…US&callback=id09400674983401085&client=gme-geotab", xhr: XMLHttpRequest, message: "The page could not be displayed", isSevere: false}
I am able to run the UI (Geotab) using a different map source they offer, however not Google.
I believe some sort of firewall rule or network setting is causing this issue, however I can't pinpoint the issue.
Any advice is much appreciated.
Regards,


text:
Q: How do I make the sound from a tennis ball hitting the floor softer? I enjoy practicing cricket bowling at my house, much to the dismay of my brother, as it results a normal tennis ball making a high pitched 'thud' when bouncing off of the floor. How could I reduce the sound made when hitting the floor? Could something like tape help?

A: You could probably cover the floor on a material with lower stiffness like a foam.


text:
Q: MooTools: How to Request and Evaluate javascript on a button click I am using mootools v1.3. I added a click event to button with id as "submit_details". All I want is to load an another mootools script on button click event and execute it. I tried a way as below
$('submit_details').addEvent('click',function(){
   alert('checkepoint-1');
   myScript = new Asset.javascript('js/main.js',{});
   alert('checkepoint-2');
});

But its not working.(It alerts only "checkepoint-1").

A: Try using without new keyword.
$('submit_details').addEvent('click',function(){
   alert('checkepoint-1');
   myScript = Asset.javascript('js/main.js',{});
   alert('checkepoint-2');
});

For more details, check here.
http://mootools.net/docs/more/Utilities/Assets


text:
Q: How does this bubblesort variation effectively carry out a sort? // A strange variation on a bubblesort I created inadvertently. I omitted the usual if a[j] >a[j+1] by mistake yet the code was still able to function perfectly. Would there be any advantage to using a bubblesort of this kind over a normal bubblesort.
public int[] bubbleSort(int[] a)
{
    for (int i = 0; i < a.length - 1; i++)
    {
        for (int j = i + 1; j < a.length - 1; j++)
        {
            if (a[i] > a[j])
            {
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;

            }
        }
    }
    return a;
}

A: Notice that at the end of the first iteration of the outer loop, the first value in the array will necessarily be the minimum value in the array (do you see why?) After the second iteration, the second value will be the second-smallest value, and after the third iteration the third value will be the third-smallest value, etc.
(That said, I think there's a bug in your logic. The upper bound on j should be a.length rather than a.length - 1, since otherwise the last value in the array is never compared to anything else or moved.)
You might want to look into selection sort, which works by moving the smallest value in the array to the front, then the second-smallest, etc. The algorithm you've come up with is (essentially) a modified version of selection sort rather than a modified bubble sort.
Hope this helps!


text:
Q: How to use WPF custom control properties in XAML Template? I've created a custom control that is intended to be used as a button but has properties to specify points for a polygon (to be drawn inside the button) and two colors for the gradient.  I've declared all the properties in the code and then written the template in the XAML but it doesn't seem to be working.  If I hard-code the values into the XAML it works just fine but nothing seems to be happening if I use the property values through TemplateBinding.  Any ideas on how to get this to work?
Here's my XAML:
<Window x:Class="WPFTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WPFTest">
    <StackPanel>
        <StackPanel.Resources>
            <Style TargetType="my:GradientButton">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type my:GradientButton}">
                            <Grid>
                                <Ellipse Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Stroke="{TemplateBinding Foreground}" VerticalAlignment="Top" HorizontalAlignment="Left">
                                    <Ellipse.Fill>
                                        <LinearGradientBrush>
                                            <GradientStop Color="{TemplateBinding GradientStart}" Offset="0"></GradientStop>
                                            <GradientStop Color="{TemplateBinding GradientEnd}" Offset="1"></GradientStop>
                                        </LinearGradientBrush>
                                    </Ellipse.Fill>
                                </Ellipse>
                                <Polygon Points="{TemplateBinding PlayPoints}" Fill="{TemplateBinding Foreground}" />
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </StackPanel.Resources>
        <my:GradientButton Content="Button" Height="50" x:Name="gradientButton1" Width="50" GradientStart="#CCCCCC" GradientEnd="#777777" />
    </StackPanel>
</Window>

And here's the code for the custom control:
public class GradientButton : Button
    {
        internal static DependencyProperty GradientStartProperty;
        internal static DependencyProperty GradientEndProperty;
        internal static DependencyProperty PlayPointsProperty;

        static GradientButton()
        {
            GradientStartProperty = DependencyProperty.Register("GradientStart", typeof(Color), typeof(GradientButton));
            GradientEndProperty = DependencyProperty.Register("GradientEnd", typeof(Color), typeof(GradientButton));
            PlayPointsProperty = DependencyProperty.Register("PlayPoints", typeof(Point[]), typeof(GradientButton));
        }

        public Color GradientStart
        {
            get { return (Color)base.GetValue(GradientStartProperty); }
            set { SetValue(GradientStartProperty, value); }
        }

        public Color GradientEnd
        {
            get { return (Color)base.GetValue(GradientEndProperty); }
            set { SetValue(GradientEndProperty, value); }
        }

        public Point[] PlayPoints
        {
            get //hardcoded return at the moment to get it to work, but this will change later
            {
                System.Collections.Generic.List<Point> result = new System.Collections.Generic.List<Point>();

                double left = this.Width / 2.77;
                double top = this.Height / 4.17;
                double right = this.Width / 1.43;
                double middle = this.Height / 2.0;
                double bottom = this.Height / 1.32;

                result.Add(new Point(left, top));
                result.Add(new Point(right, middle));
                result.Add(new Point(left, bottom));

                return result.ToArray();
            }
            set { SetValue(PlayPointsProperty, value); }
        }
    }

A: Polygon.Points is of type PointCollection.  I don't believe a Point[] fits that type.  You will need to either change the type of PlayPoints or use a IValueConverter to make the change it's type.

A: Try using this instead for your Color bindings:
Color="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=GradientStart}"

TemplateBinding only works in limited situations where declarations are in elements of the visual tree of a ControlTemplate, which is not the case for your LinearGradientBrush. You can see the same behavior, and use the same fix, inside Trigger Setters in a ControlTemplate.


text:
Q: Time Dilation - How does it know which Frame of Reference to age slower? Okay, I'm asking a question similar to this one here: Time Dilation - what happens when you bring the observers back together?. Specifically, I am curious about a specific angle on the second part of his question, regarding when two moving frames of reference (FoR) are brought back together, and how "it" knows which one should be still young.
The accepted answer on that question says that it is whichever FoR experienced the forces of acceleration/deceleration. But, isn't that the whole point of relativity, is that it's all ... well, relative; that it is not possible to say with a certainty that it was the traveler in the spaceship who was accelerating/decelerating?
Isn't it the case that it is just as legitimate to say that the universe and people on the planet accelerated/decelerated and the traveler in the spaceship was stationary? This would therefore then lead to that the universe and planet-side people should remain young and the spaceship occupant should be old, no?
Does dilation (temporal-spatial) just generally apply to the smaller of the two FoRs, or is there some other system or rule which "decides" which FoR gets dilated?

A:
Isn't it the case that it is just as legitimate to say that the universe and people on the planet accelerated/decelerated

No, it's not. If you stay on the planet, you know you didn't accelerate (that is, not any more than usual due to the gravitation and rotation of Earth, etc.). But if you are in the spaceship and you turn your engine on, you'll definitely feel the acceleration (same way you feel it in your car). We call the former frames (those that don't feel the force) inertial and they play very special role in the theory of relativity (both special and general).

A: Mentions of "acceleration", or lack of it, to establish the difference between the twins' careers, are confusing the issue.  (This can be proved by concocting roadmaps for two travelers with identical acceleration or deceleration periods, only placed at different times of their respective journeys. This way, their watches don't show the same elapsed time when they are reunited.)
A better mental picture is obtained by considering paths in spacetime for each traveller. Both paths start from the same "event" (the event of the twins saying good bye to each other) and arrive at another event (their getting together again).  Now, just as two different paths in space, with same beginning and same end, need not have the same length, two different paths in space-time need not have the same "four-dimensional length", so to speak.  The quotes are meant to warn that this expression is not used by relativists:  This "four-dimensional length" is actually what they call "proper time", and it happens to be (according to Special Relativity), what each twin's wristwatch is measuring.
So the main issue is this difference in spacetime trajectories, not gravitational effects per se.  That the steady twin finds himself older than his sister at the end comes from the fact that his spacetime trajectory is rectilinear, whereas his twin's is curved.  And contrary to three-dimensional length, "four-dimensional length", aka proper time, is maximal, not minimal, for straight (i.e., physically, inertial) spacetime trajectories.
Of course, one will suffer accelerations if one follows a curved 4-D path.  But,
(1) Meaningful effects (in terms of age difference) can be obtained with small accelerations (of order 1 g) over a few years, so invoking GR is not necessary.
(2) Acceleration per se does not cause the proper-time discrepancy:  Two traveling twins who suffer the same acceleration-deceleration events (the same in intensity and duration) can age differently if these events are not scheduled the same way.  The real cause is this difference in scheduling, which is logically the same thing as a geometrical difference between the two 4-D paths.

A: The other answers all bring out the essential points but I'll try to rephrase things in a way that makes it clear how the two "twins" (of the twin paradox) are different without any reference to General Relativity.
The twin on earth is always on a geodesic of the spacetime (which is flat Minkowski) whereas the round-trip accelerating twin is on a worldine that clearly deviates from a geodesic. So in this picture, it is very clear that the situation is not symmetric with respect to the twins. And you can also calculate the proper time ("length" of the worldines) and see that it is shorter for the non-geodesic path. In fact, the Minkowski spacetime is such that the proper time is maximized for geodesics.

A: In special relativity, acceleration breaks the symmetry between the two observers since SR is applicable only in the inertial frames. If you insists the relativity of all motions then you have to use GR. If you apply GR to the problem you will get the same answer. However, SR is sufficient to answer the twin paradox. Putting simply, just remember that although all motions are relative according to GR, the equivalence principle demands that acceleration is equivalent to gravitation for the observer accelerating. The symmetry between the two observers break there.

A: "Relativity" is actually a misleading word that Einstein didn't like.  It doesn't mean "every vantage point is equivalent and it's all relative".  It really means only inertial, non-accelerating vantage points are equivalent.  You could think of it as, prior to relativity, people believed that there was an absolute position/speed to the universe.  Special Relativity shows that there is not, but rather, there is an absolute acceleration to the universe.
This is illustrated by the famous rotating bucket thought experiment.  You put a bucket out in the middle of empty space and spin it, and the water in it starts flowing towards the edges.  But if all vantage points were the same, couldn't you also think of it as the universe spinning and the bucket stationary?  But one vantage point is obviously more correct than the other, because only one involves the water flowing towards the edges.  Thus there is a "universal" state of zero acceleration that is unambiguous.
It is interesting to note that Einstein's original idea for his theory of Special Relativity was a theory of Invariance (of the speed of light)


text:
Q: Can a bash array be used in place of eval set -- "$params"? I'm taking a look at the optparse library for bash option parsing, specifically this bit in the generated code:
params=""
while [ $# -ne 0 ]; do
  param="$1"
  shift

  case "$param" in

    --my-long-flag)
      params="$params -m";;
    --another-flag)
      params="$params -a";;
    "-?"|--help)
      usage
      exit 0;;
    *)
      if [[ "$param" == --* ]]; then
        echo -e "Unrecognized long option: $param"
        usage
        exit 1
      fi
      params="$params \"$param\"";;  ##### THIS LINE
  esac
done

eval set -- "$params"  ##### AND THIS LINE

# then a typical while getopts loop

Would there be any real reason to use eval here?  The input to eval seems to be properly sanitized.  But wouldn't it work the same to use:
params=()
# ...
    --my-long-flag)
      params+=("-m");;
    --another-flag)
      params+=("-a");;
# ...
      params+=("$param");;
# ...
set -- "${params[@]}"

That seems cleaner to me.
In fact, wouldn't this allow options to be parsed directly out of the params array (without even using set) by using while getopts "ma" option "${params[@]}"; do instead of while getopts "ma" option; do?

A: The question is "Should a bash array be used in place of eval set — "$params"?", and the answer is yes!.
In your script, the input to eval is clearly not properly sanitized. Try
    yourscript '`xterm`'

and you'll see that an xterm is started even though the backticks are properly quoted by single quotes. (Compare with
    echo '`xterm`'

which does not start an xterm.)
Fixing the bug while keepting eval is very difficult.
Even changing the line
    params="$params \"$param\"";;

to
    params="$params '$param'";;

would not help: Now
    yourscript '`xterm`'

no longer starts an xterm, but
    yourscript \'' `xterm` '\'

still does.

A: You don't need to use a bash array here (but do so if it feels better).
Here's how to do it for /bin/sh:
#!/bin/sh

for arg do
    shift

    case "$arg" in
        --my-long-flag)
            set -- "$@" -m ;;
        --another-flag)
            set -- "$@" -a ;;
        "-?"|--help)
            usage
            exit 0 ;;
        --*)
            printf 'Unrecognised long option: %s\n' "$arg" >$2
            usage
            exit 1 ;;
        *)
            set -- "$@" "$arg"
    esac
done

This is cleaner than the bash array solution (personal opinion) since it doesn't need to introduce another variable.  It's also better than the auto-generated code that you show as it retains each command line argument as a separate item in "$@".  This is good, because this allows the user to pass arguments containing whitespace characters as long as they are quoted (which the auto-generated code does not do).

Style comments:

*

*The loop above is supposed to translate long options into short options for a loop over getopts later. As such, it breaks from that task by actually acting on some options, such as -? and --help.  IMHO, these should instead be translated to -h (or some suitable short option).

*It also does the translation of long options past the point where options should not be accepted.  Calling the script as
./script.sh --my-long-flag -- -?

should not interpret -? as an option due to the -- (meaning "options ends here").  Likewise,
./script.sh filename --my-long-flag

should not interpret --my-long-option as an option, as the parsing of options should stop at the first non-option.
Here's a variant that takes the above into account:
#!/bin/sh

parse=YES

for arg do
    shift

    if [ "$parse" = YES ]; then
       case "$arg" in
            --my-long-flag)
                set -- "$@" -m ;;
            --another-flag)
                set -- "$@" -a ;;
            --help)
                set -- "$@" -h ;;
            --)
                parse=NO
                set -- "$@" -- ;;
            --*)
                printf 'Unrecognised long option: %s\n' "$arg" >$2
                usage
                exit 1 ;;
            *)
                parse=NO
                set -- "$@" "$arg"
        esac
     else
        set -- "$@" "$arg"
     fi

done

What this does not allow is long options with separate option arguments, such as --option hello (the hello would be treated as a non-option and the option parsing would end).  Something like --option=hello would be fairly easy to handle with a bit of extra tinkering though.


text:
Q: count id which are smaller than certain value My data consists of unique ids with a certain distance to a point. The goal is to count the id which is
equal or smaller than the radius.
Following example shows my DataFrame:
id    distance  radius
111   0.5       1
111   2         1
111   1         1
222   1         2
222   3         2
333   5         3
333   4         3

The output should look like this:
id  count
111 2
222 1
333 0

A: You can do:
df['distance'].le(df['radius']).groupby(df['id']).sum()

Output:
id
111    2.0
222    1.0
333    0.0
dtype: float64

Or you can do:
(df.loc[df.distance <= df.radius, 'id']
   .value_counts()
   .reindex(df['id'].unique(), fill_value=0)
)

Output:
111    2
222    1
333    0
Name: id, dtype: int64


text:
Q: CSS: Table Sizing Issue (caption/tr/th/td) Working on specifically a pricing table chart. When the screen is maximized, all of the elements (caption/tr/th/td) are spaced out correctly and if within the background-color. Once the screen begins to get smaller, the elements stay spaced out and stretch past the border and the page itself.
How do I get the elements to stay within the size of the table and it's background through-out screen resizing?
HTML5:

Cracked Screens & Hardware Pricing

                        header 1
                        header 2
                        header 3
                        header 4
                        header 5
                        header 6
                        header 7
                        header 8

                        iPhone

                        Side 1
                        $250
                        $48
                        $65
                        $58
                        $50
                        Call
                        $45
                        $65

                        Side 2
                        $150
                        $48
                        $65
                        $70
                        $47
                        $60
                        $45
                        $63

                        Side 3
                        $100
                        $45
                        $58
                        $55
                        $45
                        $53
                        $45
                        $60

                        Side 4
                        $100
                        $45
                        $55
                        $55
                        $50
                        $55
                        $45
                        $58

                        Side 5
                        $100
                        $45
                        $53
                        $57
                        $45
                        $50
                        $41
                        $60

CSS:
table{
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
-webkit-align-self: center;
align-self: center;
-webkit-flex-direction: column;
flex-direction: column;
background: #ECF0F1;
-webkit-box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40);
box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40);
-webkit-border-radius: 0.3em;
border-radius: 0.3em;
padding: 1.3em;
width: 90%;
}

table>caption{
width: 30em;
height: 2em;
font-size: 2em;
-webkit-font-smoothing: antialiased;
font-family: HelveticaNeue-Light,"Helevetica Neue",Helvetica,Arial;
}

th{
height: 2em;
font-size: 1em;
-webkit-font-smoothing: antialiased;
font-family: HelveticaNeue-Light,"Helevetica Neue",Helvetica,Arial;
text-align: center;
}

tr{
max-width: 30px;
text-align: center;
}

td{
min-width: 100px;
}

td:hover{
color: #008000;
}

.call{
background-color: #B6B6B4;
}

A: This should do the trick... let me know if I missed anything?
Reason:
You need to add min-width to the  and  tags so they won't resize to small pushing your text to the next line.
Here is the JSFiddle demo
Screenshot:

//HTML
<!DOCTYPE html>

    <link href="index.css" rel="stylesheet">

            header 1
            header 2
            header 3
            header 4
            header 5
            header 6
            header 7
            header 8

            Side 1
            $250
            $48
            $65
            $58
            $50
            Call
            $45
            $65

            Side 2
            $150
            $48
            $65
            $70
            $47
            $60
            $45
            $63

            Side 3
            $100
            $45
            $58
            $55
            $45
            $53
            $45
            $60

            Side 4
            $100
            $45
            $55
            $55
            $50
            $55
            $45
            $58

            Side 5
            $100
            $45
            $53
            $57
            $45
            $50
            $41
            $60

//CSS (index.css)
body{
    margin: 0 !important;
    display: -webkit-flex;
    display: flex;
    -webkit-justify-content: center;
    justify-content: center;
    width: 100vw;
    height: 100vh;
    background: #1E67CB;
}
section{
    display: -webkit-flex;
    display: flex;
    -webkit-align-self: center;
    align-self: center;
}
table{
    background: #ECF0F1;
    -webkit-box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40);
    box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40);
    -webkit-border-radius: 0.3em;
    border-radius: 0.3em;
}
tr{
    text-align: center;
}
th{
    min-width: 62px;
}
td{
    min-width: 62px;
}

A: One way is to use bootstrap to achieve this. You can check each screen size according to the grids of bootstrap if you want to make it responsive by overwriting the original bootstrap css.
You can check out the bootstrap grid system here.
Simply search for @media (min-width: 768px) and (max-width: 991px) in the bootstrap original css and overwrite it by setting your own properties in your styles section, in your case, set the table dimensions with respect to the screen size.


text:
Q: Display list of countries in Windows Phone 8.1 I am writing a Windows Phone 8.1 App  (WINRT)
I want to display a list of countries in registration page out of which user can select one. In Windows Phone 7, we used to have LongListSelector.
What is its replacement in Windows Phone 8.1 (WinRT).
Actually, I want users to click on this control and it should open in fullscreenmode.
I am confused between ListView, ListBox, Semanticzoom
I am currently using:
<ListView
                                              Name="UserCountry_ListPicker"
                                            FullModeHeader="Select Country:"
                                    SelectedIndex="-1"
                                    Foreground="{StaticResource DefaultTheme_DarkBlueColor}"
                                    FontWeight="ExtraLight"
                                    Margin="0,5,0,0"
                                    BorderBrush="{StaticResource DefaultTheme_DarkBlueColor}"
                                    BorderThickness="0.2,0.2,0.2,3"
                                    VerticalContentAlignment="Bottom"
                                    VerticalAlignment="Bottom"
                                    Background="{StaticResource DefaultTheme_TextBoxBackground_Light}"
                                            SelectionChanged="UserCountry_ListPicker_SelectionChanged">
                                            <ListView.ItemTemplate>
                                                <DataTemplate>
                                                    <StackPanel
                                                Orientation="Horizontal"
                                                Margin="0,0,0,0">
                                                        <Border
                                                    Background="{StaticResource DefaultTheme_DarkBlueColor}"
                                                    Width="28"
                                                    Height="28">
                                                            <TextBlock
                                                        Text="{Binding CountryWithCodesGroupItem_Symbol}"
                                                        FontSize="14"
                                                        FontWeight="ExtraLight"
                                                        Foreground="WhiteSmoke"
                                                        HorizontalAlignment="Center"
                                                        VerticalAlignment="Center"/>
                                                        </Border>
                                                        <TextBlock
                                                    Text="{Binding CountryWithCodesGroupItem_Name}"
                                                    FontWeight="ExtraLight"
                                                    Margin="12 0 0 0"
                                                    FontSize="21"/>
                                                    </StackPanel>
                                                </DataTemplate>
                                            </ListView.ItemTemplate>
                                            <ListView.FullModeItemTemplate>
                                                <DataTemplate>
                                                    <StackPanel
                                                Orientation="Horizontal"
                                                Margin="20,5,0,5"
                                                  >
                                                        <Border
                                                    Background="{StaticResource DefaultTheme_DarkBlueColor}"
                                                    Width="68"
                                                    Height="68">
                                                            <TextBlock
                                                        Text="{Binding CountryWithCodesGroupItem_Symbol}"
                                                        FontSize="26"
                                                        FontWeight="ExtraLight"
                                                        Foreground="WhiteSmoke"
                                                        HorizontalAlignment="Center"
                                                        VerticalAlignment="Center"/>
                                                        </Border>
                                                        <TextBlock
                                                    Text="{Binding CountryWithCodesGroupItem_Name}"
                                                    FontWeight="ExtraLight"
                                                            Name="CountryNames"
                                                    Margin="12 0 0 0"
                                                            Foreground="{StaticResource DefaultTheme_DarkBlueColor}"
                                                    FontSize="26"
                                                        VerticalAlignment="Center"/>
                                                    </StackPanel>
                                                </DataTemplate>
                                            </ListView.FullModeItemTemplate>

                                            <ListView.HeaderTemplate>
                                                <DataTemplate>
                                                    <StackPanel
                                    Orientation="Horizontal"
                                                Margin="0,0,0,-5">
                                                        <TextBlock
                                                    Name="UserCountry_Label"
                                                     FontSize="25"
                                                   FontWeight="ExtraLight"
                                                    Foreground="{StaticResource DefaultTheme_DarkBlueColor}"
                                                    Text="Country">
                                                        </TextBlock>
                                                        <Image Source="ms-appx:///Images/Login_RegistrationPage/athteriskRedForm_01.png"
                                                        Margin="3,0,0,0">
                                                        </Image>
                                                    </StackPanel>
                                                </DataTemplate>
                                            </ListView.HeaderTemplate>
                                        </ListView>

But it shows opened list on page. Can't I have it closed on page like this:
example image

A: Maybe you will consider using ListPickerFlyout:
<Button Content="Choose country">
   <Button.Flyout>
      <ListPickerFlyout ItemsSource="{Binding CountryList}" Placement="Full" ItemsPicked="Items_PickedEven">
         <ListPickerFlyout.ItemTemplate>
            <DataTemplate>
               <TextBlock Text="{Binding CountryName}"/>
            </DataTemplate>
         </ListPickerFlyout.ItemTemplate>
      </ListPickerFlyout>
   </Button.Flyout>
</Button>

You may also think of using general Flyout and define it's content as ListView, ListBox or other.

A: As far as the differences between the three are concerned, ListView is essentially like a ListBox however it also has a View property that ListBox does not have. The View property is useful for specifying a prefdefined way to display items.
A SemanticZoom control often has a ListView control within it, and allows you to switch between two different views of the list's data set.