text:
Q: pass a json result of a mysql query as a param to my ejs in Node/express I have a query to get all my users. I have been doing res.json(rows) to display to screen until now. Now I want to pass the object obtain from the query to a ejs file and display it. If I do like my code below, the object pass is a string and I can´t iterate or obtain the fields.
What is the best way to achive what I´m trying to do?
router.get("/users", (req, res) => {
    const connection = getConnection();
    const newLocal = "SELECT * FROM client";
    connection.query(newLocal,(err, rows, fields) => {
        if (err) {
            console.log("Error "+err);
            res.sendStatus(500);
            return;
        }
        // res.json(rows);
        res.render("users.ejs", {users: JSON.stringify(rows)});
    });
});

A: It's because you're turning your Array rows into a String. Remove JSON.stringify


text:
Q: Unable to use scp for file uploads in perl for secondary ethernet interface Hi I'm trying to use SCP to upload the files to the remote server through a perl code.
The server on which the code is being run have multiple ethernet interface(eth0,eth1,eth2)
eth0 is the default interface.
The server to which I'm trying to upload the files can only be reached by eth2 interface.
Is there something which I need to modify in the code to use that particular interface for the uploads.(eth2)
I'm using:
use Expect; #for scp

A: You can't. Routing doesn't work in 'user space' it's handled by the kernel. There is nothing you can do with a perl script that will deal with that.
You need to look at your routing table, or how to configure your network interfaces on appropriate subnets.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Collector current in a BJT transistor whose base and emitter are forward biased I'm reading a book about electronics and I have a doubt about a NAND gate implemented with Transistor-Transistor Logic. The question I have is actually about BJT transistors specifically (not the gate itself). I thought I understood how BJTs work, however, in my book, there is a new type of connection I don't understand very well, let me explain:
The NAND implementation the book provides is the following:

Now, my question is about Q1. Quoting the book:

[...] If both A and B are high, Q1 has no emitter current; however, its base-collector junction is forward biased, supplying base current to Q2. [...]

My understanding is that, if A and B are high, the voltage between them is 0, therefore the BJT is opened, so no current flows from its colletor to its emitter. However, the book states that the Q2 base receives current. That is what I don't understand.
Does this mean that the voltage in the Q1 base drives current to the Q2 base as well? If so, does this work the same way (but with voltages) with MOSFETs?
Here (BJT regions of operation), the BJT regions of operation can be seen. However, there is no region for B = E > C. What region of operation in the above table is supposed to describe this one?

A: By floating A and B, the base current can only go out the collector,
and
into the NPN with grounded emitter.

A: The base of Q1 will be at ~3 diode drops above ground (Q1 + Q2 + Q4), ie about 2V.
With the emitters at > 2.4V (TTL High) there will be some current flowing in from the emitters due to Q1's inverse beta. This is controlled by device processing to be small < 40uA worst case.
All of the base current plus the small emitter currents will flow into Q2.

A: When A and B are both held high Q1 is in reverse active mode. In this mode conventional current flows into the emitter and out of the collector. The disadvantage of this mode of operation is that the transistor's hFE is much smaller than when in forward active mode.

A:
Does this mean that the voltage in the Q1 base drives current to the
Q2 base as well? If so, does this work the same way (but with
voltages) with MOSFETs?

Don't know what you mean by Q1 voltage driving current to Q2 base. Q2's base current is common with current through Q1's base-collector diode junction, and through 4K pull-up as well. With no emitter current(s), Q1 is simply a base-to-collector forward-biased diode. The characteristic curves that might be included in a transistor data sheet don't address this biasing arrangement...more concerned with active-region transistor operation.
Logic threshold voltage for TTL is in the 1.2V to 1.3V ballpark. Consider the situation when A & B are logic high. Q2 is a bipolar switch that is saturated "ON". If you simplify transistor "ON" base-emitter voltage as 0.6V, then Q2 base is around +1.2V... because Q2 is switched "ON" and Q4 is saturated "ON" as well.
If Q2 base is 1.2V, so is Q1 collector. Q1 base is 0.6V higher, at 1.8V. If DC supply is +5V, then Q1 base current is \$ (5-1.8)\over{4000}\$ = 0.8mA. All this base current flows through 4k, and through Q1 base-emitter junction, into Q2 base. That's enough current to saturate Q2 fully "ON"...Q2 collector-to-emitter voltage clamps to a fraction of a volt. Q2 collector-to-emitter current is established by 1600 ohm resistor...around 2mA or a bit more.
Only when input A or input B falls below the 1.2V threshold does Q1 start acting as a transistor, when its base-emitter becomes forward biased. Q1 collector then pulls Q2's base toward ground, releasing it from its "ON" state, and pulling it out of saturation.

About MOSfets:
I suppose you could re-arrange a TTL input stage to use MOSfets. Getting MOSfet threshold voltage to be "TTL-compatible" would be a problem.  MOSfets might pull Q2 base up, or allow "Rpulldown" to pull Q2 base down to ground to switch the NAND gate output to "high" state. Or MOSfets might replace Q1, Q2 entirely. A strange brew - not practical.

simulate this circuit – Schematic created using CircuitLab


text:
Q: How often to check for license? My main activity is basically useless without another activity (act2). act2 can be accessed from a button in the main activity. It is also available through a home screen widget, which when clicked calls my main activity and immediately calls act2.
Right now, I have it set to check license anytime the function that handles the button click is called. This covers the button press in the main activity as well as if you come from the widget.
My question is, is this too often? Is getting a cache response anymore draining than checking a variable for example?
I have tried putting it on onCreate but when it says it's not licensed, you can just close the application and open it again and it will not run through onCreate again.

A: Here I assume you've read all the licensing documentation, and that you're using the SDK. You said nothing, so I'm going for the "defaults". There are a few clues on the Android developers blog as well as on the Internet.
I asked myself the same question last year. Or at least something similar. So let's go one step at a time:

My question is, is this too often? Is
  getting a cache response anymore
  draining than checking a variable for
  example?

I would say that the difference is going to be "imperceptible" to "not much". First of all, the validity timestamp (VT field from extras) is stored locally, properly encrypted/obfuscated. I'm assuming you're using the ServerManagedPolicy policy, since you said nothing about it.
Depending on the kind of the app, we should notice that you may be even writing things on onPause, for example (checking for changes if applicable, of course). So, I wouldn't worry about it.
But because there is no perceptible harm does not mean you should do something. That's why I disagree with what Kerin posted:

I'm sure you'll stop loads of piracy and you aren't wasting your time at all.

More on that later. For now I say that you shouldn't need to do lots of checkings. That's what the policies are for. They handle it probably better than you and me. Anything else is indeed a waste. Personally, I only do checkings on onCreate (obviously), and also in one more situation rarely used (but very important on the app usefulness).
What you should do, however, and I say because nobody said here yet, is properly obfuscate and change the LVL library, as well as your own code side (the checkerCallbacks). Here, I changed a lot of things on the LVL library, including some simple single key cryptography (weak), and also changed how the interfaces are implemented, and how arguments are passed, and so on. Basically, I created my own LVL after posting that question here on SO.
On the opposite of what you're doing, I also customized the VT field in order to mandate a minimum time for the validity of the cached response. That's why my app is to be used in the wild, where net access is not always available. Those subtle details depend on your app, what it does, how it does, where people would be using them.
If you're a developer, it's easy to forget about the user. There is nothing worse than a legitimate user being denied access to an app he bought. So far, I didn't have problems (I check usage statistics and compare to my account), but I believe games have more trouble (it's typical of that field).
So, returning to my constructive (please, we are all trying to learn here, myself included) critic about Kerin's post, I would say that even LVL itself is not enough to "stop loads of piracy".
If you know anything about how Android works, you'd know that the apks can be easily decrypted to source code, just use dex2jar and jdgui (Google them). In fact, I always decrypt my apps before publishing to check if everything is working the way it should. And take into account that I never did computer college, I just happened to learn java and Android to create my own app that I needed and was unavailable for Android (a tide app for my country). I'm sure there are hackers and techies much smarter out there that can do even more.
People start thinking that LVL will stop piracy, and then learn the ugly truth and be disappointed. That's not what the LVL is for. Just look at the code... it was made to avoid "automated" piracy. It is to force someone to personally look into the code, see how it works, and then "switch" the proper flags, if he can make sense of them. But then again, if you use proguard, it will make the task horrible, exhaustive (believe me, that's why I use dex2jar + jdgui myself).
If your app is being sold for $1 or even around $5 or more, it will make this trouble not worth it. That's my stance on the LVL. Obviously, if you have an niche app that costs $100, for example, you probably can do it properly, server side, with public keys. But I feel that it's not the case here.
Anyway, just my 2 cents.

A: You can check for the license for the first time, then cache it. The next time when your app runs, read the license from the cache, and also start a Thread that gets the license from your server. If the license that you got from the server is now invalid. You can pop up a dialog box to tell the user that the license is invalid, remove the cached license, and quit the app.


text:
Q: How can I make the "back button" appear, for a subview? I am new to ionic, and what causes me most difficulty is the subject of navigation.
I have two tabs called "Dashboard" and "friends". I would like that when I click on the dashboard button, I can navigate to the subview that is called "subview_dash", but I do not want the tabs to be shown in this view. My problem is that I know how to navigate to this view, but I can not make the return button appear in "subview_dash".

How can I do it? I would appreciate it too.
.state('tab', {
    url: "/tab",
    abstract: true,
    templateUrl: "tabs.html"
  })

  // Each tab has its own nav history stack:

  .state('tab.dash', {
    url: '/dash',
    views: {
      'tab-dash': {
        templateUrl: 'tab-dash.html',
        controller: 'DashCtrl'
      }
    }
  })

  .state('tab.friends', {
    url: '/friends',
    views: {
      'tab-friends': {
        templateUrl: 'tab-friends.html',
        controller: 'DashCtrl'
      }
    }
  })

  .state('subview_dash', {
    url: '/subview_dash',
        templateUrl: 'tab-subview_dash.html',
        controller: 'DashCtrl'

  })

This is my code:
http://plnkr.co/edit/Az3w9O8rkr7fJw4unIDz?p=preview

A: You use this code in tab-subview_dash.html
<ion-view title="subview_dash">
    <ion-nav-buttons side="left">
      <button class="button button-clear ion-arrow-left-c" ng-click="backButton()"></button>
    </ion-nav-buttons>
    <ion-content class="has-header">
       friends
    </ion-content>
</ion-view>

and write your function for backButton() give path where you want to redirect


text:
Q: Magento Ajax from Module I am new to magento module development. I want  to request ajax call from magento backend.. Here I made module... Here is the screenshot

I have fields like this:
<tpropay translate="label" module="tpropay">
                Tpro3
                <sort_order>670</sort_order>
                <show_in_default>1</show_in_default>
                <show_in_website>1</show_in_website>
                <show_in_store>0</show_in_store>
                <comment><![CDATA[
                <button class="scalable" onclick="return check(); ">Sync Products Now</button>  ]]></comment>

<fields>
 <active translate="label">
   Enabled
   <frontend_type>select</frontend_type>
   <source_model>adminhtml/system_config_source_yesno</source_model>
   <sort_order>1</sort_order>
   <show_in_default>1</show_in_default>
   <show_in_website>1</show_in_website>
   <show_in_store>0</show_in_store>
 </active>
</fields>
</tpropay>

Now I want ajax call when user click on button? Confused about how to include javascript and send ajax call... Any help would be appreciated

A: Create your controller, to which you are going to call ajax then put your JavaScript in a file and add that js file by layout xml like below
<adminhtml_system_config_edit>
        <reference name="head">
            <action method="addJs"></action>
        </reference>
</adminhtml_system_config_edit>
Hope that helps


text:
Q: Multiple NICs on a same subnet Although there are several articles discussing about the issue, I need some advice because I am still facing the problem.
I have 3 interfaces on a virtual machine (cents 6.6)
[root@localhost network-scripts]# ip addr list
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN_
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host_
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:bf:6e:7b brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.140/24 brd 192.168.1.255 scope global eth0
    inet6 fe80::20c:29ff:febf:6e7b/64 scope link_
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:bf:6e:85 brd ff:ff:ff:ff:ff:ff
    inet 172.16.64.7/24 brd 172.16.64.255 scope global eth1
    inet6 fe80::20c:29ff:febf:6e85/64 scope link_
       valid_lft forever preferred_lft forever
4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:bf:6e:8f brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.151/24 brd 192.168.1.255 scope global eth2
    inet6 fe80::20c:29ff:febf:6e8f/64 scope link_
       valid_lft forever preferred_lft forever

eth1 is used for management line.
I want to assign 192.168.1.140 and 192.168.1.150 to eth0 and eth2 respectively.
Since both eth0 and eth2 participate on a same subnet, I configured policy-based routing.
[root@localhost /]# cat /etc/sysconfig/network-scripts/route-eth0
192.168.1.0/24 dev eth0 src 192.168.1.140 table eth0
default via 192.168.1.1 dev eth0 table eth0

[root@localhost /]# cat /etc/sysconfig/network-scripts/route-eth2
192.168.1.0/24 dev eth2 src 192.168.1.151 table eth2
default via 192.168.1.1 dev eth2 table eth2

[root@localhost /]# cat /etc/sysconfig/network-scripts/rule-eth0
from 192.168.1.140 table eth0 priority 1000

[root@localhost /]# cat /etc/sysconfig/network-scripts/rule-eth2
from 192.168.1.151 table eth2 priority 1001

Then I setup the following parameter in /etc/sysctl.conf
net.ipv4.conf.all.arp_filter = 1
net.ipv4.conf.default.rp_filter = 0

Restarted the virtual machine in order to activate the changes in the kernel parameter and network configuration. The result in the routing table is the following.
[root@localhost /]# ip rule show
0:      from all lookup local
1000:   from 192.168.1.140 lookup eth0
1001:   from 192.168.1.151 lookup eth2
32766:  from all lookup main
32767:  from all lookup default

[root@localhost /]# ip route show table eth0
192.168.1.0/24 dev eth0  scope link  src 192.168.1.140
default via 192.168.1.1 dev eth0

[root@localhost /]# ip route show table eth2
192.168.1.0/24 dev eth2  scope link  src 192.168.1.151
default via 192.168.1.1 dev eth2

The configuration looked fine but it is somehow impossible to ping to the Internet.
[root@localhost /]# ping -c 1 -I eth0 8.8.8.8_
PING 8.8.8.8 (8.8.8.8) from 192.168.1.140 eth0: 56(84) bytes of data.
From 192.168.1.140 icmp_seq=1 Destination Host Unreachable

--- 8.8.8.8 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 3001ms

[root@localhost /]# ping -c 1 -I eth2 8.8.8.8
PING 8.8.8.8 (8.8.8.8) from 192.168.1.151 eth2: 56(84) bytes of data.
From 192.168.1.151 icmp_seq=1 Destination Host Unreachable

--- 8.8.8.8 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 3003ms

Any ideas?


text:
Q: Display hoverlabel before value I have a dataframe (x,y,z), i want to plot:

*

*x vs y,

*display z value as hovertext, with label 'z'.

I can get it to display z value but would like to add a label 'z: ' before the value to clarify what it is.
This is the code so far
import plotly.graph_objects as go

df=pd.DataFrame({'x':[0, 1, 2, 3, 4, 5, 6, 7, 8],
                 'y':[0, 11, 31, 21, 41, 31, 41, 61, 51],
                 'z':[0,2,4,6,7,8,9,10,12] })

fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(go.Scatter(
   x=df['x'],
   y=df['y'],
   hovertext=df['z'] #displays hover value
   #somehting like: hoverlabel='Z :'
))

A: You can use the hovertemplate argument:
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Scatter(
   x=df['x'],
   y=df['y'],
   hovertext=df['z'],
   hovertemplate = 'Z: %{hovertext}'
))

See more here: https://plotly.com/python/hover-text-and-formatting/#customizing-hover-text-with-a-hovertemplate


text:
Q: Plotting multiple density curves on the same plot: weighting the subset categories in Python 3 I am trying to recreate this density plot in python 3: math.stackexchange.com/questions/845424/the-expected-outcome-of-a-random-game-of-chess
End Goal: I need my density plot to look like this
The area under the blue curve is equal to that of the red, green, and purple curves combined because the different outcomes (Draw, Black wins, and White wins) are the subset of the total (All).
How do I have python realize and plot this accordingly?
Here is the .csv file of results_df after 1000 simulations pastebin.com/YDVMx2DL
from matplotlib import pyplot as plt
import seaborn as sns

black = results_df.loc[results_df['outcome'] == 'Black']
white = results_df.loc[results_df['outcome'] == 'White']
draw = results_df.loc[results_df['outcome'] == 'Draw']
win = results_df.loc[results_df['outcome'] != 'Draw']

Total = len(results_df.index)
Wins = len(win.index)

PercentBlack = "Black Wins ≈ %s" %('{0:.2%}'.format(len(black.index)/Total))
PercentWhite = "White Wins ≈ %s" %('{0:.2%}'.format(len(white.index)/Total))
PercentDraw = "Draw ≈ %s" %('{0:.2%}'.format(len(draw.index)/Total))
AllTitle = 'Distribution of Moves by All Outcomes (nSample = %s)' %(workers)

sns.distplot(results_df.moves, hist=False, label = "All")
sns.distplot(black.moves, hist=False, label=PercentBlack)
sns.distplot(white.moves, hist=False, label=PercentWhite)
sns.distplot(draw.moves, hist=False, label=PercentDraw)
plt.title(AllTitle)
plt.ylabel('Density')
plt.xlabel('Number of Moves')
plt.legend()
plt.show()

The code above produces density curves without weights, which I really need to figure out how to generate density curve weights accordingly as well as preserve my labels in the legend
density curves, no weights; help
I also tried frequency histograms, that scaled the distribution heights correctly but I would rather keep the 4 curves overlaid on top of each other for a "cleaner" look...I don't like this frequency plot but this is my current fix at the moment.
results_df.moves.hist(alpha=0.4, bins=range(0, 700, 10), label = "All")
draw.moves.hist(alpha=0.4, bins=range(0, 700, 10), label = PercentDraw)
white.moves.hist(alpha=0.4, bins=range(0, 700, 10), label = PercentWhite)
black.moves.hist(alpha=0.4, bins=range(0, 700, 10), label = PercentBlack)
plt.title(AllTitle)
plt.ylabel('Frequency')
plt.xlabel('Number of Moves')
plt.legend()
plt.show()

If anyone can write the python 3 code that outputs the first plot with 4 density curves with correct subset weights as well as preserves the custom legend that show percentages, that would be much appreciated.
Once the density curves are plotted with the correct subset weights, I am also interested in the python 3 code in finding the max point coordinates of each density curve that shows max frequency of moves once I scale it up to 500,000 iterations.
Thanks

A: You need to be careful. The plot that you have produced is correct. All the curves shown are probability density functions of the underlying distributions.
In the plot that you want to have, only the curve labeled "All" is a probability density function. The other curves are not.
In any case, you will need to calculate the kernel density estimate yourself, if you want to scale it like shown in the desired plot. This can be done using scipy.stats.gaussial_kde().
In order to reproduce the desired plot, I see two options.
Calculate the kde for all involved cases and scale them with the number of samples.
import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import scipy.stats

a = np.random.gumbel(80, 25, 1000).astype(int)
b = np.random.gumbel(200, 46, 4000).astype(int)

kdea = scipy.stats.gaussian_kde(a)
kdeb = scipy.stats.gaussian_kde(b)

both = np.hstack((a,b))
kdeboth = scipy.stats.gaussian_kde(both)
grid = np.arange(500)

#weighted kde curves
wa = kdea(grid)*(len(a)/float(len(both)))
wb = kdeb(grid)*(len(b)/float(len(both)))

print "a.sum ", wa.sum()
print "b.sum ", wb.sum()
print "total.sum ", kdeb(grid).sum()

fig, ax = plt.subplots()
ax.plot(grid, wa, lw=1, label = "weighted a")
ax.plot(grid, wb, lw=1, label = "weighted b")
ax.plot(grid, kdeboth(grid), color="crimson", lw=2, label = "pdf")

plt.legend()
plt.show()

Calculate the kde for all individual cases, normalize their sum to obtain the total.
import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import scipy.stats

a = np.random.gumbel(80, 25, 1000).astype(int)
b = np.random.gumbel(200, 46, 4000).astype(int)

kdea = scipy.stats.gaussian_kde(a)
kdeb = scipy.stats.gaussian_kde(b)

grid = np.arange(500)

#weighted kde curves
wa = kdea(grid)*(len(a)/float(len(a)+len(b)))
wb = kdeb(grid)*(len(b)/float(len(a)+len(b)))

total = wa+wb

fig, ax = plt.subplots(figsize=(5,3))
ax.plot(grid, wa, lw=1, label = "weighted a")
ax.plot(grid, wb, lw=1, label = "weighted b")
ax.plot(grid, total, color="crimson", lw=2, label = "pdf")

plt.legend()
plt.show()


text:
Q: Using Joi and/or Yup for schema validation, is there a way to make a collection of properties required if any of the other properties are present? Take for example an HTML form that collects the details of a person.

Note: Code snippets are simplified and do not match up with the screenshot exactly. Also, code snippets are written using Yup, which is a very similar library to Joi that targets the browser rather than NodeJS.
In order to submit the form, I want to run validations on the address fields and make them required, but only if the user has partially filled out the address section. As a whole, I want to make the address details optional.
Here is a simplified version of my PersonSchema...
import { object, string, number } from 'yup'

const PersonSchema = object().shape({
  name: string().required(),
  age: number()
    .positive()
    .integer()
    .required(),
  address: AddressSchema
})

Defining AddressSchema in this way does not work because the fields are always required...
const AddressSchema = object().shape({
  street: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  city: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  state: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required()
})

And here was my attempt to make address fields dependent on the presence of other address fields, but this does not work because you run into circular dependency issues...
const AddressSchema = object().shape({
  street: string()
    .when(['city', 'state'], {
      is: (city, state) => city || state,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    }),
  city: string()
    .when(['street', 'state'], {
      is: (street, state) => street || state,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    }),
  state: string()
    .when(['street', 'city'], {
      is: (street, city) => street || city,
      then: string()
        .min(2, 'Too Short!')
        .max(50, 'Too Long!')
        .required(),
      otherwise: string()
    })
})

A: I needed the same optional address check: Rather than checking each field based against every other address field, just set a flag in your form/schema named something like 'addressStarted', then use that as your when trigger. The flag was an explicit choice by the user in my case, but it could just as easily be a hidden value; just toggle the value to true in every onChange handler (if you're using something like Formik), or even just an event listener on an element that contains all the address fields.
import { object, string, number } from 'yup'

const AddressSchema = object().shape({
  street: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  city: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required(),
  state: string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required()
})

const PersonSchema = object().shape({
  name: string().required(),
  age: number()
    .positive()
    .integer()
    .required(),
  addressStarted: Yup.boolean(),
  address: object().when('addressStarted', {
    is: true,
    then: AddressSchema,
    otherwise: object().notRequired()
  }),
})


text:
Q: awk command to print out entire row that contains a certain string output.txt
Test Results 1 PASSED with 2 minutes to process 0 issues
Test Results 2 PASSED with 10 minutes to process 0 issues
Test Results 3 FAILED ERROR 1 issues
Test Results 4 PASSED with 4 minutes to process 0 issues
Test Results 5 FAILED ERROR 3 issues
Test Results 6 PASSED with 19 minutes to process 0 issues

I need help coming up with a awk command to parse through this text. I want to list only rows that has more than 0 issue.
So in this case
Test Results 1 PASSED with 2 minutes to process 0 issues
 Test Results 5 FAILED ERROR 3 issues

A: Try this:
$ awk '$(NF-1)' file
Test Results 3 FAILED 1 issues
Test Results 5 FAILED 3 issues

A: Try the following
awk '{if (($0 ~ /[0-9] issues/) && ($(NF-1) != "0")) {print $0}}' output.txt

Here the text is checked for number of issues.
It could have been done using
awk '{if ($0 ~ /[1-9] issues/) {print $0}}' output.txt

in case you are certain that there would be 1-9 issues only and not 10 or more. (regex would ignore 10, 20, 100 ... issues)


text:
Q: HoverOut after transition To witness the bug, hover on the right-side of the overlay box here (don't move your mouse even 1px after hovering):
http://jsfiddle.net/V99rf/

Notice that even after the dom element moves to the left, it remains green with a ":hover" being set.  This gets unset as soon as you move the mouse.  How do I make it unset when the dom element moves from under the mouse, even if the mouse isn't moved?
A recursive javascript timeout would be unsatisfying, but may be the only way...?

A: This is only possible with an event, so you will need some sort of iterative loop to accomplish what you are looking for.


text:
Q: SP13: Sending Email after a Field Change I think this can be done but not sure. I have list full of names that are assigned tasks.  Each item has a task already assigned but at time there could be a chance that the name of the assigned person will change.  If it changes I want an email to go only to the new person responsible of that task and no one else on the list.  I can't figure out where to start.  Can someone help me?

A: If you're using the built-in "Task" list type, it has the ability to "Send Email When Ownership is Assigned". And it emails whoever is in the "Assigned To" box. I don't believe it emails the "old" person when an update occurs if the assignment changes as part of the update.
If you're not using the built-in Task list, you'll need to create a workflow that checks the field containing the person and send them an email that way. Set it to run on add and update.

A: I've posted a question on this myself, I subsequently posted a detailed answer that you'll find here.
In a nutshell, you can use Sharepoint Designer to write a simple workflow using an IF statement.  What you need is to write the value (name) of the current Assigned To to a simple text field, let's call it AssignedToTextField.
A workflow similar to this would do it:
IF AssignedTo not equal to AssignedToTextField, send email to AssignedTo,
then SET AssignedToTextField to AssignedTo value.
The 'SET' part of the workflow is responsible for ensuring the email notification can work more than once.  It checks to see if the name is different between the two fields, if it is different it sends an email "Hey, you have a new task" then the SET command copies the name of the person emailed and pastes it in the AssignedToTextField.  Set the workflow to run when an item is modified.
21/06/2018 - Additional note in response to comment:

*

*Following the email being sent the workflow updates Text Name to make it match with Assigned To.  For my purposes, I wanted the Assigned To to be emailed upon item creation & when modified.  If this isn't the behaviour you want for triggering your email, you'd need to change the workflow start options - choose only 'when item changed', deselect 'when item created'.

*"...field copying over the AD name..."

I've made a mistake in the field type definition.  The Assigned To and Text Field should both be set to Display Names, Semicolon Delimited and not String.
I checked this by using the "Log" command in the workflow, to log the value that Sharepoint finds in the Assigned To field.

The item workflow history shows the values (the LOG command causes this info to be logged here):
So when the field types do not match, different values are returned.  Sorry about misadvising you.  I'll update my linked Answer.


text:
Q: Format code stored in mysql database table column using php I was trying to build a blog system and I have stored the contents being 4000 characters in length. The blog post contains  statements along with html text. The contents within these  may contain code in any implementation language. The text is loosing formatting when i copy the text to the sql database , and I would like to retain the indentation within the data , or need some javascript library that will prettify the output of the pre statements on ouput from a mysql query statement.
Output:

Expected Output:

A: Here are some javascript code formater and beautifier:
This little beautifier will reformat and reindent bookmarklets, ugly JavaScript, unpack scripts
To beautify using python:
$ pip install jsbeautifier
$ js-beautify file.js

Beautified output goes to stdout.
Find more info here:
https://www.npmjs.com/package/js-beautify
A Javascript module and CSS file that allows syntax highlighting of source code snippets in an html page.
https://code.google.com/p/google-code-prettify/
It need some effort to research on google what we require. What you can do too before posting any question.
Hope here is the inforamtion what you required
https://github.com/stevenbenner/identify-indent


text:
Q: C++ very long integer digit counter I have an assignment to create a program in C++ which would count digits of extremely long integers.
I am given two random numbers a and b (1 <= a, b <= 10^16). I need to find how many digits does a number a^b (a to the power b) has. (I don't need to know the number itself, only how many digits it has)
I had few ideas on how to solve this problem, one way I thought about it is creating a separate structure which would hold these very long integers and would be able to do multiplication on them, but it would take extremely long to do multiplication that many times, and the time limit for the program is 1s. Maybe there is some kind of function or something like that in C++ which could help me out?
Thanks for your help in advance!

A: The number of digits of a number N in base B is floor(logBN) + 1. So you need to calculate floor(log10(ab)) + 1 which is equal to floor(b*log10a) + 1
floor rounds the number down to the nearest integer. Both floor and log10 functions are available in <cmath> library

A: using logarithm, this can be solved with "small" numbers:
log (a^b) = log (a) * b
the number you are looking for is going to be
auto exp = math.log10(a) * b;

you will need to round thix result to the lower integer higher than this value

A: you will took to numbers from user and you will do (int temp) to used it in code and you will call a pow function from (cmath) library and if you want to print the power of two numbers calling this function and you will do a for loop from (1) to (power number) and in this loop you will equal temp and counter and out of loop you will print this temp
 and this is the code .
#include <iostream>
#include <cmath>
using namespace std;

void power_digit();

int main()
{
    power_digit();
}
void power_digit()
{
    int x , y ,temp ;
    string result;
    cout << "\nEnter number one :";
    cin >> x ;
    cout << "\nEnter number two :";
    cin >> y ;
    cout << "The power of x and y is : "<< pow(x,y);
      for (int i = 1 ; i < y ; i++)
    {
        temp =  i ;
    }
    cout << "\nThe digit of result is :" << temp;
}


text:
Q: How can we filter the records in a strongly typed partial view in ASP.NET MVC? I have a strongly typed partial view that populates all the Records from Search table.
Now i have a textbox to enter name & a button to filter the records that can match a name.(Like Search page).
Can anybody provide code sample for this scenario?
My Main Page loads particular view based on the radiobutton selection(Search or Inquiry) as below using JQuery:
/* Loading the partial view based on radio button click... */
        $(document).ready(function() {
            $(':radio').click(function() {
                if (this.value == '2') {
                $('#ViewAllInquiries').load('/Home/Inquiry', function(html) { $('#ViewAllInquiries')[0].value = html; });
                }
                else {
                    $('#ViewAllInquiries').load('/Home/Search', function(html) { $('#ViewAllInquiries')[0].value = html; });
                }
            });
        })

Here is my one of the Partial view ControllerCode:
[HttpGet]
    public ActionResult Search()
    {
        var search = from s in entity.Search
                     select s; return PartialView(search);
    }

Here is the User control Partial view(Search.ascx):

>" %>

         TX_Id
        Name
           <%= Html.TextBox("Name")%> <input type="submit" value="Filter" />
        Email Address

    <% foreach (var item in Model)
{ %>

            <%= Html.Encode(item.TX_Id) %>
            "><%= Html.Encode(item.CustomerMaster.FullName()) %>
            <%= Html.Encode(item.CustomerMaster.MS_Id) %>

    <% } %>

Thanks for your time.

A: I do the same thing using an Ajax form.  It's really easy.  Here's the code I use:
Html:

    <%
        using (Ajax.BeginForm("Home", "Search", null,
            new AjaxOptions { UpdateTargetId = "Output" },
            new { id = "SearchForm" }))
        {
            %>

                <input name="searchField" />
                <input type="submit" value="Search" />
            <%
        }
    %>

Then in the controller you just have:
public PartialViewResult Search(FormCollection form)
{

    var model = YourSearchMethod(form["searchField"]);
    return PartialView("Search", model);

}

The div with the id "Output" will be updated with your partial view result every time the submit button is clicked.  In your case you have two different potential partial views, just submit the radio button value as part of your form and you can switch the output view from within the controller.
Why use FormCollection instead of parameters?  I've had some difficult using named parameters with ajax forms, but you can try it and see how it works.  It should look something like this instead:
public PartialViewResult Search(string searchField, bool inquiry)
{
    if (inquiry)
    {
        var model = YourInquiryMethod(searchField);
        return PartialView("Inquiry", model);
    }
    else
    {
        var model = YourSearchMethod(searchField);
        return PartialView("Search", model);
    }
}

A: I do the same on one of my sites but have implmented it a little diffently.
I have, in my View the following html;

I also have the following jQuery;
 function editBenefit(objThis) {
     var id = $(objThis).parents('.Benefit').attr("id");
     $.post("/Home/jQueryGetBenefit", { Id: id },
        function(newHTML) {
            $('.EditProductContainer').html(newHTML);
        });
 }

Then in my controller I have;
    [AcceptVerbs(HttpVerbs.Post)]
    public PartialViewResult jQueryGetBenefit(int Id)
    {
        Application application = Helpers.CacheHelper.Get();
        Benefit thisBenefit = application.findBenefit(Id);

        return PartialView("EditBenefit", thisBenefit);
    }

I think this is doing what you want but I'm returning a rendered PartialView and replacing the contents of a containing div with the html generated by the partial view.
Hope this is of some help.


text:
Q: How to prevent retrieving Private Lists in Marketing Cloud? I'm trying to retrieve Subscriber's public lists only, but it keeps returning public lists + a private list called "All Subscribers". I've tried both following methods but neither worked, any help would be appreciated. Thanks!
METHOD 1:
var subLists = subObj.Lists.Retrieve({
                Property: "Type",
                SimpleOperator: "equals",
                Value: "Public"
             })

METHOD 2:
var subLists = subObj.Lists.Retrieve({
                  LeftOperand: {
                      Property: 'ListClassification',
                      SimpleOperator: 'equals',
                      Value: 'PublicationList'
                  },
                  LogicalOperator: 'AND',
                  RightOperand: {
                      Property: 'Type',
                      SimpleOperator: 'equals',
                      Value: 'Public'
                  }
              })


text:
Q: Вычислить среднее значение по колонке в файле Пытаюсь вычислить среднее значение оценок учеников в каждом факультете и ничего на ум не приходит. Прошу помощи! Python
filename = input('Enter name of file: ')
file = open(filename, 'r')
massive = []
massive1 = []
massive = file.readlines()
for i in massive:
    massive1.append(i.strip().split(','))

#-----Sorting

for i in sorted(massive1, key=lambda ex : (ex[1])):
    print(i)

file.close()

#Конец кода

Это часть кода для 1-й части задания, а как посчитать среднюю оценку каждого факультета(3-й параметр)
Вот данные файла с которыми я работал.
Cherkas,2002,FizMat,5
Grigorenko,2002,FizMat,5
Sokil,2001,IstFak,5
Konev,2000,IstFak,3
Pulya,2002,IstFak,4
KiMChenIn,1984,FilFak,2
Onegin,2000,FilFak,4

На экран должно выводить
IstFak: 4
FizMat: 5
FilFak: 3

A: Тут надо стбрать оценки в словарь. defaultdict упрощает
from collections import defaultdict

massive = """Cherkas,2002,FizMat,5
Grigorenko,2002,FizMat,5
Sokil,2001,IstFak,5
Konev,2000,IstFak,3
Pulya,2002,IstFak,4
KiMChenIn,1984,FilFak,2
Onegin,2000,FilFak,4""".splitlines()

massive1 = []
for i in massive:
    massive1.append(i.strip().split(','))
averdict=defaultdict(list)

for i in massive1:
    averdict[i[2]].append(int(i[3]))

for k,v in averdict.items():
    avg = sum(v)/len(v)
    print(k,avg,sep=": ")


text:
Q: Is there a way to stop training in the middle of an epoch with tensorflow? Just wondering if there is a way to save the highest accuracy and lowest loss in the middle of an epoch and using that as the score moving forward for the next epoch. Normally my data is maxed out at 43.56% accuracy but I've seen it go all the way up to above 46% in the middle of an epoch. Is there a way I can stop the epoch at that point and use that for the score to beat moving forward?
Here's the code that I'm running right now
import pandas as pd
import numpy as np
import pickle
import random
from skopt import BayesSearchCV
from sklearn.neural_network import MLPRegressor
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM, Bidirectional, SimpleRNN, GRU
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from tensorflow.keras import layers
import tensorflow_docs as tfdocs
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow_docs.modeling
from tensorflow import keras
import warnings
warnings.filterwarnings("ignore")
warnings.filterwarnings('ignore', category=DeprecationWarning)

train_df = avenues[["LFA's", "Spend"]].sample(frac=0.8,random_state=0)
test_df = avenues[["LFA's", "Spend"]].drop(train_df.index)
train_df = clean_dataset(train_df)
test_df = clean_dataset(test_df)
train_df = train_df.reset_index(drop=True)
test_df = test_df.reset_index(drop=True)
train_stats = train_df.describe()
train_stats = train_stats.pop("LFA's")
train_stats = train_stats.transpose()
train_labels = train_df.pop("LFA's").values
test_labels = test_df.pop("LFA's").values
normed_train_data = np.array(norm(train_df)).reshape((train_df.shape[0], 1, 1))
normed_test_data = np.array(norm(test_df)).reshape((test_df.shape[0], 1, 1))
model = KerasRegressor(build_fn=build_model, epochs=25,
                                   batch_size=1, verbose=0)
gs = BayesSearchCV(model, param_grid, cv=3, n_iter=25, n_jobs=1,
                               optimizer_kwargs={'base_estimator': 'RF'},
                               fit_params={"callbacks": [es_acc, es_loss, tfdocs.modeling.EpochDots()]})
try:
     gs.fit(normed_train_data, train_labels)
except Exception as e:
     print(e)

A: Try to use train_on_batch instead of fit. In this way, you can control inside your epoch to stop after each batch you would like ( Although as a machine learning point of view, I have doubts if it is a good idea, and you'll get the less generalized model at the end).


text:
Q: Is Cloud Functions in Firebase Free or Not (Cloud Functions deployment requires the pay-as-you-go (Blaze) billing plan) When i make my first deploy function I can't deploying Because I have Error Asks me to make Upgrade to my account to Blaze I need to Know Can i deploy Function when i use free account??
Output:
i  deploying functions
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
!  functions: missing required API cloudbuild.googleapis.com. Enabling now...
+  functions: required API cloudfunctions.googleapis.com is enabled

Error: Cloud Functions deployment requires the pay-as-you-go (Blaze) billing plan. To upgrade your project, visit the following URL:

https://console.firebase.google.com/project/institute-for-admin/usage/details

For additional information about this requirement, see Firebase FAQs:

https://firebase.google.com/support/faq#functions-runtime

A: Just to clear confusion here
Firebase seems to close the cloud functions for spark plan. So, I thought what if firebase is planning to take away the free plan features one by one.
Here is the answer from their FAQ page.

Does this change to Cloud Functions mean the Firebase free plan (Spark) is going away?
No. This change will not affect the other Firebase products. The Spark
plan is going to be unavailable for Cloud Functions after March 15,
2021.

A: As the message says, you can't deploy functions on the Spark free tier, if you target nodejs 10.  Read the link to the FAQ:

Why will I need a billing account to use the Node.js 10 runtime for
Cloud Functions for Firebase?
Because of updates to its underlying architecture planned for August
17, 2020, Cloud Functions for Firebase will rely on some additional
paid Google services: Cloud Build, Container Registry, and Cloud Storage. These architecture updates will apply for functions deployed
to the Node.js 10 runtime. Usage of these services will be billed in
addition to existing pricing.
In the new architecture, Cloud Build supports the deployment of
functions. You'll be billed only for the computing time required to
build a function's runtime container.
Cloud Storage, interoperating with Google Container Registry, will
provide storage space for the containers in which functions run.
You'll be billed for each container required to deploy a function. If
you're currently using Cloud Functions within free usage limits, you
may notice new, small charges for each container stored— for example,
1GB of storage is billed at $0.026 per month.
To understand more about how your bill might change, please review the
following

*

*Cloud Functions pricing: existing free tier is unchanged.

*Cloud Build pricing: Cloud Build provides for a free tier.

*Container Registry pricing.

If you want to target node 8, that might still work.  But it's been deprecated, and your functions will eventually stop working.  You would still have to migrate them to node 10 in that case, and provide a billing account.
Cloud Functions still has a monthly free allowance that's documented in the pricing page.  But you will have to provide a credit card and be on a billing plan in order to use it.  You will be responsible for paying for any monthly overage.

A: I don't think Cloud Function is free even if you stay within the free quota as  they seem to charge for container storage which seems to automatically get created when you deploy a function.

A: Currently, the firebase is using node version 10 for cloud functions which requires you to pay (pay as you go).
You can change the node from 10 to 8 (to use for free of cost) in functions/package.json
"engines": {
    "node": "8". // changed from 10 to 8
  },

However, this will be soon deprecated. This is what the firebase website says:

Node.js 8 has been deprecated. Starting Feb 15, 2021, we'll no longer
support new deploys or updates of Node.js 8 functions. Starting Mar
15, 2021, we'll no longer support executions of existing Node.js 8
functions.

https://firebase.google.com/support/faq?authuser=0#expandable-10-label
EDIT
This might be a legacy. Please check the latest comments for an updated policy.

A: As of  June 8, 2020 the answer is no it is not free anymore
It used to be an option to set the engine to a legacy node 8 but as firebase states

Node.js 8 (deprecated on June 8, 2020) Deployment of functions to the
Node.js 8 runtime was disabled in the Firebase CLI on December 15,
2020. Execution of already-deployed functions will stop at some point in the future; if you have deployed functions to the Node.js 8
runtime, we recommend that you upgrade to the Node.js 14 runtime.

And therefore it is no longer an option

A: I was also facing the same issue! If you only concerns with learning cloud functions of firebase instead of running command firebase-deploy try firebase-serve it will serve locally firebase cloud functions on your machine and you can use it!

A: in this  time when I write these lines node.js 8 is no longer available 'The Spark plan is  unavailable for Cloud Functions after March 15, 2021' so I think that we have migrate to node.js 10 and higher but with no free plan :we have to 'pay as we go' by providing our cards number series. Note that this 'blazer plan' could be free if we do note exceed some limits
for more details please see this Start for free,
then pay as you go

A: Cloud Functions are only available on the Blaze plan which means you'll need to enter a credit card.
If you want to stop using Cloud Functions, remove the functions section from your firebase.json (if it exists) and also delete the functions folder that firebase init created for you.
If you want to experiment with Cloud Functions for free, you should use the local Firebase Emulator Suite to develop.


text:
Q: Hortonworks Sandbox 2.1 | Split class cascading.tap.hadoop.io.MultiInputSplit not found I'm executing a scalding job in Hortonworks distribution (HDP 2.1) and it throws this following issue:

I tried to locate the cascading jar in Hortonworks but I couldn't find it. What am I doing wrong here?


text:
Q: Matching keys in different lists of dicts I have a csv.DictReader instance of dicts and a list of dicts.
instance:
{'Salary': '3000', 'Name': 'James Jones', 'GameInfo': 'Den@Cle 07:30PM ET',
 'AvgPointsPerGame': '4.883', 'teamAbbrev': 'Cle', 'Position': 'SG'}
{'Salary': '3000', 'Name': 'Justin Anderson', 'GameInfo': 'Orl@Dal 09:00PM ET',
 'AvgPointsPerGame': '13.161', 'teamAbbrev': 'Dal', 'Position': 'SF'}

list:
[

    {'playername': 'Justin Anderson', 'points': '6.94'},

    {'playername': 'DeAndre Liggins', 'points': '11.4'},

]

I cannot figure out how to iterate over these lists of dictionaries, match the Name and playername keys, then spit the ['Name'] from one dict and the ['points'] from the matching dict. In the example above I would match Justin Anderson from the two sets of dicts then print out Justin Anderson, 6.94
The core of the app takes 2 CSV's and makes them lists of dicts.

A: It's not really efficient this way but it wouldn't require any preprocessing:
# Instead of your CSVReader:
dicts = [{'Salary': '3000', 'Name': 'James Jones', 'GameInfo': 'Den@Cle 07:30PM ET', 'AvgPointsPerGame': '4.883', 'teamAbbrev': 'Cle', 'Position': 'SG'},
         {'Salary': '3000', 'Name': 'Justin Anderson', 'GameInfo': 'Orl@Dal 09:00PM ET', 'AvgPointsPerGame': '13.161', 'teamAbbrev': 'Dal', 'Position': 'SF'}]

list_of_dicts = [
    {'playername': 'Justin Anderson', 'points': '6.94'},
    {'playername': 'DeAndre Liggins', 'points': '11.4'},
]

# For each dictionary in the CSVReader
for dct in dicts:
    # For each dictionary in your list of dictionaries
    for subdict in list_of_dicts:
        # Check if the name and playername matches
        if dct['Name'] == subdict['playername']:
            # I just print out the results, you need to do your logic here
            print(dct['Name'])
            print(dct)
            print('matching')
            print(subdict)

and this prints:
Justin Anderson
{'Salary': '3000', 'Name': 'Justin Anderson', 'GameInfo': 'Orl@Dal 09:00PM ET', 'AvgPointsPerGame': '13.161', 'Position': 'SF', 'teamAbbrev': 'Dal'}
matching
{'playername': 'Justin Anderson', 'points': '6.94'}

If you want it faster than you should preprocess your list of dictionaries so that you can simply lookup the playername:
>>> dict_of_dicts = {dct['playername']: dct for dct in list_of_dicts}
>>> dict_of_dicts
{'DeAndre Liggins': {'playername': 'DeAndre Liggins', 'points': '11.4'},
 'Justin Anderson': {'playername': 'Justin Anderson', 'points': '6.94'}}

Then the loop simplifies to:
for dct in dicts:
    if dct['Name'] in dict_of_dicts:
        print(dct['Name'])
        print(dct)
        print('matching')
        print(dict_of_dicts[dct['Name']])

giving the same result.


text:
Q: Is there any way to "precompile" Markdown in Rails? I have a rails app which displays static markdown from an sqlite database. Is there any way to "precompile" the markdown files like for css/js so that markdown does not need to be re-rendered for each request? If so, how do I do it?
There was a question similar to this but I don't know how to cache markdown either. Some websites suggest that rendering markdown adds very little overhead to the app. Is this correct?

A: I would just cache the rendered output. Use something like this: http://railscasts.com/episodes/387-cache-digests


text:
Q: Potential bug with NSDateFormatter in iOS6. Has anyone else encountered this? We'll get straight to it.  Here's the code snippet:
NSString *dateString = @"4001-01-01T00:00:00.000Z";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];

NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"%@ -- %@", dateString, date);

The result when building for iPhone 5.1 Simulator (or iOS 5.1 device):
4001-01-01T00:00:00.000Z -- 4001-01-01 00:00:00 +0000

The result when building for iPhone 6.0 Simulator (or iOS 6 device):
4001-01-01T00:00:00.000Z -- 2001-01-01 00:00:00 +0000

Note the discrepancy in the output years (after the "--").
We've determined that in iOS 6, the date formatter subtracts 2000 years from any date beyond the year 3512 (1500 years from now).
Has anyone else experienced this and/or have an elegant workaround?
Thanks.


text:
Q: Groovy how to push value to array of type long New to groovy so take it easy...
I get an error that there is no push() method for an array of longs
def mylongs=[] as long[];
somebject.each{
     //logic to chooose...
     mylongs.push(it.thisisalong);
}

So how do I append long values properly. Using
 mylongs[mylongs.size()]=it.thisisalong

yields out of index bounds exceptions

A: First let me address your second question, and the larger difference between Arrays and Lists in the JVM:
Arrays, and lists in Java are 0-based, meaning that the first element can be found in a[0], and the last element, in a[a.size()-1]. Element a[a.size()] exceeds the bounds of your array, and that is what your exception tells you.
In groovy you can use a.last(), if you want to pick up the last element of an array/list, in my opinion it is more readable and self-explanatory.
If you cast your mylongs into an array before populating it, then you have fixed the size of the array, and you can push no more objects into it. If your array has variable size, then you need to use a List.
List<Long> a=[]

a << 1 as long
a << 2 as long

etc
When you need to convert it back to an array, you can do this:
a as long[]

Now to the answer of the first question, the others pretty much gave you a valid answer, but in groovy style, i'd write (providing that somebject is a collection of some type):
def mylongs= somebject.collect{ it.thisisalong } as long[]

But pushing an element into an List and be done like this, in groovy style:
myLongs << 4

You cannot append values into an array, it has a fixed size.

A: mylongs = someobject*.thisisalong as long[]

should do. *. is spread operator in groovy.

A: I ended up doing this.
 def mylongs=[];
 somebject.each{
      //logic to chooose...
      mylongs.add(it.thisisalong as long);
 }


text:
Q: Invertibility of Restricted Incidence Matrix of Connected Graph
Let $G$ be a connected graph with n vertices. Suppose a subset $S$ ⊂ $E(G)$ with $|S| = n − 1$ defines a
  spanning tree in G. Let $Q_S$ be the restriction of the incidence matrix $Q$ of $G$ to the columns indexed by $S$. Show that $Qˆ{
_S} = Q_S− (\text{a row})$ is invertible by constructing the inverse.

Proof
Since spanning tree has just one connected component, its rank of incidence matrix is $n-1$. This is given by the following theorem

If $G$ is a connected graph on $n$ vertices,then rank $Q(G) = n−1$

Now since $\hat Q{_s}$ is $n-1$ x $n-1$ matrix and its rank is $n-1$, it's invertible.


text:
Q: Laravel average value on accessor I need to calculate average age of user.
here is my accessor code
public function getAgeAttribute()
{
    if ($this->birthday)
        return Carbon::parse($this->birthday)->age;
    else
        return 'Unknown';
}

How can i calculate the average age from accessor?
Thanks for any help..

A: In your User.php:
public function getAgeAttribute()
{
  if ($this->birthday)
    return Carbon::parse($this->birthday)->age;
  else
    return 'Unknown';
}

If you want to calculate the average age of ALL users, place this where you need it:
User:all()
    ->where('age', '!=', 'Unknown')
    ->avg('age');

This will simply not include the users without a birth date, as it wouldn't make sense.
If the birthday attribute is in the users table, it will be more efficient to not select users without a birthday date:
User:whereNotNull('birthday')
    ->get()
    ->avg('age');

A: Property age for Carbon object not exist.
You can use diffInYears with actual date to compute the age
public function getAgeAttribute()
{
    if ($this->birthday)
        return Carbon::now()->diffInYears(Carbon::parse($this->birthday));
    else
        return 'Unknown';
}

In your model you can add protected property $dates in order to retreive derectly a Carbon object and don't parse.


text:
Q: How to hide headers and footers in Micrsoft Word 2011? I'm using Microsoft Word 2011 for Macintosh on OSX Mountain Lion and when viewing my document in Print Layout mode, I would like to hide the header and footers so that the text at the bottom of one page rolls right into the text of the following page with no space for headers, footers, or a page break.
How can I hide the headers and footers?  Do I need to switch to a different viewing mode other than Print Layout?  On windows version of word I was using, I would just double click on the blank area between pages, above the header of the next page and below the footer of the current page to hide them, but this does not work on my Macintosh. I tried Draft mode, but I don't like that you do not see the edges of the paper anymore and you lose and notes from the margins in that mode.


text:
Q: ssh_exchange_identification: Connection closed by remote host x Environment:
Ubuntu-14.04-LTS
Git Version – 1.9
Problem:
 From the Ubuntu terminal when we run ssh -Tvvv -p 29418 git-user@gerrit.server.com it fails with below error.
Error:
OpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014
debug2: ssh_connect: needpriv 0
debug1: Connecting to gerrit.server.com [101.102.103.104] port 29418.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug3: Incorrect RSA1 identifier
debug3: Could not load "/root/.ssh/id_rsa" as a RSA1 public key
debug1: identity file /root/.ssh/id_rsa type 1
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.13
debug1: ssh_exchange_identification: <Script>

debug1: ssh_exchange_identification: document.location.href = "https://109.101.11.228:8080/";

ssh_exchange_identification: Connection closed by remote host

To fix this problem we have tried the following workarounds, however so far none of them were helped us to fix it.
1.  ~/.ssh/id_rsa.pub key and user name verified in Gerrit GUI Settings.
2.  Permission applied like
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*
3.  Checked /etc/hosts.allow & /etc/hosts.deny files with working machine, both are identical.
4.  Executed unset https_proxy & unset http_proxy commands
5.  Checked .gitconfig file.
6.  Created vi .ssh/config file and added below info.
Host gerrit.server.com
User git-user
Port 29418
7.  Reinstalled OpenSSL and rebooted the machine.
8.  Tried dpkg-reconfigure openssh-server
9.  Firewall not running.
10. Ifconfig shows only eth0 & lo (No problem here).
11. Verified /etc/ssh/sshd_config with working machine, no problem with this file.


text:
Q: Get confidence limits from Gaussian Process model in Python GPy I calcualted a Gaussian Process model in Python using GPy:
ker0 = GPy.kern.Bias(input_dim=1,variance=1e-2)
...
m = GPy.models.GPRegression(x, y, ker0+ker2)

I can plot it with
m.plot()
plt.show

and it visualizes the points, the spline and the confidence limits. Now I want to extract the parameters and the confidence limits to use the data in another plot. My question is, how can I access these data.
if I print m I get
Name : GP regression
Objective : 31.9566881665
Number of Parameters : 4
Number of Optimization Parameters : 4
Updates : True
Parameters:
  GP_regression.           |              value  |  constraints  |  priors
  sum.bias.variance        |  7.48802926977e-61  |      +ve      |
  sum.spline.variance      |     -2.99999065833  |   -3.0,-1.0   |
  sum.spline.c             |      19.8308670902  |   0.0,300.0   |
  Gaussian_noise.variance  |      50.2314402955  |      +ve      |

thx!

A: Try
m.sum.bias.variance

notice the m. at the beginning.


text:
Q: Is there a more memory efficient way to search through a Core Data database? I need to see if an object that I have obtained from a CSV file with a unique identifier exists in my Core Data Database, and this is the code I deemed suitable for this task:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity;
entity =
[NSEntityDescription entityForName:@"ICD9"
            inManagedObjectContext:passedContext];
[fetchRequest setEntity:entity];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"uniqueID like %@", uniqueIdentifier];
[fetchRequest setPredicate:pred];
NSError *err;
NSArray* icd9s = [passedContext executeFetchRequest:fetchRequest error:&err];
[fetchRequest release];
if ([icd9s count] > 0) {
    for (int i = 0; i < [icd9s count]; i++) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        NSString *name = [[icd9s objectAtIndex:i] valueForKey:@"uniqueID"];
        if ([name caseInsensitiveCompare:uniqueIdentifier] == NSOrderedSame && name != nil)
        {
            [pool release];
            return [icd9s objectAtIndex:i];
        }
        [pool release];
    }
}
return nil;

After more thorough testing it appears that this code is responsible for a huge amount of leaking in the app I'm writing (it crashes on a 3GS before making it 20 percent through the 1459 items). I feel like this isn't the most efficient way to do this, any suggestions for a more memory efficient way? Thanks in advance!

A: *

*Don't use the like operator in your request predicate.  Use =.  That should be much faster.

*You can specify the case insensitivity of the search via the predicate, using the [c] modifier.

*It's not necessary to create and destroy an NSAutoreleasePool on each iteration of your loop.  In fact, it's probably not needed at all.

*You don't need to do any of the checking inside the for() loop.  You're duplicating the work of your predicate.

So I would change your code to be:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:...];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"uniqueID =[c] %@", uniqueIdentifier]];
NSError *err = nil;
NSArray *icd9s = [passedContext executeFetchRequest:fetchRequest error:&err];
[fetchRequest release];
if (error == nil && [icd9s count] > 0) {
  return [icd9s objectAtIndex:0]; //we know the uniqueID matches, because of the predicate
}
return nil;

A: Use the Leaks template in Instruments to hunt down the leak(s). Your current code may be just fine once you fix them. The leak(s) may even be somewhere other than code.
Other problems:

*

*Using fast enumeration will make the loop over the array (1) faster and (2) much easier to read.

*Don't send release to an autorelease pool. If you ever port the code to garbage-collected Cocoa, the pool will not do anything. Instead, send it drain; in retain-release Cocoa and in Cocoa Touch, this works the same as release, and in garbage-collected Cocoa, it pokes the garbage collector, which is the closest equivalent in GC-land to draining the pool.

*Don't repeat yourself. You currently have two [pool release]; lines for one pool, which gets every experienced Cocoa and Cocoa Touch programmer really worried. Store the result of your tests upon the name in a Boolean variable, then drain the pool before the condition, then conditionally return the object.

*Be careful with variable types. -[NSArray count] returns and -[NSArray objectAtIndex:] takes an NSUInteger, not an int. Try to keep all your types matching at all times. (Switching to fast enumeration will, of course, solve this instance of this problem in a different way.)

*Don't hide releases. I almost accused you of leaking the fetch request, then noticed that you'd buried it in the middle of the code. Make your releases prominent so that you're less likely to accidentally add redundant (i.e., crash-inducing) ones.


text:
Q: Fix minimum size of 3D globe cesium I want to fix the minimum size of 3D globe such as if user decreases the size through mouse it should not decrease beyond some fixed value.
var viewer = new Cesium.Viewer("cesiumContainer", {

animation: false,

timeline: false

});

Sandcastle Link
Any help is highly appreciated, Thanks

A: viewer.scene.screenSpaceCameraController.minimumZoomDistance = 6378137;
viewer.scene.screenSpaceCameraController.maximumZoomDistance = 6378137 * 2;

A: Give this a try:
var viewer = new Cesium.Viewer("cesiumContainer");  // plus whatever options

viewer.scene.screenSpaceCameraController.maximumZoomDistance = 1e8;

The value 1e8 here is the maximum number of meters that the camera is allowed to travel away from the focus point (typically the center of the Earth).  You can try 1e7 or 1e9 to adjust it.


text:
Q: Using models clean method for fields validation I need to check the model field for a list of available items before I save them to the database.
models.py
class Vendors(models.Model):
    COUNTRY_CHOICES = tuple(countries)
    ...
    country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
    ...

class for saving models
class CsvToDatabase(APIView):

    def post(self, request, format=None):
        data = request.data
        for key, vendor in data.items():
            Vendors(
                ...,
                country=vendor['Country'],
                ...,

            ).save()

        return Response({'received data': request.data,
                         'message': 'Vendors from vendors_list were successfully added to the database'})

For validation Im added clean method to models
def clean(self):
    if self.country not in [x[1] for x in countries]:
        raise ValidationError(detail="Country name does not match to the country list ")

But it doesnt work
Next step I added the same code to method save
def save(self):
    if self.country not in [x[1] for x in countries]:
        raise ValidationError(detail="Country name does not match to the country list ")

And it works, but  I read that using validation in the save method is not correct. And the correct method for use - clean, why in my case it does not work?

A: See model validation for a full explanation of how validating models works.
In short: To validate an object, you need to call full_clean() on the object. This does not happen automatically! It happens when:

*

*You use a ModelForm and call is_valid() on the form

*You use a ModelSerializer in DRF and call is_valid() on the serializer

*You call full_clean() explicitly

In your case, just create the object, call full_clean() and then save(). Note you don't even have to add your own check (clean() method) because the check for valid choices is automatically performed by Django during clean_fields() when choices is set on a field:
v = Vendors(country=vendor['country'], ...)
try:
    v.full_clean()
except ValidationError as e:
    # do something e.g. return error response
v.save()
return Response(...)


text:
Q: htaccess get value with spaces example.com/search/search+something I want to like this search but its not work

example.com/search/.htaccess
<Files .htaccess>
order allow,deny
</Files>

Options +FollowSymLinks
RewriteEngine On
RewriteBase /search/

RewriteRule ^(\w+)(?:/[^/]+)?/?$ load.php?q=$1 [L,QSA]

RewriteRule ^(\w+)/[^/]+/[^/]+/([0-9]+)/?$ load.php?q=$1&p=$2 [L,QSA]

How to fix it... if i type like this example.com/search/songs its work. but after songs add something with spaces or (+) not work and show 404 page.. ex :(example.com/search/songs+video)

A: Change the \w to [^/] so that you can match spaces but not slashes. Encoded spaces in the URI get decoded before getting matched by patterns in rewrite rules:
RewriteRule ^([^/]+)(?:/[^/]+)?/?$ load.php?q=$1 [L,QSA]

You may also want to add a NE flag in the square brackets if the string ends up with %20 in the load.php script.


text:
Q: How do I remove a block of text from mutiple repetitive json files where there is a small change between the files? I have a json file that has repetive parts and I'm trying to write a script to remove a certain block of text from multiple files. A Python script would be the most preferred otherwise from my searching sed can work too though I know nothing about it.
Here is a sample of the format of my json file:
    {
      "Animal": {
        "Type_species": "Reptile"
      },
      "FindMe": "https://www.merriam-webster.com/dictionary/amphibian",
      "Description": "Most are cold blooded."
    },
    {
      "Animal": {
        "Type_species": "Mammal"
      },
      "FindMe": "https://kids.nationalgeographic.com/animals/mammals/",
      "Description": "There Are Approximately 5,000 Mammal Species."
    },
    {
      "Animal": {
        "Type_species": "Amphibian"
      },
      "FindMe": "https://en.wikipedia.org/wiki/Amphibian",
      "Description": "Most amphibians have thin, moist skin that helps them to breathe"
    },

*

*How would I remove the following from the json file?

    {
      "Animal": {
        "Type_species": "Mammal"
      },
      "FindMe": "https://kids.nationalgeographic.com/animals/mammals/",
      "Description": "There Are Approximately 5,000 Mammal Species."
    },

My other question is,
2. How do I adapt the script to account for different "FindMe" Urls across multiple files? For example a second file would have the below and so on for multiple files?
    {
      "Animal": {
        "Type_species": "Mammal"
      },
      "FindMe": "https://kids.nationalgeographic.com/animals/mammals/facts/arctic-fox",
      "Description": "There Are Approximately 5,000 Mammal Species."
    },

I think using a regex can help but I'm having trouble understanding them and implementing them within a script.
Any help is appreciated, thank you.
Update:
I would like the end result to look like this:
    {
      "Animal": {
        "Type_species": "Reptile"
      },
      "FindMe": "https://www.merriam-webster.com/dictionary/amphibian",
      "Description": "Most are cold blooded."
    },
    {
      "Animal": {
        "Type_species": "Amphibian"
      },
      "FindMe": "https://en.wikipedia.org/wiki/Amphibian",
      "Description": "Most amphibians have thin, moist skin that helps them to breathe"
    },

A: Assuming your complete JSON contains a list of dictionaries (which your sample suggests) then:
JSON = {"data": [{
    "Animal": {
        "Type_species": "Reptile"
    },
    "FindMe": "https://www.merriam-webster.com/dictionary/amphibian",
    "Description": "Most are cold blooded."
},
    {
    "Animal": {
        "Type_species": "Mammal"
    },
    "FindMe": "https://kids.nationalgeographic.com/animals/mammals/",
    "Description": "There Are Approximately 5,000 Mammal Species."
},
    {
    "Animal": {
        "Type_species": "Amphibian"
    },
    "FindMe": "https://en.wikipedia.org/wiki/Amphibian",
    "Description": "Most amphibians have thin, moist skin that helps them to breathe"
}]}

JSON['data'] = [d for d in JSON['data'] if d['Animal']['Type_species'] != 'Mammal']

print(JSON)

A: This might work for you (GNU sed):
sed '/^\s*{/{:a;N;/^\(\s*\){.*\n\1},/!ba;/"Type_species": "Mammal"/d}' file

Gather up details for each animal and remove animal if it contains "Type_species": "Mammal".


text:
Q: Sum rows if header and first column meet criteria in Google Sheets I have a table with first row as header and first column as week number, I need to sum all the data on every week that meets the criteria depending on the header name.
This formula only filter by header and week, but I can't summarize the data, I would like that the formula is "dynamic" because the header name section can change:

=QUERY(TRANSPOSE(A1:AA23),"SELECT * WHERE Col1 = 'M.O.'",1)

This is an example spreadsheet, at the end is the desired result:
LINK TO EXAMPLE SHEET

A: use:
=INDEX(QUERY(SPLIT(FLATTEN(IF(D2:24="",,D1:1&"×"&A2:A24&"×"&D2:24)), "×"),
 "select Col1,sum(Col3)
  where Col1 matches 'INDIRECTO|M.O.'
  group by Col1
  pivot Col2"))


text:
Q: multiple preinstalled programs with similar jobs I have unity, gnome-shell and xubuntu on my laptop. They all have their favorite preinstalled programs it seems. Do I really need three text editors for example? Could I remove two and just have the other desktops use the one I keep? It seems as though I could get rid of all video playback programs as well and just use vlc for example. Am I going to mess something up? I am new to all this.

A: I would be careful with removing seemingly superfluous programs. Other packages, even unrelated ones coming with the DE might depend on them. On LXDE for instance you can't remove lxterminal (≙ gnome-terminal) or leafpad (≙ gedit) without deleting essential packages such as lxrandr, lxinput and other ones.
Save for these dependency issues there is no reason why you shouldn't be able to remove  duplicate applications. Just make sure that you can configure the DE to use a replacement of your choice, e.g. gnome-calculator instead of galculator.
If it's not the wasted disk space that bothers you, but clutter in the respective DEs menus, you can always add the OnlyShowIn= parameter to the application launchers in question. See here for a tutorial on Kubuntu entries.


text:
Q: How do I pass arguments while loading any modules in typescript? I have a module in typescript which contains the following code.
export class Account {
constructor(app: any) {
    this.initialize(app);
  }

private initialize(app: any) {
    app.get("/login", (req: any, res: any) => {
        res.render("index", { user: req.user });
    });

    app.get("/logout", (req: any, res: any) => {
        res.render("index", { user: req.user });
    });
}

}
And I want to load this module in main file. like
require('/mymodule')(app)
How I can do this in typescript ?

A:
require('/mymodule')(app)

Proper way:
import {Account} from './mymodule';
new Account(app);

More
Just some free docs

*

*Read up on classes : https://basarat.gitbook.io/typescript/docs/classes.html

*Read up on modules : https://basarat.gitbook.io/typescript/docs/project/modules.html


text:
Q: gearman works very slow with out of memory gearmand version 1.1.18 (latest) works very slow when free RAM runs out. I have 64 GB RAM on server and when gearman use all free memory and goes to 1mb of swap - gearmand starts to work very-very slowly. Adding any task to background que can take up to 10 seconds.
Removing task from que can take up to 30 seconds.
Que more than 10 000 000 jobs.


text:
Q: yii2 frontend and backend not working on shared server We had build one project in yii2. It is working fine on local server. But it not working on shared server. I tried lot in htaccess but still not working for me.It gives me 500 internal server error
Frontend htaccess :
RewriteEngine on

# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php

Backend htaccess
RewriteEngine on

# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php

How can i solve this problem ?

A: Probably the server does not support 16-bit .php files.
Some editors (such as Notepad on Windows) will always add a byte-order mark (BOM) when you save a file as UTF-8, so make sure you use a text editor where you can save the file without the BOM.
I had exactly the same problem and it took me ages to debug the problem because the text in both formats looks identical when viewed.
The problem is quite a show-stopper when using session_start() because the file must begin with


text:
Q: jQuery: really simple self-made infinite scroll I know there are multiple plugins out there however I wonder how I can make my own thing work the way I want.
First off, when scrolling to the bottom of my page I want to trigger a function called ajaxLoadActivity which is now triggered with a "Show More" button.
$(window).scroll(function() {

            if ( $(window).scrollTop() >= ( $(document).height() - $(window).height() ) )

                if ( $('ol.astream > .loadCount:last > li').attr('id') == "noMoreActivities" )
                    return false;

                ajaxLoadActivity('bottom', true);
                console.log('fired');

        });

I have the problem that probably everybody encounters when trying to do this himself. The problem is that the function is fired multiple times. The function ajaxLoadActivity does all the ajax stuff and appends <li> items to an existing <ol>. The function works perfect when just using it with the "Show More" Button.
However I wonder how I can trigger the same function when simply scrolling to the bottom of the page. But I want to call it only once - then wait till the stuff is loaded - and only then allow the function to be fired again if the bottom is reached again.
And I have an exception that is already in my sample code above … if my last element has an id of noMoreActivities I don't want the function to be fired again, because then there are no more activities.
Any ideas how I can fire the function only once and wait till the request happend?

A: Assuming you're using $.post you can return it in your ajaxLoadActivity function then check to see if it's running
var ajax;

$(window).scroll(function() {

    if ( $(window).scrollTop() >= ( $(document).height() - $(window).height() ) )

        if ( $('ol.astream > .loadCount:last > li').attr('id') == "noMoreActivities" )
            return false;

        if (ajax) {

            return false; // don't make another request, let the current one complete, or
            // ajax.abort(); // stop the current request, let it run again
        }

        ajax = ajaxLoadActivity('bottom', true);
        console.log('fired');

});

function ajaxLoadActivity(one, two) {

    return $.post(/* stuff */);
}

A: $(window).scrollTop() == ( $(document).height() - $(window).height() ) will make it execute the call only once. Try it.


text:
Q: Expression is not assignable error when comparing two nodes I have an object of type ControlPointNode that derives from an abstractNode that itself derives from SKSpriteNode and I have the following code:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

//we look at teh number of touches
for (UITouch *touch in touches)
{

    ...

        _positionInScene = [touch locationInNode:self];

        SKSpriteNode * touchedNode = (SKSpriteNode *)[self nodeAtPoint:_positionInScene];

      ...

                for (ControlPointNode *controlPoint in _controlPointsVector) {

                    if (controlPoint.position.x = touchedNode.position.x){

                      // do something
                    }
   …

The problem is that I receive an error message saying Expression is not assignable in the line:
if (controlPoint.position.x = touchedNode.position.x){
Can anyone help with a solution to this error, please?

A: Should be
if (controlPoint.position.x == touchedNode.position.x){

because
if (controlPoint.position.x = touchedNode.position.x){

tries to assign controlPoint.position.x to touchedNode.position.x instead of comparing them.
As side note: If you'll really want to assign controlPoint.position.x to touchedNode.position.x somewhere, it won't work and you'll have to use controlPoint.position = CGPointMake(touchedNode.position.x, controlPoint.position.y).


text:
Q: Understanding "back button's" behaviour on Android I'm new at Android programming so I want to ask about Android's behaviour.
I'm using baseadapter with ListView. So at first, I show "a.xml"'s content at ListView.
Then, when I clik an Item, it shows "b.xml"'s content at same Listview.
At that point, when I click "back button", app is closing. But what I want is, turn back to "a.xml"'s content.
Is this possible? Or should I make this contents with "Activity" and create "b.xml" in a new acitivity?
Regards.

A: By default, back button closes the Activity in which is located. I advise you to open the detail content of the item of the ListView in a new Activity. What you want to achieve is doable, but I think you should learn to walk before learning to run.


text:
Q: Python Zipfile writes full path to file I am making a zipfile in Python 3 like this:
zf = zipfile.ZipFile("/path/to/zipfile.zip", mode='w')
try:
    zf.write("/path/to/original.file")
finally:
    zf.close()

However, when I unzip it, I get this structure:
path
└── to
    └── original.file

How can I resolve this?

A: import os
import zipfile
zf = zipfile.ZipFile("/path/to/zipfile.zip", mode='w')
try:
    os.chdir("/path/to/original file folder")
    zf.write("original.file")
finally:
    zf.close()


text:
Q: TypeError: 'float' object is not callable after printing a calculation I am writing a program that uses a class to calculate the circumference of an ellipse.  I have checked my parenthesies, I have declared my object, but the a type error keeps on coming up and I do not know why.
When I run it, it returns this error:
Traceback (most recent call last):
  File "C:\workspace.py", line 16, in <module>
    value.Ramanujans()
  File "C:\workspace.py", line 8, in Ramanujans
    print(math.pi() * 3 * (self.x + self.y) - math.sqrt((3 * self.x + self.y) * (self.x + 3 * self.y)))
TypeError: 'float' object is not callable

If someone could give a pointer, whether it be that I am not using the class function properly or have not done the arithmetic correctly, that would be lovely.

A: The error is quite telling: math.pi is a float (just a number), not a function. math.pi() tells python to call a function called math.pi, but since math.pi is not callable, an error is thrown. Drop the parentheses and you should be fine.


text:
Q: react-router: only mount layout when needed I have the following use case:
Most of the routes in my application have a classic layout component, but some routes should be rendered as some kind blank pages (without navigation and stuff like that).
My current router looks like this:
<Routes>
  <Route element={<MainPage />}>
    <Route path={"/whatever"} element={<AnyPage />} />
    {/* ... regular routes */}
  </Route>
  <Route element={<BlankPage />}>
    <Route path={"/special-route"} element={<SpecialPage />} />
    {/* ... other special routes */}
  </Route>
</Routes>

My MainPage component contains a navigation that requires fetching additional data (to display badges and stuff like that). Now, I don't want this component to be rendered when the user is on a special route.
So, my question is, if/how we can use layout components with react-router that are only rendered, when they are needed? I understand and want that the layout component keeps its state when navigating between routes that use this layout, but I don't want the layout to be rendered, when it has never been used.
I hope my problem is clear. Thanks for any suggestions or links.


text:
Q: SSRS Subscription Parameter Performance I have a report that has ~30 parameters. Most of these are query based, and all queries take less that a second to run. However, when trying to create a Subscription from Reports Manager, the page will become unresponsive trying to load all of the parameter options. We have looked into both the report server db and the data source that the report is based upon and nothing is slow or hanging, thus it seems like report manager is just having a hard time with so many parameter options being loaded. Running the report is actually faster than trying to build a subscription, which doesn't make much sense as the queries should be the same.
Are there any settings that can be edited for the report server config files to try to speed up this performance? We are running SSRS 2016.


text:
Q: SHDeleteKey Function I am having one Delphi XE2 Project for Windows Registry Operation. I need to delete all subnodes under **HKEY_CLASSES_ROOT\CLSID\{00000000-0000-0000-0000-000000000001}** , so I have defined the following codes :
function SHDeleteKey(key: HKEY; SubKey: PWideChar): Integer; stdcall; external 'shlwapi.dll' name 'SHDeleteKeyW';
..
..
..
..
..
procedure TMainForm.BitBtn02Click(Sender: TObject);
var
  RegistryEntry : TRegistry;
begin
  RegistryEntry := TRegistry.Create(KEY_READ or KEY_WOW64_64KEY);
  RegistryEntry.RootKey := HKEY_CLASSES_ROOT;
  if (RegistryEntry.KeyExists('CLSID\{00000000-0000-0000-0000-000000000001}\')) then
    begin
      Memo01.Font.Color := 3992580;
      Memo01.Lines.Add('Windows Registry Entry Has Been Found In Your System');
      RegistryEntry.Access:= KEY_WRITE or KEY_WOW64_64KEY;
      SHDeleteKey(HKEY_CLASSES_ROOT, PWideChar('CLSID\{00000000-0000-0000-0000-000000000001}'));
      RegistryEntry.CloseKey();
      RegistryEntry.Free;
      Memo01.Font.Color := 16756480;
      Memo01.Lines.Add('Windows Registry Entry Has Been Deleted Successfully');
    end
  else
    begin
      Memo01.Font.Color := 7864575;
      Memo01.Lines.Add('Windows Registry Entry Has Not Been Found In Your System');
    end;
end;

But nothing is happening. Then I have tried
function SHDeleteKey(key: HKEY; SubKey: PChar): Integer; stdcall; external 'shlwapi.dll';

but here is another problem is telling "Entry Point not found".

A: Your function import is failing because the function is named SHDeleteKeyW where the W specifies that you want to use Unicode characters. So your function declaration should be
function SHDeleteKey(hKey: HKEY; pszSubKey: PWideChar): Integer; stdcall;
    external 'shlwapi.dll' name 'SHDeleteKeyW';

Once that is fixed, the two most common failure modes are:

*

*Your process does not have admin rights.

*Your process runs in a 32 bit process on a 64 bit system and so cannot see the 64 bit view of the registry.

Based on your earlier question, option 2 seems most likely.
You said "nothing is happening", but I'm sure something is happening. The function is failing and returning an error status to you. But you did not check the return value of the call to SHDeleteKey. Whenever you call a Windows API, check the return value. If it fails, the return value allows you to diagnose that failure.
Assuming the issue is the registry redirector for your 32 bit process, your options include:

*

*Run the code from a 64 bit process.

*Use RegDeleteTree.

*Empty the key's subkeys first, and then use TRegistry.DeleteKey.

Note that the code where you specify KEY_WOW64_64KEY only has effect when using the TRegistry methods. Since SHDeleteKey is a Windows API function, it is independent from that class.

A: For your second problem, you may want to try ShDeleteKeyW instead (explicitly selecting the wide string variant).
In both cases, however, you should check the result to see why it failed.
You don't mention what O/S this is on but there appears to be several platform-specific quirks with this function as can be seen in the comments here.


text:
Q: A href and url problems I have this weird URL problem using html href attribute. By the way I'm using laravel.
I'll give you an example let's say I have this code in my website
 and my current URL is localhost/example/example
And instead of adding link to my address like this localhost/example/example/link1 it just adds it like this localhost/example/link1 basically it removes goes one link back
I tried using  instead but it just removes all path like this localhost/link1
I tried searching what's the problem but I cannot find anything. I tough maybe it had to do something with .htaccess or laravel urls but I have no idea how to solve this(or maybe it has to do something with Apache). I just need that it would add links normally to URL.
Also i can't use laravel URL::request because i'm using JavaScript to generate dynamic content.
Thank you

A: http://localhost/ is your domain.
If you are at http://localhost/example/, , should point to your domain + link1
If your application is in /example/, I recommend you have a look a the base tag:
http://www.htmlquick.com/reference/tags/base.html
So, supposing you have the following base tag because your application is in /example/:
<base href="http://localhost/example/">
That will make http://localhost/example/, the base for your links and forms.
 will open to http://localhost/example/link1
<form method="post" action="link2"> will post to http://localhost/example/link2
Have a look at how links work in HTML:
http://www.w3.org/TR/REC-html40/struct/links.html

A: Try using
URL::to('someseg/otherseg')

A: This behavior is controlled by the base element in the head of your HTML page.  You can retrieve this value with JavaScript (document.getElementsByTagName("base")[0].href).  If you also retrieve the relevant portion of the page URL (window.location.pathname), you can do something with those two values to change the links to behave how you expect.
Simply changing the links to absolute by prepending window.location.pathname + "/" to them would work.


text:
Q: Delete regex matches within loop and continue with updated string version I have a string that I want to run through four wordlists, one with four-grams, one with tri-grams, one with bigrams and one with single terms. To avoid that a word of the single term wordlist gets counted twice when it also forms part of a bigram or trigrams for example, I start with counting for four-grams, then want to update the string in terms of removing the matches to only check the remaining part of the string for matches of trigrams, bigrams and single terms, respectively. I have used the following code and illustrate it here just starting with fourgrams and then trigrams:
financial_trigrams_count=0
financial_fourgrams_count=0

strn="thank you, john, and good morning, everyone. with me today is tim, our chief financial officer."

pattern_fourgrams=["value to the business", "car and truck sales"]
pattern_trigrams=["cash flow statement", "chief financial officer"]

for i in pattern_fourgrams:
    financial_fourgrams_count=financial_fourgrams_count+strn.count(i)

new_strn=strn
def clean_text1(pattern_fourgrams, new_strn):
    for r in pattern_fourgrams:
        new_strn = re.sub(r, '', new_strn)
    return new_strn

for i in pattern_trigrams:
    financial_trigrams_count=financial_trigrams_count+new_strn.count(i)

new_strn1=new_strn
def clean_text2(pattern_trigrams, new_strn1):
    for r in pattern_trigrams:
        new_strn1 = re.sub(r, '', new_strn1)
    return new_strn1

print(financial_fourgrams_count)
print(financial_trigrams_count)
word_count_wostop=len(strn.split())
print(word_count_wostop)

For fourgrams there is not match, so new_strn will be similar to strn. However, there is one match with trigrams ("chief financial officer"), however, I do not succees in deleteing the match from new_strn1. Instead, I again yield the full string, namely strn (or new_strn which is the same).
Could someone help me find the mistake here?

A: (As a complement to Tilak Putta's answer)
Note that you are searching the string twice: once when counting the occurrences of the ngrams with .count() and once more when you remove the matches using re.sub().
You can increase performance by counting and removing at the same time.
This can be done using re.subn. This function takes the same parameters as re.sub but returns a tuple containing the cleaned string as well as the number of matches.
Example:
for i in pattern_fourgrams:
    new_strn, n = re.subn(r, '', new_strn)
    financial_fourgrams_count += n

Note that this assumes the n-grams are pairwaise different (for fixed n), i.e. they shouldn't have a common word, since subn will delete that word the firs time it sees it and thus won't be able to find occurence of other ngrams containing that particular word.

A: you need to remove def
import re
financial_trigrams_count=0
financial_fourgrams_count=0

strn="thank you, john, and good morning, everyone. with me today is tim, our chief financial officer."

pattern_fourgrams=["value to the business", "car and truck sales"]
pattern_trigrams=["cash flow statement", "chief financial officer"]

for i in pattern_fourgrams:
    financial_fourgrams_count=financial_fourgrams_count+strn.count(i)

new_strn=strn
for r in pattern_fourgrams:
    new_strn = re.sub(r, '', new_strn)

for i in pattern_trigrams:
    financial_trigrams_count=financial_trigrams_count+new_strn.count(i)

new_strn1=new_strn
for r in pattern_trigrams:
    new_strn1 = re.sub(r, '', new_strn1)

print(new_strn1)
print(financial_fourgrams_count)
print(financial_trigrams_count)
word_count_wostop=len(strn.split())
print(word_count_wostop)


text:
Q: Replacing text in a Shell Script I am running the command
echo 'link_1234' | sed 's|_|&/|g'

And it is returns the value of link_/1234
I need the _ to be deleted
Is there any way to have the _ be cleared?

A: Just do:
echo 'link_1234' | sed 's|_||'

When you do:
echo 'link_1234' | sed 's|_|&/|g'

you are replacing _ with _/. sed keeps the searched pattern as & so that you an use it in replacement as a shorthand, as your searched pattern is _ and replacement is &/, you are replacing _ with _/.
About the g modifier at the end, it is useful when there are more than one match and you want to do the replacement on all of them, as there is only one _ so g is redundant here.


text:
Q: Inject parameters to entity I encounter this issue a lot of times, but only until now do I want to learn the best way to do it.
Say I have an Image entity, it has a 'path' property, which stores the relative path to the image file. For example, an image has its 'path' as '20141129/123456789.jpg'.
In parameters.yml, I set the absolute path to the directory that stores image files. Like this:
image_dir: %user_static%/images/galery/

I want to add the method 'getFullPath()' to Image entity, inside which the 'image_dir' parameter will be concatenated with 'path' property. I don't want to do the concatenation in controllers because I will be using it a lot. Also I don't want to insert image dir into Image's 'path' property, because I may change the image dir path later (which means I'll have to update the 'path' of all images in database).
So how can I inject the parameter into Image entity, so that getFullPath() can use it? Since Image entities will be fetched by repository methods instead of creating a new instance of Image, passing variables to construction method won't work.
Or is there a more elegant approach? I just want Image entities to have getFullPath() method, and I will be fetching images via both repository methods (find, findBy...) and query builder.

A: You could listen to the doctrine postLoad event and set the image directory in that so that when you later call getFullPath() it can return the concatenated string of the image directory and the path.
postLoad listener
namespace Acme\ImageBundle\Doctrine\EventSubscriber;

use Acme\ImageBundle\Model\ImageInterface;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;

class ImageDirectorySubscriber implements EventSubscriber
{
    protected $imageDirectory;

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

    public function getSubscribedEvents()
    {
        return array(
            Events::postLoad,
        );
    }

    public function postLoad(LifecycleEventArgs $args)
    {
        $image = $args->getEntity();

        if (!$image instanceof ImageInterface) {
            return;
        }

        $image->setImageDirectory($this->imageDirectory);
    }
}

services.yml
parameters:
    acme_image.subscriber.doctrine.image_directory.class:
            Acme\ImageBundle\Doctrine\EventSubscriber\ImageDirectorySubscriber

services:
    acme_image.subscriber.doctrine.image_directory:
        class: %acme_image.subscriber.doctrine.image_directory.class%
        arguments:
            - %acme_image.image_directory%
        tags:
            - { name: doctrine.event_subscriber }

Image Model
class Image implements ImageInterface
{
    protected $path;

    protected $imageDirectory;

    .. getter and setter for path..

    public function setImageDirectory($imageDirectory)
    {
        // Remove trailing slash if exists
        $this->imageDirectory = rtrim($imageDirectory, '/');

        return $this;
    }

    public function getFullPath()
    {
        return sprintf('%s/%s', $this->imageDirectory, $this->path);
    }
}

A: An alternative to @Qoop's approach is to make an image manager service and do the path stuff in it.  The code will be a bit simpler.
class ImageManager
{
    public function __construct($imageDirectory)
    {
        $this->imageDirectory = $imageDirectory;
    }
    public function getFullPath($image)
    {
        return $this->imageDirectory . $image->getPath();
    }
}

// Controller
$imageManager = $this->get('image_manager');

echo $imageManager->getFullPath($image);

It's a trade off.  Explicitly managing images vs using "behind the scenes" events.