text:
Q: How to clear the settings of default app to the files with special file extension? I set the default app to open the files with special file extension by mistake: the app could not open them at all for they're only file fragments (or, say, no app can until I combine them as one file).
So I want to clean the settings of default app (set no default app), but no solutions found. Any ideas? Hope for your answers!

A: It's free, and configurable per extension.
http://www.rubicode.com/Software/RCDefaultApp/

A: For changing default app (no option to clean the setting tho):

*

*If you don't have a file with that specific extension - create one.

*Right click on it -> get info.

*Set "Open with" and click "Change All" button right under it.

All files with that extension will now be opened by that app.


text:
Q: How to parse Json link Windows Phone 8 I try the all Json parse example but they don't work.
Do anyone have a proper example Json parsing from web link for Windows Phone 8 ?
Please help me...

A: 1) Generate class for json object (Online JSON class generator)
2) Call link and download data.
3) Parse data using JsonConvert or other class.( Samples )
Here is a sample:
http://smallandmighty.net/blog/using-json-with-windows-phone

A: Personally I prefer Json.NET. It is light-weight and relatively easy, especially if you read through the documentation. It is hard to answer the 'how to parse' considering there are different scenarios to consider. The resource #1 that Norbert posted I think is helpful and something I am going to use now that i know about it considering creating the classes is usually the longest and most monotonous part.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to "merge" various graphics 2d into one 3d graphic? I did some calculations and as result got a 2D graphic, but at the beginning of the work I used a constant parameter. What I want is to make a 3D graphic with this parameter as an axis, varying from 1 to 100. How to proceed?

A: Generally speaking Mathematica has 3D versions of everything, so you are probably best to use those from the start.  But if you really want to convert 2D to 3D, then you could do it with a set of rules:
Clear[linerule];
linerule[z_] := Line[points_, stuff___] :> Line[{First@#, Last@#, z} & /@ points, stuff];
Clear[textrule];
textrule[z_] := Text[t_, {x_, y_}, stuff___] :> Text[t, {x, y, z}, stuff];
(* pointRule, graphicsComplexRule, polygonRule, etc. *)
Clear[allrules];
allrules[z_] := {linerule[z], textrule[z]};

It's not so simple as taking a list of two numbers to a list of three.  Sometimes your list of two numbers might not be a 2D point.  So these rules specifically target the bits which we know are coordinates.  Some primitives like Circle are going to be more that just appending a z coordinate.
As an example use:
Clear[p];
p[z_] := Plot[(x - z)^2, {x, 0, 1}, PlotRange -> {{0, 1}, {0, 1}}, PlotStyle -> Thick];

Graphics3D[
  Table[First@FullGraphics@p[z] /. allrules[z], {z, 0, 1, 0.2}]
, Boxed -> False]


text:
Q: What is the sum of regularly spaced normal distribution pdf? $\sum_{t=-∞}^∞ \frac{e^{-(2 \pi t + \theta - \mu)^2/(2 \sigma^2)}}{\sqrt{2 \pi} \sigma}$ I'm trying to get the pdf values for angle $\theta$.
Suppose that $\theta = \theta +2 \pi$ is indistinguishable from each other.
At this time, when I say that $X$ follows $N(\mu, \sigma^2)$,
I want to know the probability distribution of $P(X=\theta)$.
If this is expressed as wolfram alpha input, it is as follows.
sum e^(-(θ - μ + 2pi t)^2/(2 σ^2))/(sqrt(2 π) σ) where t from -infinite to infinite
The problem is that this result contains the theta function
$$\sum_{t=-∞}^∞ \frac{e^{-(2 \pi t + \theta - \mu)^2/(2 \sigma^2)}}{\sqrt{2 \pi}\,\sigma} = \frac{\nu_3\left(\frac{\theta - \mu}{2}, e^{-\sigma^2/2}\right)}{2 \pi}.$$
Is there a way to get a suitable approximation function for this (where $-\pi < \mu <\pi$ and $0.001 < \sigma < 1 $)? Or, am I approaching it too crudely?


text:
Q: Communicate through a VPN link using Arduino UART WiFi Module The following describes the configuration of the system and other details. The problem is mentioned after that. If the initial description is too much or not needed, please skip it.

I have a VPN (between two SIMs). One SIM is in a USB dongle, the other one is in a WiFi router. The dongle is connected to computer 'A', and another computer ('B') is wirelessly connected to the WiFi router which can access the dongle. The VPN is between the router and the computer 'A' (dongle). As the WiFi router leases 'B' a private IP, 'A' can't ping 'B'. But 'B' can ping 'A'. There is no issue up to now.
I have created a socket-based simple Java network application (client - server pair). The client is running on 'B', the server is running on 'A. Only the client can send data to the server, the other way around is not possible. This part also is OK. Now I need to replace the computer 'B' with an Arduino. I need to send some data from the Arduino to computer 'A' through the same network.
For this, the Arduino needs a WiFi module to access the router. I've this USART WiFi module with the shield. It can successfully connect to the router, (I can ping it from a computer, which is also connected to the router).

THE PROBLEM
Now the configuration is as below.

There's the (server) application running on computer 'A', which is listening on a given port (port 8090). How can I send some data (eg. some text "hello!"), from the Arduino to the computer 'A'?
Please note that for the WiFi module I'm using, I found some examples for applications based on the Arduino WiFi shield. But I can't apply them to my configuration (can I?).


text:
Q: Error with SDK package download in Android Studio
java.io.IOException: Cannot download  , response: 200 OK Warning: An
  error occurred while preparing SDK package Android Support Repository:
  Cannot download  , response: 200 OK. java.io.IOException: Cannot
  download
  'https://dl.google.com/android/repository/emulator-windows-3833124.zip':
  dl.google.com Warning: An error occurred while preparing SDK package
  Android Emulator: Cannot download
  'https://dl.google.com/android/repository/emulator-windows-3833124.zip':
  dl.google.com. java.io.IOException: Cannot download ' Warning: An
  error occurred while preparing SDK package Google Repository: Cannot
  download

A: I had this similar issue below worked for me.
The solution for this is:

*

*Run Android Studio as Administrator.

*Re run the update.
It will work.

A: you can manual download  sdk:

*

*https://dl.google.com/android/repository/platform-29_r04.zip

*https://dl.google.com/android/repository/3534162-studio.sdk-patcher.zip

*https://dl.google.com/android/repository/build-tools_r29.0.3-windows.zip

*https://dl.google.com/android/repository/emulator-windows-6306047.zip

*https://dl.google.com/android/repository/sources-29_r01.zip

*https://dl.google.com/android/repository/platform-tools_r29.0.6-windows.zip
Unpack to

*

*C:\Android\Sdk\platforms\android-2

*C:\Android\Sdk\patcher\v4

*C:\Android\Sdk\build-tools\29.0.3

*C:\Android\Sdk\emulator

*C:\Android\Sdk\sources\android-29

*C:\Android\Sdk\platform-tools

Parsing

*

*C:\Android\Sdk\build-tools\29.0.3\package.xml

*C:\Android\Sdk\emulator\package.xml

*C:\Android\Sdk\patcher\v4\package.xml

*C:\Android\Sdk\platform-tools\package.xml

*C:\Android\Sdk\platforms\android-29\package.xml

*C:\Android\Sdk\sources\android-29\package.xml

A: delete uncompleted download in "[Android SDK folder]\.downloadIntermediates". i solved my problem by this method.

A: I have a similar problem.
And I notice some setting about Force https//... to be fetched using http://...
After using it, my download run normally:

A: run the studio.sh script with sudo:
"sudo ./studio.sh"
if that does not work run:
"sudo chmod 777 -R /opt"
without quotes
should work

A: Find Android SDK folder. (Usually C:\User\AppData\Local\Android\sdk) Delete folders which starts with dot(.), they are temporary download files. Then delete Android Emulator from SDK Manager. Then run Android Studio as administrator and then download and install Android Emulator again. Now you can create emulator and use it without errors.

A: Very often the cause of errors can be an interruption of the Internet connection.
Just resume downloading with stable Internet.

A: As shown in the android SDK video ./studio.sh has to be run, however if run without sudo or su, this might give problems like these. So you should run with sudo or su as shown below:

*

*sudo ./studio.sh(or /path/to/studio.sh)

or if you want to run as root

*

*su

*Password:root password

*./studio.sh or (or /path/to/studio.sh)
This should fix the problem
There might be a problem with /tmp if it is on a different partition and the partition has less space than needed to install

Hope this helps.

A: I had Admin access on my Laptop, but still I faced this problem (also other packages were getting downloaded). I found of that the https://dl.google.com/android/repository/android_m2repository_r47.zip file is quiet large, and in my case since my network speed was slow and I was attempting to download a large file on a slow network I concluded that it was failing for timeout. I switched to a faster LAN and it got downloaded.

A: I had the same problem, I downloaded problematic file 'https://dl.google.com/android/repository/emulator-windows-3833124.zip' and extracted it to
C:\Users\$usrname$\AppData\Local\Android\sdk\extras\android.
It solved the problem for me.

A: Hi I faced a similar issue... Turn's out that may be related to system configuration of your machine..
Try downloading latest packages as per your system configuration from below:
https://developer.android.com/studio/?gclid=Cj0KCQjwj9LkBRDnARIsAGQ-hUfGD0_yGXcqqZBN6d1Y-nMZ-TNKZtvdRBHimcE8m0tPYjyUw_bV77AaAsdzEALw_wcB

A: I had a similar issue while installing in Mac Catalina:

java.net.SocketException: Operation timed out  (Read failed) Warning:
  An error occurred while preparing SDK  package Sources for Android 29:
  Operation timed  out (Read failed).

First attempt using standard configuration - Failed
Second attempt using standard configuration - Failed
Third attempt using Customer configuration, I selected the android simulator - Failed
Fourth attempt using Customer configuration, I selected the android simulator - Successful!
Not sure what was the reason, there is no change in any setting other than the above (and I am an Administrator of the Mac).

A: Below steps fixed the problem for me -
 1. Download zip file from this location
 2. Extract it and move the emulator folder image for emulator folder into the SDK folder image for SDK folder
I hope it works for you as well, I was using Windows 10 Pro 64bit

A: This amount of download requires high speed Internet and if you don't have this it may show this error.

A: As mentioned in the earlier comments, the problem might be because of slow internet connection, just to add more details, you need to download all the problematic file which you get in the logs, in my case they were (emulator-windows_x<>.zip and x86-30_r09.zip) and place them in the respective sub-folders (PackageOperation02 or PackageOperation05 ..)  present in .tmp folder located under andriod-sdk root folder and retrigger the sdk installation from Andriod studio.
What Andriod-Studio will do after your action:
It will first search the files in .tmp folder if they exist it wont download and simply unzip and initiate the installation from where it failed.

A: I did not had android studio and was using only sdk manager. It was downloading to a location of <your path>\Android\.temp Directory.
Deleted the broken .zip file and re-ran the flutter run command.

A: Simply click on menu:  File then click ->Invalidate caches
You may need to check optional if available
(clear file system cache and local history)
(clear vcs log cache and indexes)
Then click Invalidate and Restart.
This will solve your problem.
Thanks


text: Q: In a computer simulation, what do you call the level that abstracts away the simulated world for computation? In a computer simulation, what do you call the level that abstracts away the simulated world for computation? The simulation must be computed, so there's a level where the computation is done in a computer simulation, what do you call this level? Is there a word for it?


text:
Q: C, how to transfer sqlite3 database handle I'm trying to make some utils for using with sqlite databases.
For that I create sqlite3_ut.h and sqlite3_ut.c files
sqlite_ut.h
#ifndef sqlite3_ut_h
#define sqlite3_ut_h

#include <stdio.h>
#include "sqlite3.h"

int drop_table(sqlite3 handle);

#endif

sqlite_ut.c
int drop_table(sqlite3 handle)
{
int dropped = 0;
printf("Begin Drop\n");

sqlite3_exec(handle, "BEGIN;", NULL, NULL, NULL);
sqlite3_stmt *droptab;
if (sqlite3_prepare_v2(handle, "DROP TABLE mytable;", -1, &droptab, 0) != SQLITE_OK)
    printf("db error: %s\n", sqlite3_errmsg(handle));

if(droptab)
{
    sqlite3_step(droptab);
    dropped = 1;
}
else
    printf("Error: drop_table");

sqlite3_finalize(droptab);
sqlite3_exec(handle, "COMMIT;", NULL, NULL, NULL);

printf("End Drop\n");
return dropped;
}

sqlite_ut.h is included in main file.
sqlite3 *db;

int rc = sqlite3_open("m_test.db", &db);
if (rc)...

//error here
int dropped = drop_table(db);

Obviously, I can't transfer handle of opened database properly to drop_table function which is of sqlite3 type.
How to do that with suggested program cofiguration?

A: SQLite3 handles are of type sqlite3 *, not sqlite3. Redefine drop_table as follows:
int drop_table(sqlite3 *handle) { … }


text:
Q: proftpd ssh key-based authentication not working I've setup a new proftpd server with mod_sftp for SSH support, that I'm able to login to when I use a password. But when I try to use my SSH key, I'm unable to connect.
Here's the full proftpd.conf file:
[root@myers log]# cat /usr/etc/proftpd.conf
ServerName                      "Develop CENTS"
ServerType                      standalone
DefaultServer                   on

Port                            2215

UseIPv6                         off

# Umask 022 is a good standard umask to prevent new dirs and files
# from being group and world writable.
Umask                           022

MaxInstances                    15

User                            nobody
Group                           nobody

DefaultRoot ~

AllowOverwrite          on

# Bar use of SITE CHMOD by default
<Limit SITE_CHMOD>
  DenyAll
</Limit>

<IfModule mod_auth_pam.c>
    AuthPAM off
</IfModule>

<IfModule mod_sftp.c>
SFTPEngine on
SFTPHostKey /usr/etc/proftpd/rsa_key
SFTPHostKey /usr/etc/proftpd/dsa_key
Port 2216
SFTPAuthMethods publickey
MaxLoginAttempts 4
SFTPCompression delayed

        <VirtualHost www.mydomain.com>
        SFTPAuthorizedUserKeys file:/home/mydomain.com/.ssh/authorized_keys
        DefaultRoot ~
        </VirtualHost>
</IfModule>

Here's a line I see in /var/log/messages regardless of the authentication method used:
Mar 19 10:41:51 myers proftpd[29675]: myhost.com - unable to create namebind for 'www.mydomain.com' to IPAddress#21: No such file or directory

Other than that, the only thing appearing in the log file when I attempt to connect with a SSH key, is that the client does reach the server and a SSH2 session is opened, but the very next line indicates the SSH2 session is closed.
Any ideas?

A: Mar 19 10:41:51 myers proftpd[29675]: myhost.com - unable to create namebind for 'www.mydomain.com' to IPAddress#21: No such file or directory

It's just a cosmetic warning. As I understood you are using proftpd-1.3.5.

As part of the final work on 1.3.5, I started adding some of the
  foundation for supporting the HOST command (RFC 7151), which will give
  FTP true name-based virtual hosting support.  That added code is what
  is complaining (erroneouly) here. I have fixed up that code, which was
  erroneously logging that NOTICE level log message, in the master
  branch on GitHub.  I'll also be updating the
  1.3.5 branch so that that message is not logged so noisily, for the next maint release (which should be quite soon now).

You can find more at - http://sourceforge.net/p/proftp/mailman/proftp-user/thread/alpine.DEB.2.00.1503301702090.3566%40familiar.castaglia.org/#msg33678099

A: From your configuration, it looks like you'd like a normal FTP server on port 2215, and the SFTP server on port 2216.  In order to do this, you would need the mod_sftp configuration in its own <VirtualHost> section.  As your configuration stands, both Port directives appear in the same "vhost" context, and thus ProFTPD, when parsing the configuration, may not do what you expect.  I would recommend using something like:
# ... previous config ...
<IfModule mod_auth_pam.c>
    AuthPAM off
</IfModule>

<IfModule mod_sftp.c>
  # Here we give mod_sftp its own explicit vhost, and put all of
  # of the mod_sftp configuration within that <VirtualHost> section.
  <VirtualHost www.mydomain.com>
    Port 2216

    SFTPEngine on
    SFTPHostKey /usr/etc/proftpd/rsa_key
    SFTPHostKey /usr/etc/proftpd/dsa_key
    SFTPAuthMethods publickey
    MaxLoginAttempts 4
    SFTPCompression delayed
    SFTPAuthorizedUserKeys file:/home/mydomain.com/.ssh/authorized_keys
    DefaultRoot ~
  </VirtualHost>
</IfModule>

Hope this helps!


text:
Q: Why does my app appear as a blank white screen in App Switcher? I'm trying to understand where iOS gets the image from for App Switcher and when. What do I need to change to get control of what appears on App Switcher?
Right now, I can set a breakpoint on the first line of didFinishLaunchingWithOptions, my launch screen is visible, but App Switcher shows just a blank white screen with just the green battery rectangle. The App Switcher doesn't seem to pick up any image later in my app either.
I'm doing this in didFinishLaunchingWithOptions:
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

and later in a called method (after setting up appropriate views) this:
MMDrawerController * drawerController = [[MMDrawerController alloc]
                                         initWithCenterViewController:centerView
                                         leftDrawerViewController:leftDrawer];

drawerController.maximumLeftDrawerWidth = LeftDrawerWidth;
drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureModeTapCenterView;

[imageView addSubview:[self staticToolbar]];
[imageView addSubview:[self dsaToolbar]];

self.window.rootViewController = drawerController;

[self.window makeKeyAndVisible];

[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

A: I discovered that my issue was due a feature in the Salesforce SDK I am using. useSnapshotView in SFAuthenticationManager.h can be used to toggle this security option.


text:
Q: My inertia app does not detect some specific colors from Tailwind (Laravel Vue inertia tailwind) My app does not detect some colors of the Tailwind palette.
In this case, text-green-500 called primaryColorGreen and text-indigo-600 called secondaryColor are working properly.
However, text-red-300 as primaryColorRed is not working, but it does work if I change text-red-300 to `text-red-600.
If I change text-green-500 for text-green-300 it doesn't work.
The same for the indigo color...in general only some colors are working.
Layout.js:
export const useLayoutStore = defineStore('layout', {
    state: () => (
        {
            navigation: [],
            currentModels: [],
            currentRoute: 'x',
            theme: {
                classes: {
                    primaryColorGreen: 'text-green-500',
                },
            },
            color: {
                primary: {
                    primaryColorRed: 'text-red-300',
                }
            },
            textColor: {
                secondary: {
                    secondaryColor: 'text-indigo-600',
                }
            }
        }
    ),
});

HandleInertiaRequest.php:
            'theme'=>[
                'classes'=>[
                    'primaryColorGreen' => 'text-green-500',
                ],
            ],
            'color' => [
                'primary' => [
                    'primaryColorRed' => 'text-red-300',
                ]
            ],
            'textColor' => [
                'secondary' => [
                    'secondaryColor' => 'text-indigo-600',
                ]
            ],

Vue page:

<template>

hello
how are you
 Raul

A: If you are using Laravel Jetstream with Intertia stack, then the location of your file containing Tailwind classes are probably aren't scanned by tailwind. which normally scan php and vue files inside resources directory
check the tailwind.config.js and add those files which contains tailwind css classes.
or move those files to somewhere that are scan by tailwind default config


text:
Q: Scrollable text in a DIV of unknown size? I have this:

    Unknown content!

      This part should be scrollable when
      the total content overflows the SECTION

As you can see I want the user to be able to scroll the content in the lower half, but not the upper.
I can achieve this by using "resize" events, checking the size of SECTION and "dont-scroll", etc.
However, is there an easier way today, using only CSS?

A: Defining height of scroll-this id and using overflow-y: scroll will make scroll-this id scroll able
#scroll-this {
    height: 10px; //this can be as per your choice
    overflow-y: scroll;
}

I used 10px because your content is too less.

"This part should be scrollable when the total content overflows the
  SECTION".

Scroll will show only if line breaking content is greater then provided height.

A: A possible approach using Flexbox

body, html {
   margin: 0;
   padding: 0;
}

section {
   height: 100vh;
   display: flex;
   flex-flow: column nowrap;
}

section > div {
   padding: 20px;
}

div:not([id]) {
   background: #d8d8dc;
   flex: 1;
   overflow: auto;
}

    Unknown content!

    Lorem ipsum sit dolor amet

      This part should be scrollable when
      the total content overflows the SECTION

Lorem ipsum dolor sit amet,
          consectetuer adipiscing elit. Donec
          odio. Quisque volutpat mattis eros.
          Nullam malesuada erat ut turpis.
          Suspendisse urna nibh, viverra non,
          semper suscipit, posuere a, pede.

      ...

Example on codepen

A:

#scroll-this {
  height: 20px;
  overflow-y: scroll;
}

    Unknown content!

      This part should be scrollable when the total content overflows the SECTION


text:
Q: Strange type error when producing new sequence in map closure I was using the strategy from this question's answer, and I was interested in producing another sequence that is a function of the two being created by the iterator map:
extern crate itertools_num;

use itertools_num::linspace;

fn main() {
    // 440Hz as wave frequency (middle A)
    let freq: f64 = 440.0;
    // Time vector sampled at 880 times/s (~Nyquist), over 1s
    let delta: f64 = 1.0 / freq / 2.0;
    let time_1s = linspace(0.0, 1.0, (freq / 2.0) as usize)
        .map(|sample| { sample * delta});

    let (sine_440,
         sine_100,
         summed_signal): (Vec<f64>, Vec<f64>, Vec<f64>) =
        time_1s.map(|time_sample| {
            let sample_440 = (freq * &time_sample).sin();
            let sample_100 = (100.0 * &time_sample).sin();
            let summed_sample = &sample_440 + &sample_100;

            (sample_440, sample_100, summed_sample)
        }).unzip();
}

Like the closure indicates, the third signal is the sum of the previous two. What's baffling is the error I get:
error[E0271]: type mismatch resolving `<[closure@src/main.rs:17:21: 23:10 freq:_] as std::ops::FnOnce<(f64,)>>::Output == (_, _)`
  --> src/main.rs:23:12
   |
23 |         }).unzip();
   |            ^^^^^ expected a tuple with 3 elements, found one with 2 elements
   |
   = note: expected type `(f64, f64, f64)`
   = note:    found type `(_, _)`
   = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<std::iter::Map<itertools_num::Linspace<f64>, [closure@src/main.rs:11:14: 11:40 delta:_]>, [closure@src/main.rs:17:21: 23:10 freq:_]>`

error[E0308]: mismatched types
  --> src/main.rs:17:9
   |
17 |         time_1s.map(|time_sample| {
   |         ^ expected a tuple with 3 elements, found one with 2 elements
   |
   = note: expected type `(std::vec::Vec<f64>, std::vec::Vec<f64>, std::vec::Vec<f64>)`
   = note:    found type `(_, _)`

I could understand a type error, but why should the third tuple item just be completely ignored?

A: You can create custom unzip3 implementation based on the standard unzip:
trait IteratorUnzip3 {
    fn unzip3<A, B, C, FromA, FromB, FromC>(self) -> (FromA, FromB, FromC) where
        FromA: Default + Extend<A>,
        FromB: Default + Extend<B>,
        FromC: Default + Extend<C>,
        Self: Sized + Iterator<Item=(A, B, C)>,
    {
        let mut ts: FromA = Default::default();
        let mut us: FromB = Default::default();
        let mut vs: FromC = Default::default();

        for (t, u, v) in self {
            ts.extend(Some(t));
            us.extend(Some(u));
            vs.extend(Some(v));
        }

        (ts, us, vs)
    }
}

impl<A, B, C, T: Iterator<Item=(A, B, C)>> IteratorUnzip3 for T{}

fn main() {
    let freq: f64 = 440.0;

    let (sine_440, sine_100, summed_signal): (Vec<f64>, Vec<f64>, Vec<f64>) =
        [1.0, 2.0, 3.0].iter().cloned()
            .map(|time_sample| {
                let sample_440 = (freq * &time_sample).sin();
                let sample_100 = (100.0 * &time_sample).sin();
                let summed_sample = &sample_440 + &sample_100;
                (sample_440, sample_100, summed_sample)
            }).unzip3();

    println!("{:?}\n{:?}\n{:?}", sine_440, sine_100, summed_signal);
}

Playground

A: Iterator::unzip only supports 2-tuples. You can tell this from the trait bound Self: Iterator<Item=(A, B)> that appears in the where clause.

A: Iterator::unzip is only defined to return a tuple of two items:
fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
    where FromA: Default + Extend<A>,
          FromB: Default + Extend<B>,
          Self: Iterator<Item=(A, B)>,

Note how the return type is (FromA, FromB) - a tuple with two values.


text:
Q: pg: exec_params not replacing parameters? First time using pg gem to access postgres database. I've connected successfully and can run queries using #exec, but now building a simple query with #exec_params does not seem to be replacing parameters. I.e:
get '/databases/:db/tables/:table' do |db_name, table_name|
  conn = connect(db_name)
  query_result = conn.exec_params("SELECT * FROM $1;", [table_name])
end

results in  #<PG::SyntaxError: ERROR: syntax error at or near "$1" LINE 1: SELECT * FROM $1; ^ >
This seems like such a simple example to get working - am I fundamentally misunderstanding how to use this method?

A: You can use placeholders for values, not for identifiers (such as table and column names). This is the one place where you're stuck using string interpolation to build your SQL. Of course, if you're using string wrangling for your SQL, you must be sure to properly quote/escape things; for identifiers, that means using quote_ident:

+ (Object) quote_ident(str)
Returns a string that is safe for inclusion in a SQL query as an identifier. Note: this is not a quote function for values, but for identifiers.

So you'd say something like:
table_name   = conn.quote_ident(table_name)
query_result = conn.exec("SELECT * FROM #{table_name}")


text:
Q: Nginx proxy_pass not working for tomcat (404 not found error) My angular app is running on  localhost:3030 through nginx.
My rest service is running on tomcat localhost:7001
nginx-conf settings :
enter code here
 server {
    server_name localhost;
        listen 3030;

        location / {
        root D:\Ionic_workspace\merigaadi\www;
        }
        location /app {

          proxy_pass   http://localhost:7001/;

        }
       }

I have tried everything to fix...but didn't get any luck. I am getting the following error:
GET http://localhost:3030/app/unauth/login/authenticate 404 (Not Found)

proxy_pass is not working

Please help me on this.


text:
Q: Why does containsObject not work on an NSSet copy of NSMutableSet? I'm having an issue when creating a set copy of a mutable set, and then having containsObject fail for the (new) set copy.
For example:
NSString *sameID = @"XYZ";
Then on main thread/sometimes on different thread:
[mutableSet addObject:sameID];
NSLog(@"adding Object: %@", sameID);

Then on a background thread, always after (I've verified with logging that) sameID has been added:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    NSSet<NSString *> *newSet = self.mutableSet.copy;
    if ([newSet containsObject:sameID]) {
      // do stuff
    }
});

Seen with a breakpoint:
1. po [newSet containsObject:sameID] // returns NO
2. po [self.mutableSet containsObject:sameID] // returns YES

I've tested that there is no additional or hidden whitespace for the sameID string. AFAIK containsObject for sets containing NSString uses isEqual which doesn't/shouldn't matter if the strings have different pointers, right?
Edit: Some additional information: the NSStrings that are being added to the mutableSet are happening on different threads but always before creating the newSet copy. Creating and checking newSet is being done on a background thread which is why I'm copying mutableSet (and I'm seeing with logging that this is always after having added string(s) to mutableSet). So I see with log statements that the string (sameID) was added to mutableSet, then on a background thread I'm copying mutableSet to be a set and quickly checking that set for the same string (sameID) and it's not there.
Edit2:
I've tested the code below and it passes for me, however when I tried implementing the same solution regarding above it still has the same result (mutableSet contains the string yet newSet does not).
import XCTest
import Foundation

class CustomObj: NSObject {
    let id: String

    init(id: String) { self.id = id }

    override func isEqual(_ object: Any?) -> Bool {
        if let other = object as? CustomObj {
            return self.id == other.id
        } else {
            return false
        }
    }

    override var hash: Int {
        return id.hashValue
    }
}

func testSetStrings() {
    let set = NSMutableSet(object: CustomObj(id: "String-1"))
    let copySet: Set<CustomObj> = set.copy() as! Set<CustomObj>

    let customObjForTest = CustomObj(id: "String-1")

    XCTAssertTrue(set.contains(customObjForTest), "Does Not Contain")
    XCTAssertTrue(copySet.contains(customObjForTest), "Copy Does Not Contain")
}

testSetStrings()


text:
Q: GCP cloud functions vs cloud Run which service is better in terms of # of concurrent executions, performance and cost GCP Cloud functions or Cloud Run.
I have an API, the expected traffic is 30000 req/second. Now I want to deploy to GCP. which one should i use cloud function or cloud run?

A: I wrote this article. Quite old and without all the latest feature of Cloud Run, but in term of concurrency, the basis are the same
In addition, I wrote another article on the multi CPU usage of Cloud Run. It could be interesting to process concurrently on different instances but also inside the same instance (only possible with Cloud Run, not with Cloud Function that can handle only 1 request at a time per instance).


text:
Q: deploy already installed application on WebLogic 10.3.4 using wlfullclient.jar I have an application named HelloWorld installed, yet not deployed. Its state is Installed, like such:

When I'm trying to deploy it on target server, say AdminServer, it results in creating a new application named helloworld.war which is deployed on AdminServer whereas the original HelloWorld app remains in Installed state. App helloworld.war is the one that is in state Active... Snapshot:

Here's the code I use to deploy the already installed app:
File warFilePath = new File("c:/helloworld.war"); // war file path on AdminServer machine

Target adminServerTarget = deployManager.getTarget("AdminServer");
WebLogicTargetModuleID targetModuleID = deployManager.createTargetModuleID(
        "HelloWorld", ModuleType.WAR, adminServerTarget);
WebLogicTargetModuleID[] targetModuleIDs = new WebLogicTargetModuleID[1];
targetModuleIDs[0] = targetModuleID;

ProgressObject redeployProcessObject =
    deployManager.redeploy(targetModuleIDs, warFilePath, null /*no deployment plan*/ );

There are two surprising facts, though.
First, when running this code on WebLogic versions 9.x to 10.3.3 it works great.
Second, when running this code from WLST prompt, with jython it also works great even on version 10.3.4 (I can attach the exact commands although they're the same as java except for syntactic adoptions)...
My question is, how do I make it work also on 10.3.4?

A: I should have thought that no one would answer this question... :)
Anyway, I found a solution. I should have used deploy instead of redeploy, with a DeploymentOptions of which name is the existing application name (HelloWorld):
      ProgressObject redeployProcessObject = null;
      try {
          final DeploymentOptions options = new DeploymentOptions();
          options.setName(applicationName);
          redeployProcessObject = deployManager.deploy(
              targetModuleIDs, warFilePath, null /*no deployment plan*/, options);
      } catch (TargetException e) {
          final String message =
                  String.format("Deployment of application %s on target %s failed: %s",
                          applicationName, allTargets, e.getMessage());
          _log.error(message, e);
      }

According to the docs, redeploy only replaces the current application files and plan with an updated version. Whereas deploy distributes the files (from the AdminServer) to the target(s) and starts the application.
Also, after digging deep in WebLogic's jython scripts and jars I found out that this is exactly what's done when invoking redeploy in the WLST.


text:
Q: Hibernate EventListener, access to entity deprecated / removed. Bad design, or are there alternative solutions? I'm updating from 5.4.14 to 5.4.33 (the latest version in 5.4, in preparation for moving to 5.6 shortly). In our code base we make use of event listeners, specifically PreUpdateEventListener and PreInsertEventListener to implement various checks before things are persisted.
In these implementations, we sometimes grab the entity instance and manipulate it directly. For example via PreInsertEvent#getEntity. This has worked very well for many years.
In 5.4.33 (but probably earlier, but not in 5.4.14) getEntity is now deprecated with the comment
Support for JACC will be removed in 6.0
My questions

*

*What is JACC?

*Is it considered poor/bad design to access an entity instance directly in these event listeners, or are there alternative ways you can implement similar functionality? As far as I can see the only information you will be provided going forward is the entity class and the object state as an Object[].

A: I worked around the problem by re-writing our event listeners as JPA listeners instead, thereby removing the direct dependency on Hibernate altogether.


text:
Q: Order bars within each factor using ggplot2 I am creating this "barplot" with ggplot, but I would like to be able to reorrder the bars within each categories so the highest bars are on top. In short having a High to Low bars ordering withing each categories.
Below is my code - Any hints are welcome - Thanks
library("ggplot2")
d <- read.csv('http://db.tt/EOtR3uh', header = F)

d$V4 <- factor(d$V2, levels=d$V2)
base_size <- 11
ggplot(d, aes(d$V4, -log10(d$V3), fill=d$V1)) +
geom_bar(stat="identity") +
coord_flip() +
labs(y = "-log10(Pvalues)",x = "",fill="") +
theme_grey(base_size = base_size) +
scale_x_discrete(expand = c(0, 0))

A: Just sort your levels accordingly
d <- read.csv('http://db.tt/EOtR3uh', header = F, stringsAsFactors=FALSE)
lvls <- d$V2[order(d$V1,-d$V3)]
d$V4 <- factor(d$V2, levels=lvls)

A: Another way to achieve the same objective
require(ggplot2)
d = arrange(d, V1, -V3)                             # arrange d by V1 and -V3
d = transform(d, V2 = factor(V2, as.character(V2))) # order V2 as in d

qplot(V2, -log10(V3), fill = V1, geom = 'bar', data = d) +
  coord_flip()

A: I am answering my question here :
The line to change is
d$V4 <- ordered(d$V2, levels=d$V2[order(d$V1,-d$V3)])

Full code :
library("ggplot2")
d <- read.csv('http://db.tt/EOtR3uh', header = F)

d$V4 <- ordered(d$V2, levels=d$V2[order(d$V1,-d$V3)])
base_size <- 11
ggplot(d, aes(d$V4, -log10(d$V3), fill=d$V1)) +
geom_bar(stat="identity") +
coord_flip() +
labs(y = "-log10(Pvalues)",x = "",fill="") +
theme_grey(base_size = base_size) +
scale_x_discrete(expand = c(0, 0))


text:
Q: Getting value of only 1 random row and set the values to a class I've been trying to set the value of a random row from my table but it kept on giving me a null value when I try to retrieve it from my servlet.
This is my codes to retrieve the random row and setting the values to my class. sq is the name of the table.
public Question getQuestion() throws Exception{
    System.out.println("Getting the questions");

    Question question = null;
    try{
        String selectStatement = "select * from sq order by rand() limit 1";
        PreparedStatement prepStmt = con.prepareStatement(selectStatement);
        ResultSet rs = prepStmt.executeQuery();

        if(rs.next()){
            Question myquestion = new Question();
            myquestion.setQid(rs.getInt("QID"));
            myquestion.setQuestion(rs.getString("question"));
            //System.out.println(rs.getString("question"));
            System.out.println(myquestion.getQuestion());
        }

    }catch(Exception ex){
        throw new Exception("Error:" + ex.getMessage());
    }
    return question;
}

It prints out the question here but it gives me a null value in my servlet.
try{
            Database myDatabase = new Database();
            Question question = myDatabase.getQuestion();
            if(question != null){
                HttpSession session = request.getSession(true);
                session.setAttribute("secquestion", question);
                request.getRequestDispatcher("SecQn.jsp").forward(request, response);
            }else{
                System.out.println("ERROR");
            }
            //request.getRequestDispatcher("Home.jsp").forward(request, response);
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
    }

It prints out ERROR which means question's value is null when I have already set the value previously. How do I set the value correctly? Or is there anything wrong with my codes?

SOLVED THE ERROR. THIS IS THE LATEST OF THE UPDATED CODES.
public Question getQuestion() throws Exception{
    System.out.println("Getting the questions");

    Question question = null;
    try{
        String selectStatement = "select * from sq order by rand() limit 1";
        PreparedStatement prepStmt = con.prepareStatement(selectStatement);
        ResultSet rs = prepStmt.executeQuery();
        if(rs.next()){
            question = new Question();
            question.setQid(rs.getInt("QID"));
            question.setQuestion(rs.getString("question"));
            System.out.println(question.getQuestion());
        }
    }catch(Exception ex){
        throw new Exception("Error:" + ex.getMessage());
    }
    return question;
}

A: In getQuestion() method you are returning question but you never assigned it any value.
You should either return myquestion , or assign  before returning.
question = myquestion ;


text:
Q: Como mostrar una imagen almacenada en formato BLOB en una base de datos MySQL en PHP Tengo un campo imagen que es de tipo BLOB en mi base de datos de MySQL,los datos los recojo mediante PDO, pero a la hora de visualizarlo no me muestra nada , he buscado en internet y en todos lados me ponía lo mismo con src="data:image/jpeg;base64.
Este es mi código:
 <?php
require_once './BaseDatos.php';
$id = $_GET['id'];
$bd = new BaseDatos('foro');
$imagen = $bd->SenetenciaSelect("usuarios", ["id"=>$id])[0]["image"];
echo '';

La variable $imagen retorna esto si la visualizo:

ÿØÿà\0JFIF\0\0\0\0\0\0ÿþ\0;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90 ÿÛ\0C\0  %# , #&\')*)-0-(0%()(ÿÛ\0C   (((((((((((((((((((((((((((((((((((((((((((((((((((ÿÀ\0@ \0\"\0ÿÄ\0\0\0\0\0\0\0\0\0\0\0  ÿÄ\0µ\0\0\0}\0!1AQa\"q2'¡#B±ÁRÑð$3br'   %&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ"…†‡ˆ‰Š'""•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ\0\0\0\0\0\0\0\0   ÿÄ\0µ\0\0w\0!1AQaq\"2B'¡±Á  etc.

A: Todo apunta a que es un problema de conversión de juegos de caracteres que está corrompiendo los datos de tu BLOB o bien estás sufriendo algún problema relacionado con usar las funciones obsoletas a partir de PHP 5.5 de mysql_* o mal escapado del SQL.

Problemas relacionados con el juego de caracteres:
Si en algún momento usas SET CHARACTER SET utf8 tras establecer la conexión el cliente empezará a realizar conversión de caracteres incluso en los campos de tipo BLOB desde el juego de caracteres en el que esté la tabla.
Si usas en su lugar SET NAMES utf8, tanto el servidor como el cliente acordarán el mismo juego de caracteres para todo y no habrá conversión en el lado del cliente que pueda corromper los datos.
Mira los datos de esta página.
En ella puedes ver que SET NAMES 'charset_name' es equivalente a:
SET character_set_client = charset_name;
SET character_set_results = charset_name;
SET character_set_connection = charset_name;

Sin embargo SET CHARACTER SET 'charset_name' equivale a:
SET character_set_client = charset_name;
SET character_set_results = charset_name;
SET collation_connection = @@collation_database;

Por lo que si la tabla está en su valor por defecto (latin1_swedish_ci) se estarán corrompiendo los datos.

Problemas relacionados con el mal escapado de SQL:
Para insertar los datos de manera adecuada en la base de datos debes modificar tu código y usar mysql_real_escape_string() en lugar de addslashes():
$fp = fopen($ruta, 'r');
$datos_image = fread($fp, filesize($ruta));
$datos_image = mysql_real_escape_string($datos_image);
fclose($fp);

De esa manera no tendrás problemas con caracteres extraños. Deberías probar también a usar mysql_set_charset().
Aún así, te insto a migrar tu código a mysqli o, mejor aún, a PDO. De esa manera podrás hacer consultas preparadas con asignación de campos en las que no tendrás problemas con el escapado de cadenas.

A: A mi me resulto esto
echo '';

A: EDIT : Ejemplo completo
<?php
    /*
     *Modifica modo de conexión, este ejemplo usa mysqli, pero puedes cambiarlo a PDO
     *Modifica las credenciales de conexión: usuario, password, nombre de la BD
     *Modifica los nombres de tablas y columnas
    */
    $conn = mysql_connect("localhost", "root", "");
    mysql_select_db("phppot_examples");
    $sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
    $result = mysql_query($sql);
?>

        <TITLE>List BLOB Images</TITLE>

<?php
    while($row = mysql_fetch_array($result)) {
?>
//En $row["imageId"] debes cambiar imageId por como se llama en tu tabla la columna que tiene la id de la imagen
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" />

<?php
    }
    mysql_close($conn);
?>

Tres posibles soluciones (@deprecated):

A.
Usando tu variable $imagen después de $imagen=$bd... pones esto y comentas el actual código en el que intentas mostrar la imagen:
<img src="image.php?id=<?php echo $imagen; ?>" />
header('Content-Type: image/jpeg');
echo $imagen;

B.
También usando tu variable $imagen después de $imagen=$bd... comenta tu actual código para mostrar la imagen y copia y pega esto:
echo '';

C.
¿No funciona? Asegúrate de que tu imagen es correcta en la base de datos.

A: Guiándome por tu comentario en la respuesta de @a-cedano.
Me armé una prueba y parece que el problema está en que antes de guardar el BLOB le aplicas addslashes pero no le aplicas el stripslashes al recuperar la info
este es mi codigo de prueba, (asume un archivo prueba.jpg válido en la misma ruta)
<?php

$ruta = 'prueba.jpg';
$fp = fopen($ruta, 'r');
$datos_image = fread($fp, filesize($ruta));
$datos_image = addslashes($datos_image);
fclose($fp);

echo '';
//var_dump($datos_image);

?>


text:
Q: Issue with PHP curl / json POST I am running into an issue trying to issue a POST to the chargify API log payments from within a form.
However, it appears that the POST is actually being sent as a GET for some reason as it's returning an error.
Can anyone offer any advice on what I may be doing wrong? Postman is working just fine sending a POST with the JSON as the body, but I can't get it to work from PHP.
(note: the <urlmaskedforprivacy> is obviously not in my actual code)
    //find invoice id # using invoice number search form
    $invoiceNumber = fRequest::get('invoicenumber');
    $json = file_get_contents('https://<maskedforprivacy>.chargify.com/invoices.json?number=' . $invoiceNumber);
    $returnedInvData = fJSON::decode($json);
    $invoiceId = $returnedInvData[0]->invoice->id;

    // grab form data as payment info to send to chargify
    $paymentAmount = fRequest::Get('amount');
    $memo = fRequest::Get('memo');

    if ((isset($invoiceNumber,$paymentAmount,$memo))) {

    $url = 'https://<maskedforprivacy>.chargify.com/subscriptions/' . $invoiceId . '/payments.json';

    $params = array(
                      'payment' => array(
                           'amount'   => $paymentAmount,
                           'memo'    => (string)$memo
                      ),
                );

    // encode as json
    $content = FJSON::encode($params);

    // send to chargify
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
            array("Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

    $json_response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ( $status != 201 ) {
        die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
    }

    curl_close($curl);

    $response = json_decode($json_response, true);

    }

A: I've used this one code, but it returns 401 error and asks for Basic auth. in json_response variable. May be you've missed it?
$paymentAmount = 10;
    $memo = 'test';

    $url = 'https://test.chargify.com/subscriptions/1/payments.json';

    $params = array(
                      'payment' => array(
                           'amount'   => $paymentAmount,
                           'memo'    => (string)$memo
                      ),
                );

    // encode as json
    $content = json_encode($params);

    // send to chargify
    $curl = curl_init($url);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
            array("Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

    $json_response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ( $status != 201 ) {
        die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
    }

    curl_close($curl);

    $response = json_decode($json_response, true);


text:
Q: pandas.read_json failing on this input? I'm trying to convert a list of JSON objects to a pandas DataFrame.  However, the JSON object has unquoted True/False, and None values, which appears to make read_json error out.  Is there a way to make the pandas.read_json method handle Boolean and None values?
Updated with real code (my actual JSON I am getting from a web service, but I'm not able to post the real content):
import pandas as pd
x = '[{"A": "some text","B": True,"C":7},{"A": "more text","B":False,"C":8},{"A":None,"B":False,"C":9}]'
pd.read_json(x)

ValueError: Expected object or value

if I quote the Nones and Booleans it seems to work.
import pandas as pd
x = '[{"A": "some text","B": "True","C":7},{"A": "more text","B":"False","C":8},{"A":"None","B":"False","C":9}]'
pd.read_json(x)

Of course they are then strings rather than Booleans and NaNs
Updated with error message
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-42-c251da58cd34> in <module>()
      1 import pandas as pd
      2 x = '[{"A": "some text","B": True,"C":7},{"A": "more text","B":False,"C":8},{"A":None,"B":False,"C":9}]'
----> 3 pd.read_json(x)

C:\Users\Chris\AppData\Local\Continuum\Miniconda3\lib\site-packages\pandas\io\json.py in read_json(path_or_buf, orient, typ, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit)
    196         obj = FrameParser(json, orient, dtype, convert_axes, convert_dates,
    197                           keep_default_dates, numpy, precise_float,
--> 198                           date_unit).parse()
    199
    200     if typ == 'series' or obj is None:

C:\Users\Chris\AppData\Local\Continuum\Miniconda3\lib\site-packages\pandas\io\json.py in parse(self)
    264
    265         else:
--> 266             self._parse_no_numpy()
    267
    268         if self.obj is None:

C:\Users\Chris\AppData\Local\Continuum\Miniconda3\lib\site-packages\pandas\io\json.py in _parse_no_numpy(self)
    481         if orient == "columns":
    482             self.obj = DataFrame(
--> 483                 loads(json, precise_float=self.precise_float), dtype=None)
    484         elif orient == "split":
    485             decoded = dict((str(k), v)

ValueError: Expected object or value

So, if I treat the JSON as a python object rather than JSON I get a different error.  This code
x =   [{"A": "some text","B": "True","C":7},{"A": "more text","B":"False","C":8},{"A":"None","B":"False","C":9}]
pd.read_json(x)

yields
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-59-076202b1f4ce> in <module>()
      1 x =   [{"A": "some text","B": True,"C":7},{"A": "more text","B":False,"C":8},{"A":"None","B":False,"C":9}]
----> 2 pd.read_json(x)

C:\Users\Chris\AppData\Local\Continuum\Miniconda3\lib\site-packages\pandas\io\json.py in read_json(path_or_buf, orient, typ, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit)
    196         obj = FrameParser(json, orient, dtype, convert_axes, convert_dates,
    197                           keep_default_dates, numpy, precise_float,
--> 198                           date_unit).parse()
    199
    200     if typ == 'series' or obj is None:

C:\Users\Chris\AppData\Local\Continuum\Miniconda3\lib\site-packages\pandas\io\json.py in parse(self)
    264
    265         else:
--> 266             self._parse_no_numpy()
    267
    268         if self.obj is None:

C:\Users\Chris\AppData\Local\Continuum\Miniconda3\lib\site-packages\pandas\io\json.py in _parse_no_numpy(self)
    481         if orient == "columns":
    482             self.obj = DataFrame(
--> 483                 loads(json, precise_float=self.precise_float), dtype=None)
    484         elif orient == "split":
    485             decoded = dict((str(k), v)

TypeError: Expected String or Unicode


text:
Q: How to subtract 1d array from 2d array's rows in Numpy What I want to do is to subtract 1d array from other 2d array's rows.
I found, in some case, result was wrong and confused me. Below code worked good as I wanted.
lst1 = [[10,11,12,13,14], [20,21,22,23,24], [30,31,32,33,34]]
lstave = [10,20,30,40,50]
# lstave = [0.1,0.2,0.3,0.4,0.5]  # <- This is also no problem.
# transform them to nparray.
arr1 = np.array(lst1).reshape(3,5)
arrave = np.array(lstave)

for i in range(len(lst1)):
    print(arr1[i] - arrave)
    # print(np.subtract(arr1[i], arrave))   # <- This is also work

Then I got following as expected.
[  0  -9 -18 -27 -36]
[ 10   1  -8 -17 -26]
[ 20  11   2  -7 -16]

However, when I change the array "lstave" to [1, 2, 3, 4, 5] and subtract,
lst1 = [[10,11,12,13,14], [20,21,22,23,24], [30,31,32,33,34]]
lstave = [1,2,3,4,5]
arr1 = np.array(lst1).reshape(3,5)
arrave = np.array(lstave)

for i in range(len(lst1)):
    print(arr1[i] - arrave)

I got following.
[9 9 9 9 9]
[19 19 19 19 19]
[29 29 29 29 29]

I cannot understand why the only 1st element subtraction performed 5 times.
I feel that broadcast is working wrong way, but I don't know how to fix this.
Can someone help me out?
Thank you,

A: It does actually work, just:
10 - 1

Gives:
9

But:
11 - 2

Also gives:
9

This is more of a math question.
[10 - 1, 11 - 2, 12 - 3, 13 - 4, 14 - 5]

Would give:
[9, 9, 9, 9, 9]

So your code works.
If you make arrave to be:
[0, 1, 2, 3, 4]

All the final values would be 10.


text:
Q: Can it be considered bad practice to rely on automated tests running in order? In my acceptance test suites specifically I see a lot of tests designed to run in a particular order (top to bottom) which in some ways makes sense for testing a particular flow, but I've also heard this is bad practice. Can anyone shed some light on the advantages and drawbacks here?

A: In majority situations if you rely on the order, there is something wrong. It's better to fix this because:

*

*Tests should be independent to be able to run them separately (you should be able to run just 1 test).

*Test-running tools often don't guarantee the order. Even if today it's a particular sequence, tomorrow you could add some configuration to the runner and the order will change.

*It's hard to determine what's wrong from the test reports since you see a lot of failures while there is only 1 test that failed.

*Again - from the test report tools it's not going to be easy to track the steps of the tests because these steps are assigned to different tests.

*You won't be able to run them in parallel if you'd need to (hopefully you don't).

If you want to share logic - create reusable classes or methods (see this).
PS: I'd call these System Tests, not Acceptance Tests - you can write acceptance tests on unit or component levels too.


text:
Q: Configuring URL Routes in an asp.net hybrid (web forms and mvc) app I have an app that others have worked on that was originally a Web.forms app with multiple parts and is being converted to MVC. There are two parts that have gone to MVC and one works fine but the other I am having routing issues.
The route appears in .cshtml as:
Test Table

The project is web forms with a folder called Areas > TableProject > Controllers and other folders related to the mvc project. In controllers is a HomeController.cs that has:
[HttpGet]
[Route("{id:int}/{seId:int?}", Name = "TableDetails")]
public ActionResult TableDetails(int id, int? seId)
{
    // code
}

The route file is as such:
public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.RouteExistingFiles = false;
        routes.IgnoreRoute("anotherproject/{*pathInfo}");

        routes.MapPageRoute(
            "WebFormDefault",
            string.Empty,
            "~/index.aspx");

        routes.MapRoute(
            "MvcDefault",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional });

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }

I cannot get the table project to work as the TableDetails route cannot be found.  The other MVC project works fine.
The error is:

A route named 'TableDetails' could not be found in the route collection. Parameter name: name

A: You are missing the method call to register attribute routing, MapMvcAttributeRoutes. That means that none of your [Route] attributes are being registered.
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.RouteExistingFiles = false;
    routes.IgnoreRoute("anotherproject/{*pathInfo}");

    // Register [Route] attributes
    routes.MapMvcAttributeRoutes();

    routes.MapPageRoute(
        "WebFormDefault",
        string.Empty,
        "~/index.aspx");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

In addition, the MvcDefault route is blocking every call to the Default route, making Default an unreachable execution path. See Why map special routes first before common routes in asp.net mvc? for details.


text:
Q: Gmail API Access Single User Without Domain Wide Delegation We have a bit of a dilemma that we are running into with a couple applications that are trying to read a given users email without user interaction to authorize. The key to this approach is that we want no user interaction, and want to load the client server application with the proper JSON credentials downloaded from the Google Developer Console.
I have this approach working for programs where we create a service account in the Developer Console, and then delegate domain wide authority to that account with the proper scope access. However what we are hoping is that we don't have to delegate domain wide authority, and just read the users email who created this developer console project. I have tried many different types of solutions for this, but always run into the same limitation that I have to grant domain wide access.
What I am wondering is if there is any way to gain access to a single users mailbox using a server to server type approach and not have to grant domain wide access?
I appreciate your help with this issue!

A: There is no supported authorization flow for what you want to do.  You must either use a service account that has been delegated domain-wide authority, or you must use a 3LO flow that involves user consent.

A: It seems you're looking for OAuth for Server to Server Application. You will also be using a service account. But, granting of domain-wide authority for service accounts is an optional thing. You don't have to enable it if you don't want to.

To support server-to-server interactions, first create a service
  account for your project in the Developers Console. If you want to
  access user data for users in your Google Apps domain, then delegate
  domain-wide access to the service account.
Then, your application prepares to make authorized API calls by using
  the service account's credentials to request an access token from the
  OAuth 2.0 auth server.
Finally, your application can use the access token to call Google
  APIs.


text:
Q: Non-ASCII characters not displaying correctly after Python manipulation I'm using QGIS 2.18 on a Mac (Sierra).
I'm doing some pretty extensive data manipulation using a virtual column, and using the function editor (so Python) to do so: one of my functions, for example, is to change street-name abbreviations to long-format (e.g.: All => Allée), and in French.
The result is encoded in UTF-8, and I can't seem to find a means to translate it into whatever encoding is needed to display it correctly on a map... The result of any string containing an accented character is 'null' in the attributes table.
Yet in another 'street name' layer, pulled directly from a PostGIS database, even accented labels (street names) display correctly.
Is this a common problem, and is there any way around this?
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from qgis.core import *
from qgis.gui import *
from qgis.utils import qgsfunction
import re

@qgsfunction(args='auto', group='Custom')
def streettype_format(input, feature, parent):
    rep = {
        "CITE":"Cité",
        "ALL":"Allée",
        "RUE":"Rue",
        "RPT":"Rond-point",
        "SENT":"Sentier",
        "VLA":"Villa",
        "TERR":"Terrace",
        "CHEM":"Chemin",
        "CAR":"Carrefour",
        "HAM":"Hameau",
        "BD":"Boulevard",
        "AV":"Avenue",
        "CRS":"Cours",
        "VOIE":"Voie",
        "CHAU":"Chaussée",
        "ARC":"Arcade",
        "GAL":"Galérie"
    }
    rep = dict((re.escape(k), v) for k, v in rep.iteritems())
    pattern = re.compile("|".join(rep.keys()))
    input = pattern.sub(lambda m: rep[re.escape(m.group(0))], input)
    return input

Also: from some d*cking around in the Python console:
>>>> import sys
>>>>sys.getdefaultencoding()
ascii
>>>>u"Héy"
u'H\xe9y'
>>>>"Héy"
'H\xc3\xa9y'

A: Working, but only the bottom solution: Please see below.
// FALSE SOLUTION
I found a solution... I would like to know more about the how and why of -why- it works, but it works. Germán Carrillo's "add a 'u' prefix" idea set me in that direction, so thanks.
Changing:
return input

at the end of my function to:
return u.input

...did the trick.
PS: just to follow that rabbit hole all the way, I eliminated the 'u's I had added to the dictionary's accented character strings... still works, so they weren't required there. Again, as long as the characters remain 'internal', they're okay (treated as utf-8).
Hypothesising: this must mean that Qgis has no means of determining a custom function output's encoding (or it doesn't even try), and the added 'u' gave it the information it needed... which means that Qgis falls back to 'ascii' when that information is not there.
// additional roadblock-variables
Something in that worked 'temporarily', but after a while the entire function returned 'NULL', and I got a (quite logical, actually) "global variable 'u' undeclared" error. With the additional 'unexplainable' environment behaviour, I understand even less. This is maddening.
// REAL SOLUTION
This is the code that worked: I eliminated all possible 'reserved word' conflicts, and expanded my virtual column to an 'unlimited' text type (and -this- might have been the problem: with four (at least) characters to each letter, utf-8 encoding may have gone beyond the 50-char limit I had initially set).
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Define new functions using @qgsfunction. feature and parent must always be the
last args. Use args=-1 to pass a list of values as arguments
"""
from qgis.core import *
from qgis.gui import *
from qgis.utils import qgsfunction
import re

@qgsfunction(args='auto', group='Custom')
def streettype_format(shortvers, feature, parent):
    rep = {
        "CHAU":u"Chaussée",
        "CITE":u"Cité",
        "SQ":"Square",
        "PROM":"Promenade",
        "GAV":"Grande avenue",
        "PL":"Place",
        "PER":"Passerelle",
        "COUR":"Cour",
        "RTE":"Route",
        "PAS":"Passage",
        "PONT":"Pont",
        "RLE":"Ruelle",
        "PRT":"Porte",
        "IMP":"Impasse",
        "SOUT":"Souterrain",
        "QU":"Quai",
        "ESPL":"Esplanade",
        "ALL":u"Allée",
        "RUE":"Rue",
        "RPT":"Rond-point",
        "SENT":"Sentier",
        "VLA":"Villa",
        "TERR":"Terrace",
        "CHEM":"Chemin",
        "CAR":"Carrefour",
        "HAM":"Hameau",
        "BD":"Boulevard",
        "AV":"Avenue",
        "CRS":"Cours",
        "VOIE":"Voie",
        "ARC":"Arcade",
        "GAL":u"Galérie",
        "PARV":"Parvis"
    }
    rep = dict((re.escape(k), v) for k, v in rep.iteritems())
    pattern = re.compile("|".join(rep.keys()))
    longvers = pattern.sub(lambda m: rep[re.escape(m.group(0))], shortvers)
    return longvers

BUT: the 'return u.output' thing I did earlier -did- work -before- I changed the field's character length limit.
Confusing.

A: Did you try this?
Settings->Options->Advanced->"I will be careful, I promise!" -> Processing -> encoding -> Set "Value" to UTF-8
I think this was the fix to a similar problem I had on Windows. Not sure though... I tried so many things. Encoding problems is a pain.


text:
Q: List view doesn't update I have a code that adds work to a register client. The problem is that when I register work for the client and the sheet is being dismissed the list view doesn't update. I have to go out from the view and back in for it to display the latest registered work.
All variables I have is either @State or @ObservedObject and to my understanding the view should refresh whenever those are updated. I will provide my code for the WorkListView and the AddWorkView.
struct WorkListView: View {
    @State var client: Client
    @ObservedObject var clientData = ClientData()
    @State private var showingAddWork = false
    @State private var additionalInfo: [String] = []

    let dateFormatterStart: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "MMM d, HH:mm"
        return formatter
    }()
    let dateFormatterEnd: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter
    }()
    func calculateHoursAndMinutes(startDate: Date, endDate: Date) -> String {
        let interval = endDate.timeIntervalSince(startDate)
        let hours = Int(interval) / 3600
        let minutes = Int(interval) / 60 % 60
        return "\(hours) hour(s) and \(minutes) minute(s)"
    }
    var body: some View {

        List {
            Section {
                VStack(alignment: .leading) {
                    Text("Company")
                        .font(.footnote)
                        .foregroundColor(.secondary)
                    TextField("Company", text: $client.company)
                        .fontWeight(.semibold)
                        .autocorrectionDisabled(true)
                }

                VStack(alignment: .leading) {
                    Text("E-mail")
                        .font(.footnote)
                        .foregroundColor(.secondary)
                    TextField("E-mail", text: $client.eMail)
                        .fontWeight(.semibold)
                        .keyboardType(.emailAddress)
                }
                VStack(alignment: .leading) {
                    Text("Phone")
                        .font(.footnote)
                        .foregroundColor(.secondary)
                    TextField("Phone", text: $client.phone)
                        .fontWeight(.semibold)
                        .keyboardType(.numberPad)
                }
                VStack(alignment: .leading) {
                    Text("Price")
                        .font(.footnote)
                        .foregroundColor(.secondary)
                    TextField("Price", text: $client.price)
                }

            }

            Section(header: Text("Performed Work")) {
                ForEach(client.work.indices) { work in
                        VStack(alignment: .leading) {
                            Text("\(self.dateFormatterStart.string(from: self.client.work[work].startDate)) to \(self.dateFormatterEnd.string(from: self.client.work[work].endDate))\nDuration: \(self.calculateHoursAndMinutes(startDate: self.client.work[work].startDate, endDate: self.client.work[work].endDate))\n\(self.client.work[work].title)")

                        }

                }

                .onDelete { indexSet in
                    guard let workIndex = indexSet.first else { return }
                    self.clientData.deleteWork(for: self.client, work: self.client.work[workIndex])
                }

            }
        }

        .navigationBarTitle(client.name)
        .navigationBarItems(trailing: Button(action: {
            self.showingAddWork = true
        }) {
            Image(systemName: "plus")
        })
        .sheet(isPresented: $showingAddWork) {
            AddWorkView(client: self.client, clientData: self.clientData, isPresented: $showingAddWork)

        }
    }
}

And here is the View for adding the work
struct AddWorkView: View {
    @State var client: Client
    @ObservedObject var clientData = ClientData()
    @Binding var isPresented: Bool
    @State private var title = ""
    @State private var startDate = Date()
    @State private var endDate = Date()

    var body: some View {
        NavigationView {
            Form {
                TextField("Work title", text: $title)
                DatePicker("Start date", selection: $startDate)
                    .environment(\.locale, Locale(identifier: "sv-SE"))
                DatePicker("End date", selection: $endDate)
                    .environment(\.locale, Locale(identifier: "sv-SE"))

                Button(action: {
                    let work = Work(title: self.title, startDate: self.startDate, endDate: self.endDate)

                    self.clientData.addWork(for: self.client, work: work)
                    self.isPresented = false
                }) {
                    Text("Add work")
                }
            }
            .navigationBarTitle("Add work")
            .navigationBarItems(trailing: Button(action: {
                self.isPresented = false
            }) {
                Text("Cancel")
            })
        }
    }

}

EDIT:
The code I have for adding clients is similar and that code makes the Added client appear directly. Here is the code for adding clients:
struct ContentView: View {
    @ObservedObject var clientData = ClientData()
    @State private var showingAddClient = false
    @State private var showingAddWork = false

    var body: some View {
        NavigationView {
            List {
                ForEach(clientData.clients) { client in
                    NavigationLink(destination: WorkListView(client: client, clientData: self.clientData)) {
                        VStack(alignment: .leading) {
                            Text(client.name)
                                .font(.headline)
                            Text(client.company)
                                .foregroundColor(.secondary)
                        }
                    }
                }
                .onDelete { indices in
                    indices.forEach { self.clientData.clients.remove(at: $0) }
                }
            }
            .navigationBarTitle("Clients")
            .navigationBarItems(leading: EditButton(), trailing: Button(action: {
                self.showingAddClient.toggle()
            }) {
                Image(systemName: "plus")
            })
            .sheet(isPresented: $showingAddClient) {
                AddClientView(clientData: self.clientData, isPresented: self.$showingAddClient)
            }
        }
    }
}

struct AddClientView: View {
    @ObservedObject var clientData = ClientData()
    @Binding var isPresented: Bool
    @State private var name = ""
    @State private var company = ""
    @State private var eMail = ""
    @State private var phone = ""
    @State private var price = ""
    @State private var additionalInfo = ""

    var body: some View {
        NavigationView {
            Form {
                TextField("Client name", text: $name)
                    .autocorrectionDisabled(true)
                TextField("Comapny", text: $company)
                    .autocorrectionDisabled(true)
                TextField("E-mail", text: $eMail)
                    .keyboardType(.emailAddress)
                TextField("Phone", text: $phone)
                    .keyboardType(.numberPad)
                TextField("Price", text: $price)
                    .keyboardType(.numberPad)
                Button(action: {
                    let client = Client(name: self.name, company: self.company, eMail: self.eMail, phone: self.phone, price: self.price)

                    do {
                        try self.clientData.addClient(client)
                        self.isPresented = false
                    } catch {
                        // Handle the error
                    }
                }) {
                    Text("Add client")
                }
            }
            .navigationBarTitle("Add client")
            .navigationBarItems(trailing: Button(action: {
                self.isPresented = false
            }) {
                Text("Cancel")
            })

        }
    }
}

Here is the Client Class code:
class Client: ObservableObject, Codable, Hashable, Identifiable, Equatable {
    var id = UUID()
    @Published var name: String
    @Published var company: String
    @Published  var eMail: String
    @Published  var phone: String
    @Published  var price: String
    @Published  var work: [Work]

    init(name: String, company: String, eMail: String, phone: String, price: String) {
        self.name = name
        self.company = company
        self.eMail = eMail
        self.phone = phone
        self.price = price
        self.work = []
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        company = try container.decode(String.self, forKey: .company)
        eMail = try container.decode(String.self, forKey: .eMail)
        phone = try container.decode(String.self, forKey: .phone)
        price = try container.decode(String.self, forKey: .price)
        work = try container.decode([Work].self, forKey: .work)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        try container.encode(company, forKey: .company)
        try container.encode(eMail, forKey: .eMail)
        try container.encode(phone, forKey: .phone)
        try container.encode(price, forKey: .price)
        try container.encode(work, forKey: .work)
    }

    enum CodingKeys: String, CodingKey {
        case name
        case company
        case eMail
        case phone
        case price
        case work
    }

    static func == (lhs: Client, rhs: Client) -> Bool {
        return lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

What am I missing here?

A: Here is a minimal reproducible example of your problem:
ContentView
struct ContentView: View {
    @ObservedObject var clientData = ClientData()
    var body: some View {
        NavigationView {
            List {
                ForEach(clientData.clients) { client in
                    NavigationLink(destination: WorkListView(client: `client, clientData: clientData)) {`
                            Text(client.name)
                        }
                    }
                }
            }
        }
    }

WorkListView
struct WorkListView: View {
    @State var client: Client
    @ObservedObject var clientData = ClientData()
    @State private var showSheet = false
    var body: some View {
        List {
    Section {
        Text(client.name)
    }
    Section(header: Text("Performed Work")) {
        ForEach(client.work.indices) { work in
            VStack  {
                Text(client.work[work].content)
            }
        }
    }
        }
        .onTapGesture {
            showSheet.toggle()
        }
        .sheet(isPresented: $showSheet, content: {
            AddWorkView(client: client, showSheet: $showSheet)
        })
        .padding()
    }
}

AddWorkView
struct AddWorkView: View {
    var work = Work()
    @State var client: Client
    @ObservedObject var clientData = ClientData()
    @Binding var showSheet: Bool
    var body: some View {
        Form {
            Text(work.content)
            Button("Add") {
                clientData.addWork(for: client, work: work)
                showSheet = false
            }
        }
    }
}

ClientData
class ClientData: ObservableObject {
    let clients = [Client(), Client()]

    func addWork(for client: Client, work: Work) {
        client.work.append(work)
    }
}

Client
class Client: ObservableObject,
                            Identifiable {
    let name = "Foo"
    @Published var work: [Work]

    init() {
        self.work = []
    }

    func addWork(_ work: Work) {
        self.work.append(work)
    }
}

Work
struct Work: Identifiable {
    var id = UUID()

    let content = "Bar"
}

To fix the problem you are having
The problem that you've got is that when we want to share a property between multiple views, as here, we must instantiate it as a StateObject rather than just reference it's state.
So, in WorkListView replace
@State var client: Client

with
@StateObject var client: Client

Then rather than using ForEach to iterate over the indices of the client work array as so
ForEach(client.work.indices) { work in
    Text(client.work[work].content
}

instead bind use it to iterate over the elements of the collection
ForEach(client.work) { work in
    Text(work.content)
}

A few extra points to note:

*

*If you are dependency injecting a reference to a class into a subview you do not need to also instantiate the same class in the subview.

*Please look at @EnvironmentalObject property wrapper, or delegate pattern to look at how to pass reference to objects between views.

*Try and work out which property wrapper gives you the behaviour that you need and only use that. There are lots of extraneous @State and duplications in your code.

A: Please pass down the client data as a binding to the detail view.
struct AddWorkView: View {
    @Binding var clientData : ClientData
}

Not sure what you are doing in client, but if you use Core Data please check out @FetchRequest, as it does all the heavy lifting for you. It's similar to NSFetchedResultsController.
Could look like this for your client setup:
@FetchRequest(entity: Client.entity(), sortDescriptors: []) var locations : FetchedResults<Client>


text:
Q: Check if product prices includes tax in Woocommerce 3+ How can you programmatically check if a product's price includes tax? I checked the WC_Product reference, but couldn't find anything like that.

A: You will simply use the dedicated conditional function wc_prices_include_tax() in an IF statement:
if( wc_prices_include_tax() ) {
    // Price include tax
} else {
    // Price doesn't include tax
}

It will check if taxes are enabled in Woocommerce and if your product prices general setting are including tax or not.

For example wc_prices_include_tax() is used by  wc_get_price_including_tax() a WC_Product price function (not a method),
used herself in wc_get_price_to_display() price function when products prices need to be displayed including taxes in product pages…
If product prices need to be displayed excluding taxes in product pages, wc_get_price_to_display() will use wc_get_price_excluding_tax()

wc_get_price_to_display(), wc_get_price_including_tax() and wc_get_price_excluding_tax() have 2 arguments:
• $product (mandatory) the WC_Product object
  • $args (optional) an array containing the product price and the quantity

Related: Display Woocommerce product price with and without tax and tax amount

On Cart, Checkout and Orders there is another general setting that allow you to display prices with or without taxes. You can use the following to check if prices are displayed with or without taxes:
if( get_option( 'woocommerce_tax_display_cart' ) ) {
    // Prices displayed including tax
}

Order items related:

*

*Get tax rate used in an order for one product and for shipping in WooCommerce

*Get Order items and WC_Order_Item_Product in Woocommerce 3

*Get some order and order items data in Woocommerce emails

A: Well product will not tell you if someone paid sales tax. For that you need something involving an order.
Something that has orders and products, something like this class:
WC_Order_Item_Product

For reference
https://docs.woocommerce.com/wc-apidocs/source-class-WC_Order_Item_Product.html#262-270
This has at least 3 relevant methods:
//Get subtotal tax.
WC_Order_Item_Product::get_subtotal_tax();

//Get total tax.
WC_Order_Item_Product::get_total_tax();

Get taxes.
WC_Order_Item_Product::get_taxes();

Note these are not "static" I just like the way it looks, and it's common on the PHP document page to do it this way :-p
Now how you get there from where you are, I don't know. Meaning how you get one of these mystical WC_Order_Item_Product objects.
Good Luck!


text:
Q: How to run a project without dotenv? I've created a Node.js/Express.js that manipulates a Mongo database through a connection to MongoDB Atlas. The thing is that the login to MongoDB Atlas info is stored in a .env file, which must not be uploaded to GitHub. So how will anyone trying to run my project do it without the data inside .env` ? I downloaded the project and tried to run it, but the app complains about the lack of the login to MongoDB Atlas info. The project is for a test to get a job in a company, so they will probably need to manipulate the database to evaluate my code. Should I give them the login info ?

A: You should never share your credentials.
The common practice is to share a "dummy" .env file with dummy credentials and instructions on how to edit it to point to a local database the user sets up.
If you want to go the extra mile, you could create a docker-compose file that sets up your application with a local mongodb container, and have the default credentials in .env reference it.

A: Make an .env.sample
Add ENV Vars there but leave them empty, so they can add their own


text:
Q: android:gravity does not align as it should I have some code that should center a text in button, but the text is not aligned exactly in the middle. It is located a little at the bottom. How I could fix this?
</style>
    <style name="ButtonText">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">34dp</item>
    <item name="android:layout_weight">0.5</item>
    <item name="android:textColor">#ffffff</item>
    <item name="android:gravity">center</item>
    <item name="android:layout_margin">3dp</item>
    <item name="android:padding">1dp</item>
    <item name="android:textSize">26sp</item>
    <item name="android:textStyle">bold</item>
</style>

        <Button
        android:id="@+id/buttonStop"
        android:background="@drawable/greenbutton"
        style="@style/ButtonText"
        android:text="@string/ButtonStop" />

A: This is normal. Text generally has top/bottom padding that isn't even. It's used for ascender/descender area.
If you need pixel-perfect centering, you can try telling it not to include the font padding with:
android:includeFontPadding="false"

A: I guess must be contradict in your style. Change your padding and layout_height attributes to following.
<item name="android:layout_height">wrap_content</item>
<item name="android:paddingTop">4dp</item>
<item name="android:paddingBottom">4dp</item>


text:
Q: Apache beam JOIN using java- extensions library (beam-sdks-java-extensions-join-library) I am using the below code for join data in the apache beam in java and the beam version is 2.19. (without CoGroupByKey). But I am getting NullPointerException.
Any Idea what I am doing wrong here. Below is the code.
public class InnerJoinExample {

    public static void main(String[] args) {

        Pipeline p = Pipeline.create();

        Schema left = Schema.builder().addStringField("a1")
                    .addStringField("a2")
                    .build();

            Row row1 =
                    Row
                      .withSchema(left)
                      .addValues("key1", "5")
                      .build();

            PCollection<Row> leftPCollection = p.apply(Create.of(row1)).setRowSchema(left);

            Schema right = Schema.builder().addStringField("b1")
                    .addStringField("b2")
                    .build();

            Row row2 =
                    Row
                      .withSchema(right)
                      .addValues("key1", "15")
                      .build();

            PCollection<Row> rightCollection = p.apply(Create.of(row2)).setRowSchema(right);

            PCollection<Row> joined = leftPCollection.apply(Join.innerJoin(rightCollection));

            p.run();
    }
}


text:
Q: App force closing while trying to integrate Stripe I am trying to integrate Stripe to process payment in my Android application.
I have the user input credit card information and then all I'm trying to do for now is create a token.  But when I click the button the app force closes.
This is not how the final app will accept cards and work with Stripe but I'm just trying to get an understanding how I will integrate Stripe in the future
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.stripe.android.*;
import com.stripe.android.model.Card;
import com.stripe.android.model.Token;
import com.stripe.android.Stripe;

import java.util.HashMap;
import java.util.Map;

public class newUser extends AppCompatActivity {

String fname;
String lname;
String email;
String phonenum;
String pin;
String cardNumber;
String cardCVC;
Integer cardExpMonth;
Integer cardExpYear;
String stripetok;
Card cardNew;

private static final String PUBLISHABLE_KEY = "pk_test_iUVdhdvJuurqSxIlXpzq32LS";
UserDBHelper newUserr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_user);

    newUserr = new UserDBHelper(newUser.this);

    EditText fNameh = (EditText) findViewById(R.id.fNameNew);
    EditText lNameh = (EditText) findViewById(R.id.lNameNew);
    EditText emailh = (EditText) findViewById(R.id.emailNew);
    EditText phoneNumh = (EditText) findViewById(R.id.phoneNew);
    EditText pinh = (EditText) findViewById(R.id.pinNew);
    EditText cardNumberh = (EditText) findViewById(R.id.cardNumNew);
    EditText cardCVCh = (EditText) findViewById(R.id.cvcNew);
    Spinner cardExpMonthh = (Spinner) findViewById(R.id.monthNew);
    Spinner cardExpYearh = (Spinner) findViewById(R.id.yearNew);

    fname = fNameh.getText().toString();
    lname = lNameh.getText().toString();
    email = emailh.getText().toString();
    phonenum = phoneNumh.getText().toString();
    pin = pinh.getText().toString();
    cardNumber = cardNumberh.getText().toString();
    cardCVC = cardCVCh.getText().toString();
    cardExpMonth = (Integer) cardExpMonthh.getSelectedItem();
    cardExpYear = (Integer) cardExpYearh.getSelectedItem();

    cardNew = new Card(
            cardNumber,
            cardExpMonth,
            cardExpYear,
            cardCVC
    );

    ImageButton createNewUser = (ImageButton) findViewById(R.id.createNew);

    createNewUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            if(cardNew.validateCard() & cardNew.validateCVC()) {
                Stripe stripe = new Stripe();
                stripe.createToken(cardNew, PUBLISHABLE_KEY, new TokenCallback() {
                    public void onSuccess(Token token) {
                        // TODO: Send Token information to your backend to initiate a charge
                        Toast.makeText(
                                getApplicationContext(),
                                "Token created: " + token.getId(),
                                Toast.LENGTH_LONG).show();
                    }

                    public void onError(Exception error) {
                        Log.d("Stripe", error.getLocalizedMessage());
                    }
                });

            }

            else{
                Toast.makeText(
                        getApplicationContext(),
                        "Token not made!",
                        Toast.LENGTH_LONG).show();
            }

        }
    });

Any ideas on why this is occuring?  I am not getting any errors but the activity won't even load.
I have included
compile 'com.stripe:stripe-android:2.0.2'

into the app's build.gradle under dependencies
Thanks for any input!
Edit 1:
I believe the issue may be when I'm casting a String to an Integer from the spinner.
E/dalvikvm: Could not find class 'android.widget.ThemedSpinnerAdapter', referenced from method android.support.v7.widget.AppCompatSpinner$DropDownAdapter.<init>
W/dalvikvm: VFY: unable to resolve instanceof 2583 (Landroid/widget/ThemedSpinnerAdapter;) in Landroid/support/v7/widget/AppCompatSpinner$DropDownAdapter;
D/dalvikvm: VFY: replacing opcode 0x20 at 0x0016
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x416fcbc0)
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.zeuspwr.zeuspower, PID: 32121
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zeuspwr.zeuspower/com.zeuspwr.zeuspower.newUser}: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
                      at android.app.ActivityThread.access$800(ActivityThread.java:166)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:136)
                      at android.app.ActivityThread.main(ActivityThread.java:5584)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
                      at com.zeuspwr.zeuspower.newUser.onCreate(newUser.java:62)
                      at android.app.Activity.performCreate(Activity.java:5447)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
                      at android.app.ActivityThread.access$800(ActivityThread.java:166)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:136)
                      at android.app.ActivityThread.main(ActivityThread.java:5584)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
                      at dalvik.system.NativeStart.main(Native Method)
I/Process: Sending signal. PID: 32121 SIG: 9
Application terminated.

A: Change
cardExpMonth = (Integer) cardExpMonthh.getSelectedItem();
cardExpYear = (Integer) cardExpYearh.getSelectedItem();

To
cardExpMonth = Integer.valueOf(cardExpMonthh.getSelectedItem());
cardExpYear = Integer.valueOf(cardExpYearh.getSelectedItem());


text:
Q: How can I tell if a USB WiFi dongle is working? I am trying to get a generic 802.11N USB WiFi dongle to work in a MacBook Pro running Sierra which allegedly has a dodgy WiFi chip (though it works most of the time), to help out a friend.
It shows up in System Information as a USB device by MediaTek (no model or more information just "802.11 n WLAN" device name. Some sort of Ralink software was already installed by the owner...but he says it's not working.
However I have no idea how to tell which WiFi device is actually being used. How can I determine this - is there a way to turn of the onboard WiFi specifically or see which device is being used?

A: Yes, you can turn off the native wifi on mac OS.

*

*Click on the Apple logo (top left)

*Select Network

*Pick your native wifi from the left device options

*Click on the Turn Wi-Fi Off button on the right side

You're done!

A: An alternate way to test your dongle is, if you use ifconfig, you can list all your network interfaces. Find the interface you're interested in and then you can run traceroute -i YOUR_INTERFACE SOME_IP_ADDRESS where YOUR_INTERFACE is the interface you want to test and SOME_IP_ADDRESS is your gateway IP address, a public Internet address, or any other IP you want to see if you can reach via the wifi adapter.


text:
Q: A proper closing expression for informal email What is an expression that you can use at the end of an informal email, when you forgot something and want to add it to the email after your signature?

A: You can use either P.S. or N.B. For informal articles, P.S. is the apt choice.
P.S. being post scriptum, and N.B. (nota bene) if it is something important you want to draw the reader's attention to.
Source : http://en.wikipedia.org/wiki/Nota_bene
http://en.wikipedia.org/wiki/Post_script
P.S. : In case of an email, the text can be altered, even if you forget to write something.
And if you have already sent it, then you will have to send a mail again, including the matter you wanted to write.

A: By the way I forgot to add that...
Forgot to mention that...
.... is perfect for informal emails.


text:
Q: How to pass JavaScript object to another function? I am downloading csv file from AWS S3 bucket so that I can use it in D3.
No problem downloading the csv file. In code below the console.log(data.Body.toString()) prints out the csv file contents in expected format
However, I am not sure how to pass the downloaded csv file content to D3 in code below.
The file contents are already in nice csv file format.
Question: how to replace merged.csv below with the mergedcsv object?
<script type="text/javascript">

var bucket = new AWS.S3();

bucket.getObject({
    Bucket: 's3-google-analytics',
    Key: 'merged.csv'
},
    function awsDataFile(error, data) {
        if (error) {
            return console.log(error);
        }
        mergedcsv = data.Body.toString();
        console.log(data.Body.toString());
    }
);

// how to replace the "merged.csv" below with the mergedcsv object above?

d3.csv("merged.csv", function(data) {
    var parseDate = d3.time.format("%Y%m%d").parse;
    var counter = 0;
    data.forEach(function(d) {
        etc
    });
});

</script>

updated to add sample of mergedcsv content eg output of console.log(mergedcsv); or console.log(data.Body.toString()); :
yyyymm,date,hostname,source,PPCC,in30days,sessionDuration,users,sessions,newUsers,twitterSessions,bounceRate,sessionsPerUser
201203,20120330,journal,google,PPCC,>30days,26.25,4,4,4,0,75.0,1.0
201203,20120331,journal,(direct),PPCC,>30days,0.0,3,3,3,0,100.0,1.0
201203,20120331,journal,bing,PPCC,>30days,0.0,1,1,1,0,100.0,1.0

A: After reading a the docs on d3.csv, it loads a CSV file from a URL, but in your example, you've already loaded the data, you just need to parse it. So d3.csv isn't going to be of any use.
It looks like the D3 function for parsing is d3.csv.parse(data) which will return an array of parsed data. (Docs are here)
So you could do something like…
var bucket = new AWS.S3();
var mergedcsv;

bucket.getObject({
    Bucket: 's3-google-analytics',
    Key: 'merged.csv'
},
    function awsDataFile(error, data) {
        if (error) {
            return console.log(error);
        }
        mergedcsv = d3.csv.parse(data.Body.toString());

        // now mergedcsv will be an array, so you can do whatever you were going to do with it before, i.e...
        var parseDate = d3.time.format("%Y%m%d").parse;
        var counter = 0;
        data.forEach(function(d) {
           etc
        });
    }
);


text:
Q: How to minimize/fix the firefox browser window with selenium 2.0 standalone and in a perl script I use selenium-server-standalone-2.41.0.jar as selenium server and perl script (with Test::WWW::Selenium) to do tests. Then selenium test starts and Firefox windows are opening. I'd like to reduce then to the smallest window as possible.
I'm starting selenium by using the following command:
java -jar selenium-server-standalone-2.41.0.jar -firefoxProfileTemplate ./selenium.ff.profil

and try to change the size in the profile with addons, but it doesn't work. The windows are resized.
Any idea how to fix the Firefox window size or reduce it with perl ?


text:
Q: Transfer DateTime to .NET WebAPI I would like simply get Android current time and pass to .NET WebAPI. That is it. But there are many approaches...
I tried this one
Android side
String TimeOfRequest =  Long.toString(new Date().getTime());

.NET side
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
t = epoch.AddMilliseconds(Convert.ToInt64(locationItem.TimeOfRequest));

But it gives this result

0001-01-02 18:01:34.0366112

Please suggest about simplest approach to do it.

A: Try this:
private String formatDate(long milliseconds) /* This is your topStory.getTime()*1000 */ {
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliseconds);
    TimeZone tz = TimeZone.getDefault();
    sdf.setTimeZone(tz);
    return sdf.format(calendar.getTime());
}

A: As mentioned, assume your API is correct, meaning you passing string from Android mobile to ASP.net API correctly.
String TimeOfRequest =  Long.toString(new Date().getTime());
//TimeOfRequest = "1512977867949" // For example

In your API:
// For example locationItem.TimeOfRequest = "1512977867949";
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var t= epoch.AddMilliseconds(Convert.ToInt64(locationItem.TimeOfRequest));

Console.WriteLine(t.ToString("MM/dd/yyyy HH:mm:ss")); // print "12/11/2017 07:37:47"
Console.WriteLine(t.GetType().ToString()); // print "System.DateTime"