text:
Q: How to correct add domain to a field inside a one2many field in Odoo? I created a model Version, add a relation to the product model like this:
class product_template(models.Model):
    _inherit = 'product.template'

    versions_ids = fields.Many2many('mymodel.version',string='Versions')

class sale_order(models.Model):
    _inherit = 'sale.order'

    version_filter = fields.Many2one('mymodel.version')

I add a field "version_filter to the sale.order view, and now want to filter product search by this relation, but only the ones being adding not the previous ones addded
Like this:
<record id="sale_filter_append" model="ir.ui.view">
    <field name="name">sale.order.form</field>
    <field name="model">sale.order</field>
    <field name="inherit_id" ref="sale.view_order_form"/>
    <field name="arch" type="xml">
        <xpath expr="//field[@name='order_line']" position="before">
            <group colspan="4">
                <field name="version_filter"/>
            </group>
        </xpath>
        <xpath expr="//field[@name='product_id']" position="replace">
            <field name="product_id"
                   context="{'partner_id':parent.partner_id, 'quantity':product_uom_qty, 'pricelist':parent.pricelist_id, 'uom':product_uom, 'company_id': parent.company_id}"
                   attrs="{'readonly': ['|', ('qty_invoiced', '>', 0), ('procurement_ids', '!=', [])]}"
                   domain="[('version_filter', 'in', versions_ids)]"
            />
        </xpath>
    </field>
</record>

But the "product_id" field is never replace.
I would rather make a modal form as in "Search more" option in many2one fields... but if someone could help me filter by domain the order_line product_id search its more than ok
Thanks for reading!

A: Problem is there with the xpath. You should try following.
If you want to add domain in sales order line -> product_id in form view and tree view both then the example is given below.
<xpath expr="//notebook/page[@string='Order Lines']/field[@name='order_line']/form/group[1]/group/field[@name='product_id']" position="attributes">
    <attribute name = "domain">Add your domain</attribute>
</xpath>

<xpath expr="//notebook/page[@string='Order Lines']/field[@name='order_line']/tree[@string='Sales Order Lines']/field[@name='product_id']" position="replace">
    <field name="product_id" context="{'partner_id':parent.partner_id, 'quantity':product_uom_qty, 'pricelist':parent.pricelist_id, 'uom':product_uom, 'company_id': parent.company_id}"
        attrs="{'readonly': ['|', ('qty_invoiced', '>', 0), ('procurement_ids', '!=', [])]}"
        domain="[('version_filter', 'in', versions_ids)]" />
</xpath>


text:
Q: Why is this htaccess rule assigning two matches to one $_GET variable? Here's the htaccess rule for my site's profile page:
RewriteRule ^users/([0-9]+)/?(.+)?/?(.+)? profile.php?id=$1&slug=$2&tab=$3&%{QUERY_STRING}

When you click on a tab on a user's profile, such as favorites:

/users/83028/nathan-johnson/favorites

The $_GET variable with the name of slug is receiving nathan-johnson/favorites instead of just nathan-johnson and the tab variable is blank, according to a var_dump:
array(3) {
      ["id"]=> string(5) "83028"
      ["slug"]=> string(24) "nathan-johnson/favorites"
      ["tab"]=> string(0) "" }

It looks like the issue is with my htaccess regexp (above), but I don't see the issue with it.
Thanks in advance.

A: Because your forward slashes are optional (via /?), the (.+) grouping is greedy and will gobble them all up. You need to make them non-greedy by adding a ?:  (.+?)
Also, instead of (.+)? you should just use a * which means none, one, or more.
Try:
RewriteRule ^users/([0-9]+)/?([^/]*)/?(.*?)?$ profile.php?id=$1&slug=$2&tab=$3&%{QUERY_STRING}

Also, instead of using %{QUERY_STRING}, you can just use the QSA flag:
RewriteRule ^users/([0-9]+)/?([^/]*)/?(.*?)?$ profile.php?id=$1&slug=$2&tab=$3 [L,QSA]

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve buildings polygon in Google Places near a given latitude longitude Given a latitude and longitude, google places api can be used to query for nearby places. But it seems to give only places marked as dots on the google map. I am interested in retrieving the buildings which are marked as grey polygons on google maps.

A: The Google Places API does not currently support this feature. If you believe this would be a useful feature you can submit a 'Places API - Feature Request' here: http://code.google.com/p/gmaps-api-issues/issues/entry?template=Places%20API%20-%20Feature%20Request
You could however in the mean time use a Rectangle or Circle overlay from the Google Maps API with an estimated building size at the Latitude and Longitude provided by the Places API.
http://code.google.com/apis/maps/documentation/javascript/overlays.html#BasicShapes


text:
Q: How do I make the default timestamp columns behave? I'm trying to force these columns to do two things:

*

*Use "timestamp without time zone" (the backend is Postgres).

*Actually set the default on the backend to "now/utc".
    {
        // a bunch of column definitions
        createdAt: { type: DataTypes.DATE, defaultValue: sequelize.fn('now') }
    },
    {
        timestamps: false,
        comment: "this isn't even the real comment"
    }

The results are this:
CREATE TABLE IF NOT EXISTS "common"."images" ("id" VARCHAR(255) , "imageType"
VARCHAR(255), "mimeType" TEXT, "source" VARCHAR(255), "path" TEXT UNIQUE,
"createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(), PRIMARY KEY ("id"));
COMMENT ON TABLE "common"."images" IS 'blah blah blah.';

However, I can't find any documentation on how I could force this to be a timestamp-without-tz, or how I can make the default "now() at time zone 'utc'".
Are either of these possible?
If they are possible, can it be done without setting timestamps to false and manually defining the column as I have done?

A: Apparently there is a fairly elegant solution for the second half of this question. Sequelize presents a "literal" method that allows you to (among other things) make a default value exactly as you like.
{
    // a bunch of column definitions
    createdAt: { type: DataTypes.DATE, defaultValue: sequelize.literal("(now() at time zone 'utc')") }
},

I wrap it in double quotes because Postgres wants single quotes around the "utc" on the back end.
Of course, Yuri is correct in that there are no "without time zone" data types in Sequelize, nor any option to configure the Data type that way. I know that partial answers are discouraged here, but thought this might help others.

A: When you set up your sequelize instance, you can set options.timezone to UTC which sets the timezone for all sequelize connections, meaning every NOW() call would be in UTC. This would work with the default timestamps too. See the docs: http://sequelize.readthedocs.org/en/latest/api/sequelize/
Alternatively, you could modify your postgresql.conf and default the timezone there.

A: You can use moment library for creating timestamp:
    createdAt: {
      type: DataTypes.NOW,
      allowNull: false,
      defaultValue: moment.utc().format('YYYY-MM-DD HH:mm:ss'),
      field: 'createdAt'
    },
    updatedAt: {
      type: DataTypes.NOW,
      allowNull: false,
      defaultValue: moment.utc().format('YYYY-MM-DD HH:mm:ss'),
      field: 'updatedAt'
    }

Also, you can enable the timestamps as true in the model config to automatically update the timestamp whenever you create the row in DB.
  const orderDetails = sequelize.define('orderDetails', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      field: 'id'
    },
    itemId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      field: 'item_id'
    }
    quantity: {
      type: DataTypes.FLOAT,
      allowNull: false,
      field: 'quantity'
    },
    itemDescription: {
      type: DataTypes.STRING(128),
      allowNull: false,
      defaultValue: ' ',
      field: 'item_desc'
    },
    createdAt: {
      type: DataTypes.NOW,
      allowNull: false,
      defaultValue: moment.utc().format('YYYY-MM-DD HH:mm:ss'),
      field: 'createdAt'
    },
    updatedAt: {
      type: DataTypes.NOW,
      allowNull: false,
      defaultValue: moment.utc().format('YYYY-MM-DD HH:mm:ss'),
      field: 'updatedAt'
    },
  }, {
    tableName: 'order_details',
    timestamps: true,
  });


text:
Q: Skipped installing realm-cocoa.framework binary due to the error: when I try to add my dependencies using Carthage I got this error
*** Downloading realm-cocoa.framework binary at "v3.7.4"
*** Downloading RxSwift.framework binary at "Zürich"
***  Skipped installing realm-cocoa.framework binary due to the error:
    "Incompatible Swift version - framework was built with 4.1 (swiftlang-902.0.48 clang-902.0.37.1) and the local version is 4.1.2 (swiftlang-902.0.54 clang-902.0.39.2)."

    Falling back to building from the source
A shell task (/usr/bin/xcrun xcodebuild -workspace /Users/safoinemoncefamine/AppWink/carthage\ frameworks/Carthage/Checkouts/Alamofire/Alamofire.xcworkspace CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES -list) failed with exit code 72:
xcrun: error: unable to find utility "xcodebuild", not a developer tool or in PATH

this is my CartFile
github "Moya/Moya"
github "rs/SDWebImage"
binary "https://dl.google.com/dl/firebase/ios/carthage/FirebaseAdMobBinary.json"
binary "https://dl.google.com/dl/firebase/ios/carthage/FirebaseAnalyticsBinary.json"
github "SVProgressHUD/SVProgressHUD"
github "realm/realm-cocoa"


text:
Q: How to route traffic from a VirtualBox VM only over a VPN? I've got a VirtualBox VM (both host & guest Ubuntu Maverick). My VPN provider uses OpenVPN to setup TUNs. I'd like to set things up so that traffic from the VM only goes over the VPN and is just dropped if the VPN goes down (it's happened). Suggestions? My iptables-fu is  a little weak
What I've tried: using VirtualBox's "host-only networking" which gives you a vboxnet0 loopback interface on the host to the guest, but couldn't get the iptables/routes right.  I'd like to avoid NAT on VM, as I'm already double NAT'd (ISP & home router) and one more level will make my head pop.
Other possibilities: switching to TAP (how?) and bridging to VM. Creating VPN inside VM and filtering all eth0 traffic except VPN connect with iptables (but see below)
Bonus points: if you can tell me how to use different VPN exit points on host & guest without double-tunneling traffic from guest through the host's VPN.

A: There will be other solutions, but this is what I'm thinking:

*

*Setup the VM in bridge mode. This will give your virtual machine an IP address in the same network as your host.

*Setup the VPN on the host, let's say it's tun0.

*Enable routing on the host echo 1 > /proc/sys/net/ipv4/ip_forward

*Setup the VM with the host IP address as the default gw.

At this point, the host has the VPN connection, and the VM will route all traffic to the host. All that is left to do is restrict the host so that it does not allow the guest to route any traffic that isn't going to go thru the tun0 device. You could do that with a set of iptables rules something like this:
iptables -P FORWARD DROP
iptables -A FORWARD -o tun0 -j ACCEPT
iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT

That should work. The first rule sets a default policy to DROP packets in the FORWARD chain. This only effects packets that your host would route, not packets to the host (INPUT) or from the host (OUTPUT). The second rule allows any traffic that is routing out tun0 - you could tighten that up with a --source if you wanted. And the last rule should let replies coming back from tun0 to route back to the VM.
Will your VPN be expecting all packets on the tun interface to be from a single IP? If so, you'll want to add a NAT rule as well. Probably something like:
iptables -t nat -A POSTROUTING -o tun0 -j SNAT --to-source {your host tun0 ip}


text:
Q: How to find which actual application uses port 80 via the System process TL;DR
An application is listening on TCP port 80, but the process listed when I run netstat or TcpView from the SysInternals tools is System. I want to know which application is really listening on this port.

I have read this question, and tried running netstat, but it didn't help finding the actual application which uses port 80. The PID it gave me was 4, which corresponds to System. If I try to open a browser on localhost:80, it only gives me a basic 404 page ("HTTP Error 404. The requested resource is not found.").
I tried using a simple HTTP request via telnet, and I got the following:
                       HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 28 Jul 2016 19:22:42 GMT
Connection: close
Content-Length: 334

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Hostname

HTTP Error 400. The request hostname is invalid.

Is there another way to find out which application is blocking my port 80 through the System process? I'm using Windows 7.
Update
Here's an extract of the output when I run netstat -anbo | findstr :80:
TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       4
TCP    0.0.0.0:8000           0.0.0.0:0              LISTENING       3900
TCP    0.0.0.0:8081           0.0.0.0:0              LISTENING       2876

And it's impossible to start our own HTTP server because port 80 is already in use.
Update2
We found out which application was using the port afterall (see my answer). However, I'm curious to see if anyone has a collection of tricks to speed up the process of finding which application uses a port in the case where it is using it via the System process (and not in the case where a virus is emulating the System process, as suggested by Steven).

A: We finally found the culprit. In our case, it was the BranchCache service. From what we learned, this service uses TCP port 80 by default, and our IT service didn't change the default configuration. Stopping this service freed the port 80.
We had to manually stop every services on our computer, until we found the service which actually used port 80. This can lead to weird behaviors though, so I'm not fully sure this is the best way to get the information.

A: If you download the Sysinternals Suite from Microsoft and extract it to somewhere, start the tool TCPCon.exe (or TCPMon) This will ist all the services and processes including PID and tons of other information. If the service is not self-explanatory, upload it to virustotal.com

A: Run the command;
netsh http show servicestate view=requestq
This will give snapshot of all the HTTP listeners. Find the "Registered URL" containing the port number you are looking for and the PID of the controlling process will be a few lines above it, like my own rogue process here;
Request queue name: Request queue is unnamed.
    Version: 2.0
    State: Active
    Request queue 503 verbosity level: Basic
    Max requests: 1000
    Number of active processes attached: 1
--> Process IDs:
        14035
    URL groups:
    URL group ID: F80000014000004F
        State: Active
        Request queue name: Request queue is unnamed.
        Properties:
            Max bandwidth: inherited
            Max connections: inherited
            Timeouts:
                Timeout values inherited
            Number of registered URLs: 1
-->         Registered URLs:
              HTTP://+:8081/ROGUESERVICE/
        Server session ID: F70000011000012D
            Version: 2.0
            State: Active
            Properties:
                Max bandwidth: 4294967295
                Timeouts:
                    Entity body timeout (secs): 120
                    Drain entity body timeout (secs): 120
                    Request queue timeout (secs): 120
                    Idle connection timeout (secs): 120
                    Header wait timeout (secs): 120
                    Minimum send rate (bytes/sec): 150

A: I had the same issue, and found my Windows 10 System was running IIS Web Server. I knew that was a possible suspect, but had a hard time finding it. It was in Administrative Tools > Services > World Wide Web Publishing Service.

A: This is what is using the port: C:\Windows\system32\svchost.exe -k iissvcs, and
I had to disable its startup type in services.msc.


text:
Q: Python, slicing lists? i really need your help with slicing a list.
lets say I've got a list of lists like this:
field=[[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]

and I have to write a function which will return a string that will look like this:
42334
44423
21142
14221

thus fat i managed to do this:
def out(field):
    b=''
    for list in field:
        list1=list[::-1]
        b+=''.join((str(sth) for sth in list1))+'\n'
    return b

which returns this:
4421
2414
3412
3242
4321

A: You need to transpose your list of rows to a list of columns, as well as reverse the results of the transposition to get a proper rotation.
zip(*field) transposes the rows to columns, reversed() then reverses the results. Combined with a list comprehension you can do this all in one expression:
def out(field):
    return '\n'.join([''.join(map(str, c)) for c in reversed(list(zip(*field)))])

or spelled out into an explicit loop:
def out(field):
    b = []
    for columns in reversed(list(zip(*field))):
        b.append(''.join(map(str, columns)))
    return '\n'.join(b)

The list() call around the zip() call allows us to reverse the iterator result in Python 3; it can be dropped in Python 2.
Demo:
>>> field=[[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
>>> [''.join(map(str, c)) for c in reversed(list(zip(*field)))]
['42334', '44423', '21142', '14221']
>>> '\n'.join([''.join(map(str, c)) for c in reversed(list(zip(*field)))])
'42334\n44423\n21142\n14221'
>>> print('\n'.join([''.join(map(str, c)) for c in reversed(list(zip(*field)))]))
42334
44423
21142
14221

A: def out(field):
    b=''
    a=[]
    while len(field[0])>0:
        for list in field:
            a.append(list.pop())
        a.append("\n")
    a="".join(str(x) for x in a)
    return a
x=[[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
print out(x)


text:
Q: Why regular module import routing module instead of reverse I'm confusing  why NomalModule import the NormalRoutingModule instead of   NormalRoutingModule  import NomalModule  . for example a angular project normally create like this
app.module.ts  --> AppModule --> import AppRoutingModule
app.routing.module.ts --> AppRoutingModule
my.module.ts ----> MyModule  ---> import MyRoutingModule
my.routing.module.ts->  MyRoutingModule

From what I think, it'll be more flexiable if the routing module import normal module .
should the AppRoutingModule import AppModule and MyRoutingModule import MyModule  so the component of Url is relate to routing module , and the MyModule can be reuse without create duplicate url .
for example :
My2Module use a compoent from MyModule, and My2Module has it's own url routing ,  it will be two set of url for My2Module if MyModule import MyRoutingModule. and it'll be ok if MyRoutingModule import MyModule because MyModule won't contains routing any more.


text:
Q: Secrets in databricks I created a secret on databricks using the secrets API.
Code :
Scope_name : {"scope": "dbtest", "initial_manage_principal":"user"}
Resp= requests.post('https://instancename.net/mynoteid/api/2.0/secrets/scopes/create',json=Scope_name)

Similar way, I added the user and password
Code:
Content = {"scope":"dbtest","key":"user","string_value":"Vidyasekar"}
requests.post('https://instancename.net/mynoteid/api/2.0/secrets/put', json=content)

After the execution I got response : <Response [200]>
Which means secrets stored successfully.
While listing the same using the list API call or dbutils.secrets.get(), its shows 'Secret does not exist with scope
Here my doubt is,
How to get the databricks intance name?
Where the secrets stored in the DBFS location?

A: The creation of a secret scope (sample on Azure) in python would look like this:
import requests
import json

# Set authorization token (token is generated in user settings)
hdr = {"authorization": "Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}

x = json.dumps({'scope': 'lab-a-adls'})

r = requests.post("https://westeurope.azuredatabricks.net/api/2.0/secrets/scopes/create",
    headers = hdr,
    data= x)

Store a credential in the scope via:
x = json.dumps({
  "scope": "lab-a-adls",
  "key": "credential",
  "string_value": "*******************************"
})

 r = requests.post("https://westeurope.azuredatabricks.net/api/2.0/secrets/put",
    headers = hdr,
    data= x)


text:
Q: How does covering ally works in Final Fantasy Brave Exvius? I have a team of Ramza, Elza, Cecil, ExDeath, Minfilia.
For some reason, during my fight with Titan (the Raid Boss), Cecil would 90% of the time cover Ramza instead of Minfilia or ExDeath whose defense and HP are lower than Ramza. Why is this? How to make Cecil cover ExDeath or Minfilia instead of Ramza?
Ramza
Lv 100
HP 4343
Elza
Lv 100
HP 5122
Cecil
Lv 100
HP 4552
ExDeath
Lv 100
HP 3513
Minfilia
Lv 59~
HP 2929
Tell me if more information are needed.

A: Quoting the wiki http://exvius.gamepedia.com/Cover

When more than 1 unit are attacked at the same time, the chance to
  protect party member is based on the order of the party, with
  left-most unit having the highest chance.

Cover only blocks physical attacks, but if you enhance Golem to have provoke, you could make it more likely for the enemy to attack your tank and can still use cover if needed.
Edit: in case you aren't sure, left-most refers to before you go into battle. That person will be your top left character, but if that's your tank, he's more likely to cover the person below him (second from left).


text:
Q: How many Apple IDs should one household have? To date my wife and I share one Apple ID for all Apple purchases and devices. We currently own a first and third generation iPod, iPhone 4, and will own an iPad 2 in the morning. Thus far having the one account has not been an issue, but with more Apple purchases to follow at what point does it make sense to have more than one Apple ID? What are the advantages and disadvantages of having one or multiple accounts? If we each had an iPhone would multiple Apple IDs be required? What's the relation to iCloud?

A: FaceTime can't be used to call each other on the same iTunes account, for this reason alone you must have a separate apple ID to make use of this great tool.

A: Check out this excellent FAQ from Apple on Apple IDs and iCloud: http://support.apple.com/kb/HT4895
Of particular interest are the sections:

*

*Using the same Apple ID for Store purchases and iCloud (recommended)

*Using one Apple ID for iCloud and a different Apple ID for Store
Purchases

A: There is no limit and having more is not necessarily better. Having all your devices registered under one Apple ID has the benefit of having all your purchases pushed to them without having to manage multiple accounts. So your wife can enjoy an app on her iPhone 4 just the same as you can enjoy the same app on your iPad 2, without needing to purchase the app a second time (once for each device), or constantly logging in and out of various Apple IDs to install and update.
I find it is always better to pool your purchases to one account and register your devices under that single account. Having multiple Apple IDs requires that one micro-manage each account (iTunes will only check for updates for the current Apple ID), which can be bothersome at the best of times and a nightmare at the worst of times.
One advantage of having separate Apple IDs, however, is that each account belongs to its respective owner and can be registered to their own payment methods. But if you share your finances, that is of little value to you.
iCloud is bound to its respective Apple ID, so if you have just the one, all the features of iCloud would permeate through any device registered to that account. That means if you downloaded an app on your iPad 2, it would appear on your wife's iPhone 4. You would also share documents, pictures, music, etc. (anything supported by iCloud and expressly enabled by you) across all your devices as well—email as well. iCloud would essentially unify them and their content.
Multiple Apple IDs are not required. You may also find this article on managing multiple devices (although somewhat dated when iCloud launches).

A: I actually think multiple ids are a good idea.  I too assumed that if I bought an app from one account the other account would not be able to use the app.  But if you sync the app from the same iTunes installation (Windows7 for me).  The paid app works on all the iOS devices. Facetime & Messages are also a great reason to have multiple accounts.

A: You can use one Apple ID for FaceTime across multiple devices that have distinct Apple ID for app purchase. I can contact my son's iPod Touch with my iPhone using the same ID, all I did was change what email I can contact him on because it's not a phone (gmail). Works perfect for us with no confusion.


text:
Q: python does not solve an ode system properly I have an ODE which I need to solve and plot. This is my code so far:
import numpy as np
import math
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
from scipy import integrate

##############################
# Constants
#α = 1,β = 12,μ = 0.338,Vb = 0.01,ω = 0.5,
alpha = 1#p1
beta = 12#p2
mu = 0.338#p3

omega = 0.5#p5
gamma = 0.25#p6
Acoef=0.5
tmax = 1000
t = np.arange(0.0, tmax, 0.001)
################################
# Initial conditions vector

X0=0
I0=0
Z0=0.06
H0=0.04
E0=0
O0=0.02
# The  model differential equations.
def deriv(y,t):
    X, I, Z, H, E, O = y
    dXdt = I
    dIdt = -(alpha)*(X)-(beta)*(X**3)-(mu)*I+gamma*(1/(1-X)**2)-gamma*(1/(1+X)**2)+Acoef*(1/(1-X)**2)*(np.sin(omega*t))
    dZdt = H
    dHdt =-(alpha)*(Z)-(beta)*(Z**3)-(mu)*I+gamma*(1/(1-Z)**2)-gamma*(1/(1+Z)**2)+Acoef*(1/(1-Z)**2)*(np.sin(omega*t))
    dEdt=O
    dOdt=-(alpha)*(X)-(beta)*(X**3)-(mu)*I+gamma*(1/(1-X)**2)-gamma*(1/(1+X)**2)+Acoef*(1/(1-X)**2)*(np.sin(omega*t))-(-(alpha)*(Z)-(beta)*(Z**3)-(mu)*I+gamma*(1/(1-Z)**2)-gamma*(1/(1+Z)**2)+Acoef*(1/(1-Z)**2)*(np.sin(omega*t)))
    return dXdt, dIdt, dZdt, dHdt, dEdt,dOdt
# Initial conditions vector
y0 = X0,I0,Z0,H0,E0,O0
# Integrate the SIR equations over the time grid, t.
ret = odeint(deriv, y0, t)
X, I, Z, H, E, O = ret.T
# Plot the data on three separate curves for S(t), I(t) and R(t)
plt.xlim([-10, 10])
plt.plot(ret[:,4], ret[:,5])
plt.show()
e1=ret[:,4]
e2=ret[:,5]

Unfortunately, it produces the following warning:

File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\integrate\odepack.py", line 247
warnings.warn(warning_msg, ODEintWarning)
ODEintWarning: Excess work done on this call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative information.

And the result is not as expected. I cannot here post graphical result probably.
Does anyone know how I can fix it, please?


text:
Q: how can do slices in python similar to slices in praraview? For those who are familiar with paraview: in 3D case we can do slice and contour and visualize for example what it inside a sphere/cylinder/box.
I am wondering if there is any tool to do the same things in python? I mean if rather than reading a file in preview, I will read it in python, and obtain a 3D plot, which tool can I use to get slices and contours  in python plot similar to those in praview?

A: ParaView is also available through a python module, so what you do in the graphical interface is also doable in python.
See this introduction.


text:
Q: React-Router - Redirect if URL parameter not passed I want the redirect back to home if the params are not passed with the url.
How can I achieve this?
I tried something like this, but it`s not working:
export default function Summary() {
  const { id } = useParams();
  const navigate = useNavigate();
  if (!id) {
    navigate("/home");
  }

Thanks in advance

A: import {Redirect} from "react-router-dom"

if(!id){
return <Redirect to="/" />
}

A: I solved in in the router itself:
        <Route
          path={`${LocalRoutes.summary}/:id`}
          element={<Summary/>}
        />
        <Route path={LocalRoutes.summary} element={<Navigate to="/home" />} />


text:
Q: What (formal) language does this describe? And, how do I prove it's regular? I have this problem that I can't seem to be able to wrap my head around, and I was wondering if there was someone here that could help me understand it.
Let $L_1$ be a regular language over $\{a, b, c\}$. We define
$\qquad L_2 = \{xy \in \{a, b, c\}^∗ \mid xay \in L_1 \vee xby \in L_1\}$.
For example, if $L_1 = \{a, abc, c\}$, then $L_2 = \{\lambda, ac, bc\}$. Prove that $L_2$ is a regular language.
I really don't understand what language $L_2$ is in the first place, which makes it very hard for me to prove its regularity...
Any help would really be appreciated!

A: L2 is the set of words that can be formed by deleting exactly one $a$ (or exactly one $b$) from a word in L1.

A: If $L_1$ is regular there is a DFA $A$ accepting that language. Try to build another finite automaton from $A$ that is essentially the same but demands that exactly one $a$ or $b$ is "skipped" in any accepting run of $A$.
(Can you do it with this hint? If not, I can post details.)


text:
Q: Let atom editor recognize external APIs I'm trying to set up a python like environment with Atom-editor on a Linux machine.
I find the autocomplete-python package that uses jedi.
In the settings of the package I tried to add some python path where the APIs are (/usr/lib/python2.7/dist-packages/) but then the autocompletion doesn't recognize these libraries (for example the PyQt ones)
Am I missing something?

A: For anybody having the same issue please look here.
Basically everything should work out of the box, but if it does not -- try to configure path to python executable with which you have installed your external module. If it's still fails to complete -- try to configure extra path to python modules. (usually your site-packages directory)


text:
Q: Raspberry Pi communication hangs on accept() I have 2 raspberry pis I want to send some data between to initiate a function simultaneously on both of them, the connection between the two is an ethernet cable and neither is connected to the internet.
I am having an issue where my server code hangs once it hits accept. I've included both the server and client code. I am using the IP of the Pi running the server code in the client code. I believe it is an issue of either the client not sending the connection to the correct place or the server is not being told the correct location where to receive it.
The code is based on the example code here http://www.cs.rpi.edu/~moorthy/Courses/os98/Pgms/socket.html.
Server:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
//#include <opencv2/opencv.hpp>
#include <iostream>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <iterator>

using namespace std;

int main(int argc, char *argv[]){
     int sockfd, newsockfd, portno;
     printf("Sock \n");
     socklen_t clilen;
     printf("clilen \n");
     char buffer[256];
     printf("buffer \n");
     struct sockaddr_in serv_addr, cli_addr;
     printf("struct \n");
     int n;
     printf("n \n");

     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     printf("Sockfd \n");

     bzero((char *) &serv_addr, sizeof(serv_addr));
     printf("bzero \n");
     portno = 6666;
     printf("port \n");
     serv_addr.sin_family = AF_INET;
     printf("afinet \n");
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     printf("inadder any \n");
     serv_addr.sin_port = htons(portno);
     printf("htons \n");

     printf("listen \n");
     cout << listen(sockfd,5) << "\n";
     listen(sockfd,5);
     clilen = sizeof(cli_addr);
     cout << "&clilen: " << &clilen << "\n";
     cout << "clilen: " << clilen << "\n";

     newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
     printf("newsock \n");

     bzero(buffer,256);
     printf("bezero 2 \n");
     n = read(newsockfd,buffer,255);
     printf("read \n");
     printf("Here is the message: %s\n",buffer);

     n = write(newsockfd,"I got your message",18);
     printf("write \n");

     return 0;
}

Server Output:
Sock
clilen
buffer
struct
n
Sockfd
bzero
port
afinet
inadder any
htons
listen
0
&clilen: 0x7eeaaf0c
clilen: 16

Client code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
//#include <opencv2/opencv.hpp>
#include <iostream>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <iterator>

using namespace std;

int main(int argc, char *argv[]){
    int sockfd, portno, n;
    printf("sock \n");

    struct sockaddr_in serv_addr;
    printf("sockaddr \n");
    struct in_addr ipv4addr;
    printf("ipv4 \n");
    struct hostent *server;
    printf("hostent \n");

    char buffer[256];
    printf("buffer \n");

    portno = 6666;
    printf("port \n");
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    printf("sockfd \n");
    if (sockfd < 0)
        printf("ERROR opening socket");
    inet_pton(AF_INET, "169.254.59.109", &ipv4addr);
    printf("inet \n");
    server = gethostbyaddr(&ipv4addr, sizeof ipv4addr, AF_INET);
    cout << "server: " << server << "\n";
    printf("server \n");
    //if (server == NULL) {
        //fprintf(stderr,"ERROR, no such host\n");
        //exit(0);
    //}
    bzero((char *) &serv_addr, sizeof(serv_addr));
    printf("bzero \n");
    serv_addr.sin_family = AF_INET;
    printf("af \n");
    bcopy((char *)server->h_addr,(char*)&serv_addr.sin_addr.s_addr,server->h_length);
    printf("bcopy \n");
    serv_addr.sin_port = htons(portno);
    printf("htons \n");
    cout << "connect: " << (connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))) << "\n";
    cout << "sockfd: " << sockfd << "\n";
    cout << "struct: " << (struct sockaddr *)&serv_addr << "\n";
    cout << "serv: " << sizeof(serv_addr) << "\n";
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        printf("ERROR connecting\n");

    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    n = write(sockfd,buffer,strlen(buffer));
    printf("write \n");
    if (n < 0)
         printf("ERROR writing to socket");
    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    printf("read \n");
    if (n < 0)
         printf("ERROR reading from socket");
    printf("%s\n",buffer);
    return 0;
}

Client Output:
sock
sockaddr
ipv4
hostent
buffer
port
sockfd
inet
server: 0x76d3c5a4
server
bzero
af
bcopy
htons
connect: -1
sockfd: 3
struct: 0x7ea32ef0
serv: 16
ERROR connecting
Please enter the message: hello


text:
Q: How to enable sidebar changelog in WebStorm? Today I added Material Theme plugin to WebStorm and I believe this is the reason behind changelist not appearing on the sidebar.
To be precise, this is what happens in IntelliJ when I make change to a specific line of code and click on the yellow bar that appeared after I removed the semicolon:

The change I made can also be seen under VCS -> Local History -> Show History menu option, which shows the diff between the previous and current version of that file.
However, performing the same action in WebStorm doesn't show the changelist/diff on the sidebar:

which means that the only way I can see it is by going to VCS -> Local History -> Show History which is very tedious:

I found being able to quickly revert/lookup the changes on the fly by clicking on that coloured bar really handy, could someone tell me if there is a setting in the IDE that enables that? I looked up and down but couldn't find anything relevant, perhaps I wasn't looking for the right keyword.
Thanks in advance.

A: Change markers are there for me when using Material UI plugin. Do you have Highlight modified lines in gutter enabled in Settings | Editor | General?


text:
Q: Doing a lookup using dataframe.get I have a list, tids, containing track IDs. that I to do a lookup of those track IDs onto the a dataframe, res, and give me back a list of track titles instead.
I was basing my code on the one given here: Look up and replace values in a list (pandas)
But it was simply giving me back the track ID again.
I then tried tweaking the code as below but this gives me back a dict within a list it seems (so the print [0] at the end there seems to return everything). I can of course then play with this to extract just the track titles but was wondering what I'm doing wrong in my approach?
def convertTrackIDToTrackName(dbPath, tids):
    con = sqlite3.connect(dbPath)
    sqlStr = "SELECT track_id, title from songs"

    # Load into Pandas
    res = pd.read_sql_query(sqlStr, con)
    con.close()
    res = res.set_index('track_id')

    z_new = [res.get('title',t) for t in tids]
    print (z_new[0])

A: Use pd.Series, map, and tolist:
s = pd.Series(tids).map(res['title']).tolist()


text:
Q: Can we rebuild node native module on Linux for win32 platform using node-gyp? I've created an electron application which uses two NodeJS native modules node ref and node ffi. The application is being developed on windows right now and the windows executable is generated with the help of electron-builder. This all works perfectly fine and the application is installed in windows properly. As both ffi and ref are native modules, I'm simply use electron-rebuild to rebuild them for platform win32 (I guess that internally uses node-gyp).
But the problem is, my CI/CD server is Ubuntu 16 and I need to generate the windows executable file there. If my application doesn't have node's native addons, it works fantastic but with native modules included, the exe file is generated but on launch it says %1 is not a win32 application and the reason for that is, the native deps are rebuilt for Linux platform instead of windows.
So I wanted to know is, is there any way to rebuild the node native modules on Linux machine for win32 platform or if its not possible then how can we use the pre-built .node file across the platforms.


text:
Q: Setting an index of a binary tree in go Im trying to teach myself data structures & algos and I am trying to figure out the best way to add an index to a binary tree
Im guessing the best way to do this is to modify an in orderTraversal operation but im not exactly sure how I would implement this and chain that on after every insert and delete function.

type BinarySearchNode struct {
    Left *BinarySearchNode
    Right *BinarySearchNode
    Parent *BinarySearchNode
    Data int
    Index int
}

func (BSN *BinarySearchNode) Insert(value int){

    if BSN.Data > value {
        if BSN.Left == nil{
            BSN.Left = &BinarySearchNode{Data:value, Parent:BSN}
            return
        }
        BSN.Left.Insert(value)
        return
    }

    if BSN.Right == nil{
        BSN.Right = &BinarySearchNode{Data:value, Parent: BSN}
        return
    }
    BSN.Right.Insert(value)
}

func (BSN *BinarySearchNode) setIndex(node *BinarySearchNode, count int)(int){
    if node == nil{
        return count
    }

    if node.Right == nil && node.Left == nil{
        node.Index = count
    }
    node.setIndex(node.Left, count+1)
    node.setIndex(node.Right, count+1)

    return count
}

A: I have a piece of code for the implementation of binary tree in golang. It may help you.
package main

import (
    "fmt"
    "math"
)

// A single Node in a binary tree
type Node struct {

    // Value contained by the node
    Value int

    // Left subnode of the node
    Left *Node

    // Right subnode of the node
    Right *Node
}

type BinaryTree struct {
    Root *Node
}

// inserting the element in the binary tree
func (tree *BinaryTree) Insert(value int) {
    if tree.Root == nil {
        node := new(Node)
        node.Value = value
        tree.Root = node
        return
    }
    current := tree.Root
    for {
        if value < current.Value {
            if current.Left == nil {

                node := new(Node)
                node.Value = value
                current.Left = node
                return
            } else {
                current = current.Left
            }

        } else {
            if current.Right == nil {

                node := new(Node)
                node.Value = value
                current.Right = node
                return
            } else {
                current = current.Right
            }
        }
    }
}

// current left right
func (tree *BinaryTree) RecursivePreOrder(root *Node) {
    if root == nil {
        return
    }
    fmt.Println(root.Value)
    tree.RecursivePreOrder(root.Left)
    tree.RecursivePreOrder(root.Right)

}

func (tree *BinaryTree) IterativePreOrder(root *Node) {
    stack := []*Node{}
    for {
        for root != nil {
            fmt.Println(root.Value)
            stack = append([]*Node{root}, stack...)
            root = root.Left
        }
        if len(stack) == 0 {
            break
        }
        root = stack[0]
        stack = stack[1:]
        root = root.Right
    }
}

func (tree *BinaryTree) RecursiveInOrder(root *Node) {
    if root == nil {
        return
    }
    tree.RecursiveInOrder(root.Left)
    fmt.Println(root.Value)
    tree.RecursiveInOrder(root.Right)

}

func (tree *BinaryTree) IterativeInOrder(root *Node) {
    var stack []*Node
    for {
        for root != nil {
            stack = append([]*Node{root}, stack...)
            root = root.Left
        }
        if len(stack) == 0 {
            break
        }
        root = stack[0]
        stack = stack[1:]
        fmt.Println(root.Value)
        root = root.Right
    }
}

func (tree *BinaryTree) RecursivePostOrder(root *Node) {
    if root == nil {
        return
    }
    tree.RecursivePostOrder(root.Left)
    tree.RecursivePostOrder(root.Right)
    fmt.Println(root.Value)
}

func (tree *BinaryTree) IterativePostOrder(root *Node) {
    stack := []*Node{}

    var previous *Node = nil
    for {
        for root != nil {
            stack = append([]*Node{root}, stack...)
            root = root.Left
        }
        for root == nil && len(stack) != 0 {
            root = stack[0]
            if root.Right == nil || root.Right == previous {
                fmt.Println(root.Value)
                stack = stack[1:]
                previous = root
                root = nil
            } else {
                root = root.Right
            }
        }
        if len(stack) == 0 {
            break
        }
    }
}

func (tree *BinaryTree) LevelOrder(root *Node) {
    // a queue for performing level order traversal of breadth first traversal
    queue := []*Node{}

    if root != nil {
        queue = append(queue, root)
    }
    for len(queue) > 0 {
        root = queue[0]
        queue = queue[1:]
        fmt.Println(root.Value)
        if root.Left != nil {
            queue = append(queue, root.Left)
        }
        if root.Right != nil {
            queue = append(queue, root.Right)
        }
    }
}

func (tree *BinaryTree) Size(root *Node) int {
    if root == nil {
        return 0
    }
    sum := tree.Size(root.Left) + 1 + tree.Size(root.Right)
    return sum
}

func (tree *BinaryTree) ElementAt(root *Node, index int) *Node {
    if index > tree.Size(root)-1 {
        fmt.Println("Index doesnot exist")
        return nil
    }
    leftSize := tree.Size(root.Left)
    if index == leftSize {
        return root
    } else if index < leftSize {
        return tree.ElementAt(root.Left, index)
    } else {
        return tree.ElementAt(root.Right, index-leftSize-1)
    }
}

func (tree *BinaryTree) Height(root *Node) int {
    if root == nil {
        return -1
    }
    return int(math.Max(float64(tree.Height(root.Left)), float64(tree.Height(root.Right)))) + 1
}

// starting point of the program
func main() {
    tree := new(BinaryTree)
    tree.Insert(44)
    tree.Insert(55)
    tree.Insert(33)
    fmt.Println(tree.Height(tree.Root))

}


text:
Q: Instantiate from csv with pandas I have previously made a code to instantiate from a csv file. I what to do the same with Pandas (gives more possibilities when importing csv file). Is this possible?
What I want (without Pandas):
    @classmethod
    def instantiate_from_csv(cls):
        with open('items.csv', 'r') as f:
            reader = csv.DictReader(f)
            items = list(reader)

        for item in items:
            Item(
                project=item.get('project'),
                price=str(item.get('item')),
                quantity=str(item.get('maker')),
            )

What I have:

import pandas as pd

df = pd.read_csv('items.csv', sep=';', header=0, index_col=['project'], usecols=["project", "item", "maker",])

print(df)

Any help is greatly appreciated.

A: Not sure if I understood your question correctly. If what you're looking for is "what you want" (first piece of code) but reading with Pandas, then this is what you might be looking for:
import pandas as pd

def instantiate_from_csv(cls):
    df = pd.read_csv('items.csv', sep=';', usecols=["project", "price", "quantity",])

    for index, item in df.iterrows():
        Item(
            project=item['project'],
            price=str(item['item']),
            quantity=str(item['maker']),
        )


text:
Q: Unable to find a specification for '[Any pod libraries]' I don't know what's wrong with my cocoapods. It always show this error on every pod libraries every time I run pod install. For instance "AFNetworking"
[!] Unable to find a specification for `AFNetworking (~> 3.0)`

I tried the following but nothing help:
pod repo update
sudo rm -fr ~/.cocoapods/repos/master
pod setup
pod install

I tried to update my cocoapods to 1.1.1, Xcode to 8.2 and Mac OS to 10.12.2 but problem remain.
My cocoapods can't even search. It show this error every time I run "pod search AFNetworking"
[!] Unable to find a pod with name, author, summary, or description matching `AFNetworking`

Here is my podfile look like:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'

target 'Leader' do
  use_frameworks!
  pod 'AFNetworking', '~> 3.0'
end

I did try to uninstall and reinstall cocoapods back but nothing help.

A: Please follow below format in your pod file its working in project.
#Uncomment this line to define a global platform for your project
 platform :ios, '8.0'
 #Uncomment this line if you're using Swift
 use_frameworks!
target 'applicationName' do
pod 'AFNetworking', '~> 3.0'
end
If you find any issue please let me know.


text:
Q: A theory of equation question from my exam paper Consider The equation $x^3+3x^2+3x+3=0$ Then the sum of it's non-real roots is
A) is equal to $0$
B)lies in $0$ and $1$
C)lies in $-1$ and $0$
D)Greter that $1$
Which one is correct , plz explain briefly;

A: HINT:
$$x^3+3x^2+3x+3=0\implies (x+1)^3=-2$$
Do you about the roots of $y^3=a$ where $a$ is a real number?
If no, please have a look into this problem

A: As the eqn shows the imaginary roots are $x=-s\omega -1,-s\omega^2 -1$ where $s$ is the real cube root of $2$.Now summing them we get the sum is $s-2$.Now it remains to show that $-1<s-2<0\implies 1<s<2\implies 1<s^3<8\implies 1<2<8$ which is true so the option C) is correct.


text:
Q: int in javascript returning as string in php I am sending some data from ajax to a php script that passes it to an api. I noticed that the data being console.log'd from my javascript has ints where ints are required but when I altered my php to return the data back to my script so that I could make sure it is structured correctly, all of my ints come back as strings.
example:
javascript
[{"UnitID":563614,"InsuranceID":null}]

php
[{"UnitID":"563614","InsuranceID":"NaN"}]

I am confused as to why this is happening. How the javascript has it is how it should be, but php seams to want to convert all of the ints to strings when it receives the data.
Here is the relevant part of my scripts
javascript
function wssReserve(form) {

    var sendinsid   = parseInt(form.InsuranceID.value);

    data = {
        "Units": [{
            "InsuranceID": sendinsid
        }]
    };

    var settings2 = {
        "async": true,
        "crossDomain": true,
        "url": "php.script",
        "data": { json: { data } },
        "method": "POST"
    };

    var a2 = $.ajax(settings2);

    $.when(a2).done(function(d2) {

        console.log(JSON.stringify(d2));

    });

}

php
function wssLocationReserve($data) {

    header('Content-Type: application/json');

    $url = 'external.api';
    $auth = 'Authorization: Basic auth-token';

    //$post_data = json_encode($_POST['data'});

    $ch = curl_init($url);
    $options = array(
        CURLOPT_HTTPHEADER => array(
            $auth,
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ),
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true
    );
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_decode($data));
    curl_setopt_array($ch, $options);

    $result = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$json = $_POST['json'];

if( strcasecmp($_GET['method'],'hello') == 0){
    $response['code'] = 1;
    $response['status'] = $api_response_code[ $response['code'] ]['HTTP Response'];
    $response['data'] =  wssLocationReserve($json);
}

deliver_response($_GET['format'], $response);

if I return the $result instead of $data I get this from the api
 {\"Success\":false,\"ErrorMessage\":\"An unhandled exception has occurred and been logged.\"}


text:
Q: клавиатура для бота вк с библиотекой vk_api я хочу чтобы при написании /start бот выводил клавиатуру,
for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW:
        if event.to_me:
            message = event.text.lower()
            # Получаем id пользователя
            id = event.user_id

вот цикл прослушки и допустим в конце
if message == '/start':
    #выводится клавиатура

подскажите пожалуйста

A: до цикла for нужно вставить вот эту функцию:
import menu

def keyboard_run(sender, message, menu):
    vk_session.method('messages.send', {
                      'chat_id': sender, 'message': message, 'random_id': get_random_id(), 'keyboard': menu.get_keyboard()})

Тут импортируем файл с клавиатурами, а в дальнейшем пишем функцию для её вызова.
Это что-то вроде метода обработки ответа, как и функция текстового ответа или функция вызова изображения.
Сама клавиатура:
Клавиатуры можно хранить в отдельном файле, например menu.py
group = VkKeyboard(inline=True)
group.add_button('1 вариант', color=VkKeyboardColor.SECONDARY)
group.add_button('2 вариант', color=VkKeyboardColor.SECONDARY)
group.add_button('3 вариант', color=VkKeyboardColor.SECONDARY)

Ну и собственно сам вызов:
if message == '/start'::
    keyboard_run(sender, "Текст с клавиатурой", group) # Последний параметр это та переменная, на которую мы клавиатуру привязали.


text:
Q: Python: AttributeError: 'str' object has no attribute 'keys' I want to make country map from code:
import chart_studio.plotly as py
import pandas as pd

df = pd.read_csv('MS.csv')

data = [ dict(
       type = 'choropleth',
       locations = df['CODE'],
       z = df['MS'],
       text = df['COUNTRY'],
       colorscale = [[0,"rgb(5, 10, 172)"],[0.35,"rgb(40, 60, 190)"],[0.5,"rgb(70, 100, 245)"],\
           [0.6,"rgb(00, 120, 245)"],[0.7,"rgb(06, 130, 247)"],[1,"rgb(255, 255, 259)"]],
       autocolorscale = False,
       reversescale = True,
       marker = dict(
           line = dict (
               color = 'rgb(180,180,180)',
               width = 0.5
           ) ),
       colorbar = dict(
           autotick = False,
           tickprefix = None,
           title = 'ASes'),
     ) ]

layout = dict(
   title = 'MS COUNTRY',
   geo = dict(
       showframe = False,
       showcoastlines = False,
       projection = dict(
           type = 'Mercator'
       )
   )
)

fig = dict( data=data, layout=layout )
py.plot( fig, validate=False, filename='d3-world-map' )

This produces a fine map with Python 3 but when I run on spyder Anaconda It is giving error:
Traceback (most recent call last):

  File "<ipython-input-8-fe3c136d7898>", line 1, in <module>
    runfile('C:/charts/plot (2).py', wdir='C:/charts')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/charts/plot (2).py", line 38, in <module>
    py.plot( fig, validate=False, filename='d3-world-map' )

  File "C:\ProgramData\Anaconda3\lib\site-packages\chart_studio\plotly\plotly.py", line 265, in plot
    figure, grid = _extract_grid_from_fig_like(figure)

  File "C:\ProgramData\Anaconda3\lib\site-packages\chart_studio\plotly\plotly.py", line 1870, in _extract_grid_from_fig_like
    trace_dict, reference_trace, grid, path + "data.{}.".format(i)

  File "C:\ProgramData\Anaconda3\lib\site-packages\chart_studio\plotly\plotly.py", line 1800, in _extract_grid_graph_obj
    "{path}{prop}.".format(path=path, prop=prop),

  File "C:\ProgramData\Anaconda3\lib\site-packages\chart_studio\plotly\plotly.py", line 1800, in _extract_grid_graph_obj
    "{path}{prop}.".format(path=path, prop=prop),

  File "C:\ProgramData\Anaconda3\lib\site-packages\chart_studio\plotly\plotly.py", line 1782, in _extract_grid_graph_obj
    for prop in list(obj_dict.keys()):

AttributeError: 'str' object has no attribute 'keys'

How can I solve this?

A: Without a proper data sample and complete knowledge of your data, it's hard to know what's the cause of the error. But with newer versions of plotly  you should be able to show plotly figures in Spyder with examples like the one below. Try that, see if it works, and tell us what you find out.
Version info:
Python 3.7.0
Spyder 3.3.1
Plotly 4.2.0

Code:
import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')

fig = go.Figure(data=go.Choropleth(
    locations = df['CODE'],
    z = df['GDP (BILLIONS)'],
    text = df['COUNTRY'],
    colorscale = 'Blues',
    autocolorscale=False,
    reversescale=True,
    marker_line_color='darkgray',
    marker_line_width=0.5,
    colorbar_tickprefix = '$',
    colorbar_title = 'GDP
Billions US$',
))

fig.update_layout(
    title_text='2014 Global GDP',
    geo=dict(
        showframe=False,
        showcoastlines=False,
        projection_type='equirectangular'
    ),
    annotations = [dict(
        x=0.55,
        y=0.1,
        xref='paper',
        yref='paper',
        text='Source: \
            CIA World Factbook',
        showarrow = False
    )]
)

fig.show()

Plot:


text:
Q: Unable to print PHP variable using JS I understand that this question has been asked a lot of of times, but the solutions posted there don't seem to work for me. I have a code as follows:
<script>
  var JSvar = "<?php echo $phpVar ?>";
  document.write(JSvar);
</script>
<?php
$phpVar="jajha";
?>

I actually want to pass a PHP variable to a JS function, but I wanted to try if printing the variable works first. Please help me out.

A: instead of
<script>
  var JSvar = "<?php echo $phpVar ?>";
  document.write(JSvar);
</script>
<?php
$phpVar="jajha";
?>

try
<?php
    $phpVar="jajha";
    ?>
<script>
    var JSvar = "<?php echo $phpVar ?>";
    document.write(JSvar);
</script>


text:
Q: How can I create a different layout between cart.liquid and ajax-cart-template.liquid using Timber framework for Shopify I'm wondering if you could help me with a problem I'm facing with the Ajaxify cart for my theme using the Timber framework.
My design has a slightly different layout of content between my standard cart page (cart.liquid template) and the ajaxify pop-out quick cart that I want to create. I'm a bit confused as to how you remove & add certain elements, for example when I move the product title to go above my product image nothing changes…
Am I right in thinking that the ajaxify script is pulling in the /cart form content from the cart.liquid template, if so am I able to create an additional different form in a template for my ajax quick cart?
How to achieve this? It is possible to have a different layout between the cart and the quick cart?


text:
Q: Uninitialized value error while using Adadelta optimizer in Tensorflow I am trying to build a CNN using Adagrad optimizer but am getting the following error.
tensorflow.python.framework.errors.FailedPreconditionError: Attempting to use uninitialized value Variable_7/Adadelta
[[Node: Adadelta/update_Variable_7/ApplyAdadelta = ApplyAdadelta[T=DT_FLOAT, _class=["loc:@Variable_7"], use_locking=false, _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_7, Variable_7/Adadelta, Variable_7/Adadelta_1, Adadelta/lr, Adadelta/rho, Adadelta/epsilon, gradients/add_3_grad/tuple/control_dependency_1)]]
Caused by op u'Adadelta/update_Variable_7/ApplyAdadelta',
optimizer = tf.train.AdadeltaOptimizer(learning_rate).minimize(cross_entropy)
I tried reinitializing the session variables after the adagrad statement as mentioned in this post, but that didn't help too.
How can I avoid this error? Thanks.
Tensorflow: Using Adam optimizer
import tensorflow as tf
import numpy
from tensorflow.examples.tutorials.mnist import input_data

def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

# Parameters
learning_rate = 0.01
training_epochs = 100
batch_size = 1000
display_step = 1

# Set model weights
W = tf.Variable(tf.zeros([784, 10]), name="weights")
b = tf.Variable(tf.zeros([10]), name="bias")

W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

# Initializing the variables
init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(training_epochs):
        total_batch = int(mnist.train.num_examples/batch_size)
        for i in range(total_batch):

            batch_xs, batch_ys = mnist.train.next_batch(batch_size)

            x_image = tf.reshape(batch_xs, [-1,28,28,1])

            h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
            h_pool1 = max_pool_2x2(h_conv1)

            h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
            h_pool2 = max_pool_2x2(h_conv2)

            h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
            h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

            y_conv=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)

            cross_entropy = tf.reduce_mean(-tf.reduce_sum(batch_ys * tf.log(y_conv), reduction_indices=[1]))
            #optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)

            optimizer = tf.train.AdadeltaOptimizer(learning_rate).minimize(cross_entropy)
            sess.run(init)

            correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(batch_ys,1))
            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
            sess.run([cross_entropy, y_conv,optimizer])
            print cross_entropy.eval()

A: The problem here is that tf.initialize_all_variables() is a misleading name. It really means "return an operation that initializes all variables that have already been created (in the default graph)". When you call tf.train.AdadeltaOptimizer(...).minimize(), TensorFlow creates additional variables, which are not covered by the init op that you created earlier.
Moving the line:
init = tf.initialize_all_variables()

...after the construction of the tf.train.AdadeltaOptimizer should make your program work.
N.B. Your program rebuilds the entire network, apart from the variables, on each training step. This is likely to be very inefficient, and the Adadelta algorithm will not adapt as expected because its state is recreated on each step. I would strongly recommend moving the code from the definition of batch_xs to the creation of the optimizer outside of the two nested for loops. You should define tf.placeholder() ops for the batch_xs and batch_ys inputs, and use the feed_dict argument to sess.run() to pass in the values returned by mnist.train.next_batch().


text:
Q: Basic search in wordpress I am creating a wordpress template in which I want to integrate a simple search form. I googled a lot about this in the last 3 days and tried several tutorials but I am afraid there is something I don't get at all. I have 3 pages for the search: search.php, searchform.php and searchpage.php. All the tutorials I read provide similar code like this:
search.php:
<?php if (have_posts()) : ?>
…
<?php while (have_posts()) : the_post(); ?>
…
<?php endwhile; else: ?>
…
The key word <?php the_search_query(); ?> is not on this website.

<?php include (TEMPLATEPATH . "/searchform.php"); ?>
<?php include (TEMPLATEPATH . "/searchpage.php"); ?>
<?php endif; ?>

searchform.php:
<?php
$querystring = esc_attr(apply_filters('the_search_query', get_search_query()));
$searchstring = "Suchbegriff eingeben";
if (empty($querystring)) { $querystring = $searchstring; }
?>

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">

    <input type="text" name="s" id="s" value="<?php echo $querystring; ?>"
        onblur="if (this.value == '') { this.value = '<?php echo $searchstring; ?>'; }"
        onfocus="if (this.value == '<?php echo $searchstring; ?>') { this.value = ''; }" />
    <input type="submit" id="searchsubmit" value="Suchen" />

</form>

searchpage.php (adapted from page.php):
<?php
/*
Template Name: Search Page
*/
?>

<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

        <?php the_content(); ?>
        <?php $this->posts = $wpdb->get_results($this->request); ?>

<?php endwhile; ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

If there is no match with the key word the search works. But if there is a match I only get … … … … … … … as output. I know that must be from the search.php but I have no idea how I can change that. Thanks for your advise and help, I really appreciate it!

A: The important file is search.php, which displays any matching results, or a failure message if there are no matches.  Try something like this:
<?php
/**
 * Search results page
 */
?>
<?php if ( have_posts() ): ?>

Search Results for '<?php echo get_search_query(); ?>'

<?php while ( have_posts() ) : the_post(); ?>

<a href="<?php esc_url( the_permalink() ); ?>" title="Permalink to <?php the_title(); ?>" rel="bookmark"><?php the_title(); ?>

            <time datetime="<?php the_time( 'Y-m-d' ); ?>" pubdate><?php the_date(); ?> <?php the_time(); ?></time> <?php comments_popup_link('Leave a Comment', '1 Comment', '% Comments'); ?>
            <?php the_content(); ?>

<?php endwhile; ?>

<?php else: ?>

No results found for '<?php echo get_search_query(); ?>'

<?php endif; ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
Q: Angular controller inheritance with view routing I have an Angular app, and I am currently using $routeProvider to route the urls to a template with an ng-view directive:
app.js
.config( function ($interpolateProvider, $routeProvider) {
$routeProvider
    .when('/project/:projectId', {
        // this is the partial...
        templateUrl : 'partials/_project_detail.html',
        controller: 'ProjectDetailCtrl',
        resolve: {
            project: function ($route, MyService) {
                return MyService.get('projects/', $route.current.params.projectId);
        }
    })
})

.controller('ProjectDetailCtrl', function ($scope, project) {
    ...
    $scope.project = project;
})

index.html
...

...

Now, I would like to use controller scope inheritance to have a child controller within the parent one, along the lines of:
project_detail.tmpl.html
...

Project: {{ project.title }}

Project: {{ project.title }}

...

But this doesn't seem to work. I know according to the Angular docs that you can inherit scope between parent and child scopes if both controllers are declared in the template: http://docs.angularjs.org/guide/controller
Is there some way to achieve inheritance using the router method?

A: Maybe this is because you are binding to primitive value, instead of an object in your controller. Try using an object with dot notation, for example: {{ project.var1 }}
If this is the problem, I recommend you watching this video: Egghead.io


text:
Q: PayPal API, HttpWebRequest throws SSL WebException I'm trying to get an PayPal access token as shown here:
https://developer.paypal.com/docs/integration/direct/make-your-first-call/#get-an-access-token
My C# Code looks like this:
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + clientSecret));
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en_US");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;

byte[] postBytes = Encoding.ASCII.GetBytes("grant_type=client_credentials");
request.ContentLength = postBytes.Length;

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

Stream postStream = request.GetRequestStream(); // ###### Here I get the Exception! ######
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

When calling request.GetRequestStream(), I get a WebException with the german text "Die Anfrage wurde abgebrochen: Es konnte kein geschützter SSL/TLS-Kanal erstellt werden." which means that it was unable to create a secure SSL/TLS channel.
What do I do wrong? Can anybody help me?
Thanks,
Volker

A: I found the solution:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //SecurityProtocolType.Tls12;

Maybe it helps somebody else, too...

A: Correct they don't use SSL 3 any more and that is where the error is coming from.
You can use TLS 1.1 & 1.2
ServicePointManager.SecurityProtocol =  SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;


text:
Q: Need a control/solution that will be used as a container for storing values from the textfield in yii Here's what I want to do: (in yii)
I have multiple textFields (around 6), in a form. I need a control that will used as a container for storing values from the textFields (meaning one container for each textField as more values will be added to the container from the same textField on button click), and that control should be accessible from yii model or controller.
Is there any control or any way to achieve this?
Any suggestions will be appreciated. Thank you.

A: In view
For Active records
<?php echo $form->textField($model,'title[]',array('size'=>60,'maxlength'=>1000)); ?>

CHtml
<?php echo CHtml::textField('title[]','Title'); ?>

You can use multiple input's with same name by array of name
In controller
You can get these values as array with the name of you posted
i prefer this to you


text:
Q: Qdir's function exists() always returns true, even when the directory doesn't exist I'm trying to error-proof the first part of a project, in which a folder is created in a specified base directory. The base directory is selected by the user either manually in QLineEdit, or by browsing through the computer's directories using QFileDialog. I'm trying to check if the base directory exists before I make a sub-folder in it using the following commands:
QString base_dir = ui->baseDir->text();
QString blank = "";
QString no_text1 = "Please enter a valid directory";
if( base_dir==no_text1 || base_dir==blank ) {
    if( !QDir( base_dir ).exists() ) {         //does base directory exist?
    ui->baseDir->setText( no_text1 );
    return;
    }
}

The issue is that whether I type a valid directory into the line edit, or an invalid one (ie. a random phrase) the second if statement always returns false, meaning exists() always returns true. The first if statement works properly. Am I just using exists() wrong?
Edit:
The full code
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "functions.h"
#include <QtGui/QApplication>
#include <QFileDialog>
#include <fstream>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// This is the function that handles the directory search when the 'browse' button is pressed
void MainWindow::on_findDir_clicked()
{
    QString path;   //declaring the path to the base directory

    path = QFileDialog::getExistingDirectory(   //gathering the directory from QFileDialog class
        this, tr("Choose the project directory"),
        "/home",
        QFileDialog::ShowDirsOnly
        | QFileDialog::DontResolveSymlinks );

    ui->baseDir->setText( path );   //setting the retrieved path into the line edit box
}

// This function makes the project by creating a new directory with name 'project_name'
// in the base directory, and collects the OpenFOAM version number and simulation type
void MainWindow::on_create_clicked()
{

    QString project_name, foam_version, full_dir, slash, base_dir;
    base_dir = ui->baseDir->text();
    project_name = ui->projectName->text();     //getting the text from the 'projectName' field
    foam_version = ui->version->currentText();  //getting the selection from the 'version' drop-down box

    //first checking if the fields have input in them:
    QString blank = "";
    QString no_text0 = "Please enter project name";
    if( project_name==no_text0 || (project_name==blank) ) {
        ui->projectName->setText( no_text0 );
        return;
    }

    QString no_text1 = "Please enter a valid directory";
    if( base_dir==no_text1 || base_dir==blank ) {
        if( !QDir( base_dir ).exists() ) {         //does base directory exist?
        ui->baseDir->setText( no_text1 );
        return;
        }
    }

    slash = "/";        // needed to separate folders in the directory (can't use a literal)
    full_dir = base_dir.append(slash.append(project_name));

    if( !QDir(full_dir).exists() )  //check if directory already exists
        QDir().mkdir(full_dir);     //creating directory

    QString blockmesh_filename, suffix;
    suffix = "_blockmesh";
    slash = "/";    //must re-define
    blockmesh_filename = full_dir.append( slash.append( project_name.append(suffix) ) );
    std::ofstream create_file( blockmesh_filename.toStdString().c_str() );  //creating empty blockmesh file

}

A: Your second if statement will not be executed if you type in anything in the text field. Your logic in the first if states that if the input is empty or a predefine string, then test for the existence of the dir. Which means you are always testing with an empty string or the canned message.
The correct logic should be:
if( base_dir!=no_text1 && base_dir!=blank ) {
    ....


text:
Q: getUserMedia Detection JS I am currently using a getUserMedia function in order to have the user's voice recorded. This same algorithm is used in cwilso's JavaScript tuner: https://github.com/cwilso/PitchDetect
I want to be able to know when the microphone is ready for recording, so the user does not assume the program is broken when the mic is not loaded.
In the GitHub the mic loads immediately, but if I run it on mobile it takes some time before starting.
I know this is a very peculiar problem, but any help, even pointing me in a direction, would be greatly appreciated.
Thank you in advance! Please comment if I was not clear anywhere.


text:
Q: How to find a simple function representing FizzBuzz Consider the FizzBuzz programming challenge:

Output the numbers [1, 100], replacing numbers divisible by 3 with
  "Fizz", numbers divisible by 5 with "Buzz", and numbers divisible by
  both 3 and 5 with "FizzBuzz".

The case selection can be seen as a function with the domain $[1, 100]$ mapping to values in four non-overlapping intervals; $A$, $B$, $C$, $D$,
$$
  f(n) =
\begin{cases}
\text{something}\in A,  & \text{if $3 \mid n ~\land~ 5 \not\mid n$}   \\
\text{something}\in B,  & \text{if $3 \not\mid n ~\land~ 5 \mid n$}   \\
\text{something}\in C,  & \text{if $3 \mid n ~\land~ 5 \mid n$}   \\
\text{something}\in D,  & \text{otherwise}   \\
\end{cases}
$$
Such a function can be trivially found with e.g. polynomial interpolation by letting each interval contain only a single number.
However, how does one find such a function that is as "simple" as possible? "Simple" is a bit vague, but in the case of a polynomial the number of terms would be a good measure.
Are there any other ways to construct such a function (without using cases)? Preferable a so "simple" function as possible.

A: Using number theory, you can say:
$$f(n)=n^{4}\bmod {15}$$ going to $$A=\{10\},B=\{6\},C=\{0\},D=\{1\}$$
If you want something more "continuous," you could take, for example, $$f(n)=2\cos (2\pi n/3)-\cos(2\pi n/5)$$
$$A=[1.65,2.85],B=[-2,-2], C=[1,1], D=[-1.31,0]$$
The best approach is to use trig functions, since $f$ is inherently periodic.
A discrete Fourier transform gives us an "exact" function:
$$f(n)=\frac{13}{15}+\frac{2}{5}\left(\cos 2\pi n/5+\cos 4\pi n/5\right)+\frac{4}{3}\cos(2\pi n/3)$$
Then we get $A=\{2\},B=\{1\},C=\{3\},D=\{0\}.$ You can expand those to make them intervals.


text:
Q: jQuery: write variable between 2 quotation mark I want to create a loop for input so that the variable img get number 1 to 5 like this:
img1, img2 ... img5.

How to write $i after img?
for ($i=1;$i<=5;$i++) {

  function(data) { $('input[name="img1"]').val(data) });

}

Note: img is between two quotation mark.
it's edite:
user = $('input[name="name"]').val();
for (var i = 1; i <= 5; i++) {
  $.post("test.php", { name: user, num: i },
  function(data) {
    $('input[name="img'+i+'"]').val(data)
  });
}

A: The function you have declared in your loop seems weird. That's not valid javascript. You may try the following:
for (var i = 1; i <= 5; i++) {
    $('input[name="img' + i + '"]').val(data);
}

or if we suppose that you have defined some function:
var foo = function(data, index) {
    $('input[name="img' + index + '"]').val(data);
}

you could invoke it like this:
for (var i = 1; i <= 5; i++) {
    foo('some data ' + i, i);
}

UPDATE:
An interesting example was provided in the comments section:
for (var i = 1; i <= 5; i++) {
    $.post(
        "test.php",
        { name: username, num: i },
        function(data) {
            $('input[name="img'+i+'"]').val(data);
        }
    );
}

This won't work because the i variable might have changed value between the loop and the AJAX success callback. To fix this you may try the following:
for (var i = 1; i <= 5; i++) {
    (function(index) {
        $.post(
            "test.php",
            { name: username, num: index },
            function(data) {
                $('input[name="img'+index+'"]').val(data);
            }
        );
    })(i);
}

or use the $.ajax() method which allows you to pass a context to the success callback:
for (var i = 1; i <= 5; i++) {
    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: { name: username, num: i },
        context: i, // here we are defining the context
        success: function(result) {
            // since we have used the context parameter, this variable
            // here will point to the value that i had when we initiated
            // the AJAX request
            $('input[name="img' + this + '"]').val(result);
        }
    });
}

A: Like this:
for ($i=1;$i<=5;$i++) {

    function(data) { $('input[name="img' + $i + '"]').val(data) });

}

By the way, I'm guessing you'e coming from a PHP background, but in JavaScript it is not conventional to use $ for variable names (except sometimes for jQuery objects). So normally you'd write your code like this:
for (i=1;i<=5;i++) {

    function(data) { $('input[name="img' + i + '"]').val(data) });

}


text:
Q: Testing Zend_Controller which is using Twitter API I'm trying to write a unit test for my Controller which calls the Twitter API using Zend_Service.
/**
 * Authenticate Step 1 for Twitter
 */
public function authenticateAction()
{
    $this->service->authenticate();
}

The Service does:
/**
 * Authenticate with twitter
 *
 * @return void
 */
public function authenticate()
{
    $consumer = new Zend_Oauth_Consumer($this->config);
    $token = $consumer->getRequestToken();
    $this->session->twitterRequestToken = serialize($token);
    $consumer->redirect();
    exit;
}

My Problem is that I have no idea how to replace the authenticate action inside the service for the unit test. I don't want to call the Twitter API while the tests run.
Is there any Mocking Framework which can do such things?

A: Zend_Service_Twitter uses Zend_Http_Client so you can stub it in your test case
$httpClient = $this->getMock('Zend_Http_Client');

$httpResponse = new Zend_Http_Response(200, array(), $data);  // $data - response you expected to get

$httpClient->expects($this->any())
                   ->method('request')
                   ->will($this->returnValue($httpResponse));

Zend_Service_Twitter::setLocalHttpClient($httpClient);


text:
Q: User authentication in tornado based on other php site I wrote my own long-pollig Tornado/AJAX chat with rooms , whisper messages and other cool stuff . Till now as user authentication for just test purposes i've been using cookies . So u had to just enter your name ,after what cokie 'user' was created and chat would react accordingly to that cookie . But the problem is that i wrote this chat for a friend which has a php site. So basically i need to authenticate users based on his sessions. Thats where i got confused. And i am very ashamed , because i caught myself on a thought that i don't know how exactly session work , which is kind of absurd, because i don't consider myself such a bad programmer ^^ Well shit happens. Well ofcourse i know that sessions only store id on the client and other information is stored on the server , but that doesn't really help because i need know excatly what happens in details .  Sure i googled a bit , but still am confused how to solve this problem. So the basic questions are :
1) Would appreciate if someone could in details explain one more time exactly how sessions work , and what i need know or have access to on php site ,  to use sessions in another application ...
*2)*So for example when i authenticate on my django site ,session is created with some value like 's5ds6dssd6' , and to tell the truth i don't know what to further do with it.Ashamed again. For example in PHP to extract  username (if it was set) and check/do something i would do something like  PHP_SESSION['username'] === ... .In django even less work just to use decorator or user.is_authenticated method. Yet how works inside and what i need i don't know.

There is a big chance what i wrote is stupid , and it's very easy , and i am a moron , which wrote before trying ...Yet even if i somehow would be able to get data from sessions/php site  how could i be sure that some guy didn't create session with random id by himself , without authencating on php site ....
Well hope someone could point me in right direction . It felt necessary to write so much so you could udnerstand =) what bothers me and respond accordingly....  Sorry if i wrote something stupid.

A:
1) Would appreciate if someone could
  in details explain one more time
  exactly how sessions work , and what i
  need know or have access to on php
  site , to use sessions in another
  application ...

P.S: I am using Linux(I use the freely available Ubuntu which is the most popular/user-friendly Linux distro) as OS below and I would advice you to use a *nx distro(MacOSX is also pretty good but expensive in my opinion) as well with all your webdevelopment although all these commands are also available in Cygwin(windows).
Sessions are:

Session support in PHP consists of a
  way to preserve certain data across
  subsequent accesses. This enables you
  to build more customized applications
  and increase the appeal of your web
  site.

Below I try to explain what sessions are and how they are using cookies

I created a simple no.php which does not use sessions and simply outputs Hello World:
Hello World

When we curl this script with the headers using -v we get the following output:
alfred@alfred-laptop:~/www/6500588$ curl http://localhost/6500588/no.php -v
* About to connect() to localhost port 80 (#0)
*   Trying ::1... Connection refused
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /6500588/no.php HTTP/1.1
> User-Agent: curl/7.21.0 (i686-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18
> Host: localhost
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 28 Jun 2011 02:10:53 GMT
< Server: Apache/2.2.16 (Ubuntu)
< X-Powered-By: PHP/5.3.3-1ubuntu9.3
< Vary: Accept-Encoding
< Content-Length: 12
< Content-Type: text/html
<
Hello World
* Connection #0 to host localhost left intact
* Closing connection #0

As you can see from the output no cookie has been set. If you do this repeatedly you will get the same output.

Next I create a simple yes.php file which does make use of sessions.
<?php

session_start();

if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 0;
}

echo $_SESSION['count']++;

Let's show the output from curl without storing the cookie:
alfred@alfred-laptop:~/www/6500588$ curl http://localhost/6500588/yes.php -v
* About to connect() to localhost port 80 (#0)
*   Trying ::1... Connection refused
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /6500588/yes.php HTTP/1.1
> User-Agent: curl/7.21.0 (i686-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18
> Host: localhost
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 28 Jun 2011 02:12:47 GMT
< Server: Apache/2.2.16 (Ubuntu)
< X-Powered-By: PHP/5.3.3-1ubuntu9.3
< Set-Cookie: PHPSESSID=hrduhht116e9mikhkkj0gu7126; path=/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Vary: Accept-Encoding
< Content-Length: 1
< Content-Type: text/html
<
* Connection #0 to host localhost left intact
* Closing connection #0
0

As you can see the count is 0, but also a cookie has been set: Set-Cookie: PHPSESSID=hrduhht116e9mikhkkj0gu7126; path=/. with session_id hrduhht116e9mikhkkj0gu7126

If we do not store this cookie when we issue the same curl command again we wil still receive 0 as answer(forget to count) and also receive another cookie.
alfred@alfred-laptop:~/www/6500588$ curl http://localhost/6500588/yes.php -v
* About to connect() to localhost port 80 (#0)
*   Trying ::1... Connection refused
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /6500588/yes.php HTTP/1.1
> User-Agent: curl/7.21.0 (i686-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18
> Host: localhost
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 28 Jun 2011 02:16:42 GMT
< Server: Apache/2.2.16 (Ubuntu)
< X-Powered-By: PHP/5.3.3-1ubuntu9.3
< Set-Cookie: PHPSESSID=ihlj9c9fifl8f0lklu0umesas2; path=/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Vary: Accept-Encoding
< Content-Length: 1
< Content-Type: text/html
<
* Connection #0 to host localhost left intact
* Closing connection #0
0

As you can see hrduhht116e9mikhkkj0gu7126 is not equal to ihlj9c9fifl8f0lklu0umesas2 which means a new cookie has been set and the information in that session is lost.

Next we store the cookie to cookie file issuing -c flag
alfred@alfred-laptop:~/www/6500588$ curl http://localhost/6500588/yes.php -v -c cookie
* About to connect() to localhost port 80 (#0)
*   Trying ::1... Connection refused
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /6500588/yes.php HTTP/1.1
> User-Agent: curl/7.21.0 (i686-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18
> Host: localhost
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 28 Jun 2011 02:27:11 GMT
< Server: Apache/2.2.16 (Ubuntu)
< X-Powered-By: PHP/5.3.3-1ubuntu9.3
* Added cookie PHPSESSID="1h6710hhk84e0k9bj2kg7p03u5" for domain localhost, path /, expire 0
< Set-Cookie: PHPSESSID=1h6710hhk84e0k9bj2kg7p03u5; path=/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Vary: Accept-Encoding
< Content-Length: 1
< Content-Type: text/html
<
* Connection #0 to host localhost left intact
* Closing connection #0
0

As you can see from ls(directory listing) we stored cookie to file named cookie.
alfred@alfred-laptop:~/www/6500588$ ls -al
total 20
drwxr-xr-x  2 alfred alfred 4096 2011-06-28 04:27 .
drwxr-xr-x 19 alfred alfred 4096 2011-06-28 03:59 ..
-rw-r--r--  1 alfred alfred  196 2011-06-28 04:27 cookie
-rw-r--r--  1 alfred alfred   12 2011-06-28 04:00 no.php
-rw-r--r--  1 alfred alfred  114 2011-06-28 04:12 yes.php

That cookie to keep track of the count contains the following information according to cat(shows output of file)
alfred@alfred-laptop:~/www/6500588$ cat cookie
# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

localhost   FALSE   /   FALSE   0   PHPSESSID   1h6710hhk84e0k9bj2kg7p03u5

We next use that cookie to keep track of the count.
alfred@alfred-laptop:~/www/6500588$ curl http://localhost/6500588/yes.php -v -b cookie
* About to connect() to localhost port 80 (#0)
*   Trying ::1... Connection refused
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /6500588/yes.php HTTP/1.1
> User-Agent: curl/7.21.0 (i686-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18
> Host: localhost
> Accept: */*
> Cookie: PHPSESSID=1h6710hhk84e0k9bj2kg7p03u5
>
< HTTP/1.1 200 OK
< Date: Tue, 28 Jun 2011 02:40:18 GMT
< Server: Apache/2.2.16 (Ubuntu)
< X-Powered-By: PHP/5.3.3-1ubuntu9.3
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Vary: Accept-Encoding
< Content-Length: 1
< Content-Type: text/html
<
* Connection #0 to host localhost left intact
* Closing connection #0
1

As you can see we used that cookie with the same ID 1h6710hhk84e0k9bj2kg7p03u5 and the count is 1 instead of 0 when we don't use any cookie(or not store cookie and get new cookie).

So basically i need to authenticate
  users based on his sessions.

sessions are just simple using cookies(sessionid) under the cover. You could for example override the standard implementation for sessions to use the database instead of the filesystem(interesting read!). But I would just use the session_id you receive from PHP(session_id) within your tornado application to authenticate your session because that should be unique(hard to guess).

session_id() returns the session id
  for the current session or the empty
  string ("") if there is no current
  session (no current session id
  exists).

P.S: I hope this answers your question a little bit. If not you could ask in the comments for a little bit more information?


text:
Q: Object values to Enum or type I have a object as :
const bodyParts: Record<string, string>  = {
  HAND: 'hand',
  MOUTH: 'mouth'
}

I have used the object later as
type PartType = "hand"| "mouth"

const data: Array<{part: 'hand' | 'mouth'}> = [{
  part: bodyParts[HAND]
}, {
  part: bodyParts[MOUTH]
}
]

But I want to extract PartType from values of bodyParts. Is there any walkaround for this?
Or maybe to create enum from object and set type as enum. I tried looking for creating enum but didnot got to solution.
I can create Enum but I want to automate task of creation of enum, as bodyparts can be added.

A: I suspect with a broader understanding of your end goal, one could suggest a better alternative to the use of bodyParts as shown in the question, but you can do what you want to do by inferring the type from the constant, like this:
const bodyParts: Record<string, string> = {
    HAND: "hand",
    MOUTH: "mouth",
};

const data: Array<{ part: typeof bodyParts[keyof typeof bodyParts] }> = [
    {
        part: bodyParts.HAND,
    },
    {
        part: bodyParts.MOUTH,
    },
];

playground link
Or it's a bit clearer if we grab an alias for typeof bodyParts:
const bodyParts: Record<string, string> = {
    HAND: "hand",
    MOUTH: "mouth",
};
type BodyParts = typeof bodyParts;

const data: Array<{ part: BodyParts[keyof BodyParts] }> = [
    {
        part: bodyParts.HAND,
    },
    {
        part: bodyParts.MOUTH,
    },
];

playground link
But, if you want to preserve the compile-time type of those (and in particular to ensure that data is a tuple, not just an array), you may do better with const assertions and less explicit typing:
const bodyParts = {
    HAND: "hand",
    MOUTH: "mouth",
} as const;

const data = [
    {
        part: bodyParts.HAND,
    },
    {
        part: bodyParts.MOUTH,
    },
] as const;

playground link


text:
Q: How to know the total test case count in android CTS I am running CTS8.1_r4 for my product. is there any command or way to know total available test cases/ module  or for complete cts package?

A: Unfortunately I have not found any way to see how many test are other than running all the modules, and then run
l r

command and check the last session where the test were completed and add column 2 and 3.
Running the entire cts suite takes some time and sometimes it stops to see how much it take to run and how to continue by running only the failed and the ones that weren't execute check this answers:
How much time It takes to perform all tests using Android CTS tool?
When I run CTS after a few hours the adb connection to device becomes unresponsive


text:
Q: MySQL IF and AND helper I am trying to write an if statement that executes if a user is banned and a time has passed. I have a table named players that has a username, banned, and expires column. How would I check if a player is banned and their ban has expired (expires is before current time) and then call a stored procedure.
This is what I have tried:
IF (SELECT p.banned FROM players p WHERE p.username=user = 1 AND p.expires FROM players p WHERE p.username=user < NOW()) THEN
Call unban(user);
END IF;

I have found how to do it, here is the code but most people reading this probably already know how to do this.
    IF (SELECT p.banned FROM players p WHERE p.username=user)=1 AND (SELECT p.expires FROM players p WHERE p.username=user) < NOW() THEN
    Call unban(user);
    END IF;

A: use it in three steps:

*

*join table users and player

*check where expires > NOW()

*execute the function on result query


text:
Q: how to display and hide a form field according to select another field of form? I use wordpress, contact form 7,

Contact: [checkbox checkbox-932 "email" "Other"]

Other: [text text-327 placeholder]

and I want to display other only when user check other option. Can you do that?

A: As doublesharp pointed out, this is something that is accomplished via JavaScript.
Given this HTML:
<input type="checkbox" id="chkEmail" name="contact" value="email">E-Mail

<input type="checkbox" id="chkOther" name="contact" value="other">Other

<input type="text" id="chkOtherText" name="OtherText">

You would use the following JavaScript:
var chkBox = document.getElementById("chkOther");
var chkBoxTxt = document.getElementById("chkOtherText");

chkBoxTxt.style.display = "none";
chkBoxTxt.setAttribute("aria-hidden", "true");

function toggleOtherText() {
    if (chkBox.checked == true) {
        chkBoxTxt.style.display = "block";
        chkBoxTxt.setAttribute("aria-hidden", "false");
    } else {
        chkBoxTxt.style.display = "none";
        chkBoxTxt.setAttribute("aria-hidden", "true");
    }
}

chkBox.addEventListener("click", toggleOtherText, false);

You will have to modify the script based on the output of the plugin though.

A: I have written the following code in the page where my contact form will be displayed.
$(document).ready(function(){
     $('#moreinfo').hide();
    $('#more input').change(function(){
        if(this.checked)
            $('#moreinfo').show();
        else
            $('#moreinfo').hide();

    });
});

And the fields i need to display, i have put them in a div like this in contact-form-7 forms builder page, where you need to define the fields using shortcodes;

        [checkbox more id:more "Help us to know your requirements better"]

Property Requirement [select property_required class:form-control "Immediate" "15 Days" "1 Month" "6 Months" "1 Year"]

Don't forget to give the id to the checkbox field.


text:
Q: Using fastai to predict a single image New to fastai, I'm just trying to get my model to predict a singular image using learner.predict function, but it gives the error AttributeError: 'str' object has no attribute 'apply_tfms'. Is there something I'm formatting incorrectly?
learn = cnn_learner(data, base_arch=models.resnet18, metrics=accuracy, model_dir="/tmp/models", callback_fns=ShowGraph)
learn.fit_one_cycle(cyc_len=5)
interp = ClassificationInterpretation.from_learner(learn)

learn.predict('test/0.jpg')

A: I think you need to read the image first instead of just passing it to the predict method.
You can use PIL to open and read the image.
# Read and open time image file
from PIL import Image
img = Image.open('test/0.jpg')

# Get the predicted output
preds, _ = learn.predict(img)


text:
Q: Redirect subdomains + http to https using mod_rewrite in Apache Virtual Host I have a virtual host with 1 name and 2 alias, name.domain.com.br, alias1.domain.com.br and alias2.domain.com.br. I need to redirect alias 1 and 2 to name, but it's not working completely, this is my current code:
ServerName name.domain.com.br
ServerAlias alias1.domain.com.br
ServerAlias alias2.domain.com.br
DocumentRoot ****************
ErrorLog ****************
CustomLog ****************
RewriteEngine on
RewriteCond %{SERVER_NAME} =alias1.domain.com.br [OR]
RewriteCond %{SERVER_NAME} =alias2.domain.com.br [OR]
RewriteRule ^/(.*)$ https://name.domain.com.br [L,R=301]

However, this way the redirecting is only working when using http://aliasX.domain.com.br and for some reason it puts two slashes at the end of the link, getting https://name.domain.com.br//. It doesn't work when https:// is used.
I want all variations with or without https to redirect to https://name.domain.com.br.
can you help me?

A:
RewriteCond %{SERVER_NAME} =alias1.domain.com.br [OR]
RewriteCond %{SERVER_NAME} =alias2.domain.com.br [OR]
RewriteRule ^/(.*)$ https://name.domain.com.br [L,R=301]

It doesn't work when "https://" is used.

HTTP and HTTPS require two separate virtual host containers.
No doubt you've put these rules in the virtual host for HTTP only, eg. <VirtualHost *:80>. You would need to repeat the redirect in the virtual host for HTTPS as well. eg. <VirtualHost *:443>. (Although the redirect in the HTTP vHost can be simplified, since you just need to redirect everything to HTTPS - see my solution below.)
HOWEVER, the rule you've posted is incorrect. Due to the erroneous OR flag on the last condition (RewriteCond directive), the redirect will always occur, effectively unconditionally.
You are also discarding the URL-path and redirecting to the homepage? (The browser corrects the missing slash.) I assume this is an error and you should be redirecting alias1.domain.com.br/foo to name.domain.com.br/foo, not name.domain.com.br/?

for some reason it puts two slashes at the end of the link

That is not caused by this rule. Something else must be doing that.
So, the solution then becomes...
###
### HTTP (not secure)
###
<VirtualHost *:80>
ServerName name.domain.com.br
ServerAlias alias1.domain.com.br
ServerAlias alias2.domain.com.br
DocumentRoot ****************
ErrorLog ****************
CustomLog ****************

# Redirect everything to HTTPS and canonical domain
# No need for mod_rewrite, a simple mod_alias Redirect will suffice
Redirect 301 / https://name.domain.com.br/
</VirualHost>

###
### HTTPS (secure)
###
<VirtualHost *:443>
ServerName name.domain.com.br
ServerAlias alias1.domain.com.br
ServerAlias alias2.domain.com.br
DocumentRoot ****************
ErrorLog ****************
CustomLog ****************

# Other SSL directives here...

# Redirect to the canonical domain
RewriteEngine On
RewriteCond %{HTTP_HOST} !=name.domain.com.br [NC]
RewriteRule ^ https://name.domain.com.br%{REQUEST_URI} [R=301,L]
</VirualHost>

The redirect in the HTTPS vHost checks that the request is not already for the canonical hostname, rather than checking that it is one of the aliases.
NB: When checking the requested hostname, use HTTP_HOST instead of SERVER_NAME. By default they are the same, however, depending on the server config, SERVER_NAME might reference the value of the ServerName directive, not the hostname the client requested.
You will need to clear your browser cache is cleared before testing, since any erroneous 301 (permanent) redirects will have been cached. Test first with 302 (temporary) redirects to avoid potential caching issues.
And as mentioned above, if you are still seeing a double slash at the start of the URL-path then something else is doing that.