text:
Q: Sequences in metric spaces Let $(x_n)$ be a sequence in a metric space X. Show that $x_n$ converges to x in X iff for every open set containing x there is a natural number N so that if $n \geq N$ $x_n \in U$
Suppose $x_n \rightarrow x$. Let U be an arbitrary open set containing X. Hence there exists a radius $r>0$ so that $B(x,r) \subset U$. Since $x_n$ converges to x, there exists a natural number N so that if $n\geq N$ then $x_n \in B(x,r) \subset U$
Suppose for each open set U containing x there is a natural number N so that when $n \geq N$ we have $x_n \in U$
Let $\epsilon >0$ be arbitrary. Let $U=B(x,\epsilon)$. Since U is an open subset of X, there is a natural number N so that whenever $n\geq N$ , $x_n \in B(x,\epsilon)$. Since epsilon is artbitrary, $x_n$ converges to x.
Is my proof correct?

A: Yes that's correct. In essence, we only need to check convergence of a sequence using basic open sets (and open balls form a base for the metric topology).
(If you know subbases, then note we could have used subbasic sets too, as we can use finite maxima of indices to talk sequences into induced base elements..)


text:
Q: Minkowski space
*

*In Minkowski space, coordinates which satisfy
$x^2 = t^2 - X^2 > 0$
are in the region of spacetime that is time-like.

*If it's
$x^2 = t^2 - X^2 < 0$
the region is space-like.

*But if
$x^2 = t^2 - X^2 > 0$
then its "trajectory of light-like particles".
I have understood the first two points about time- and space-like regions but I could not get the third one about "light-like particles".
My confusion is - why just light-like particles? There are many other particles at quantum level.

A:
My confusion is about why just light like particles? there are many other particles at quantum level.

You are correct. The terminology is historical in nature. Light was the first massless particle to be discovered. The terminology "lightlike" was established before any other massless particles were discovered. Once other massless particles were discovered it was shown that they also travel along lightlike geodesics, but by then the term "lightlike" was well established.
An alternative term with the same meaning as "lightlike" is "null". If you prefer then you can always use "null" and just understand that people saying "lightlike" mean the same thing.

A: Only particles with zero mass can travel between two events which are separated by a light-like distance. The trajectory is called light-like because photons (light) are massless, and historically the first example of a massless particle, as well as the only example in the 1910's. There are other massless particles, like gluons which would also be able to travel between two events separated by a light-like distance.
The reason why only massless particles are able to travel between two events separated by a light-like distance is that it requires you to travel at exactly the speed of light. You can see this by considering the equation $t^2-x^2=0$, this means that $x=\pm t$. These equations are with the units such that the speed of light $c=1$. Thus the particle taking this trajectory is travelling at the speed of light.

redpajama_set_name: RedPajamaStackExchange


text:
Q: onchange not working in Internet Explorer I have a form with a field like:

    <input name='prod_partnum1' type='text'  id='prod_partnum1' size='20' maxlength='20'  color='#333333' value='$prod_partnum1'>

    <input onchange='ceck_modulo1();' id='prod_partnumver1' name='prod_partnumver1' value=''>

and this is java for check_modulo
function check_modulo1() {

    if (document.modulo.prod_partnumver1.value == "" || document.modulo.prod_partnumver1.value != document.modulo.prod_partnum1.value) {
        document.modulo.prod_partnumver1.value = "";
        document.modulo.prod_partnumver1.style.backgroundColor = "#FF0000";
        document.getElementById('line1').style.backgroundColor = "#FF0000";
        document.modulo.prod_partnumver1.innerHTML = '<audio autoplay="autoplay"><source src="NuclearAlert.mp3" type="audio/mpeg" /><embed hidden="true" autostart="true" loop="false" src="NuclearAlert.mp3" /></audio>';
        document.modulo.prod_partnumver2.focus();
        document.modulo.prod_partnumver1.focus();
    } else {
        document.modulo.prod_partnumver1.innerHTML = '<audio autoplay="autoplay"><source src="SmallBlink.mp3" type="audio/mpeg" /><embed hidden="true" autostart="true" loop="false" src="SmallBlink.mp3" /></audio>';
        document.modulo.prod_partnumver1.style.backgroundColor = "#008800";
        document.getElementById('line1').style.backgroundColor = "#008800";
        document.modulo.prod_partnumver2.focus();
    }

onchange works just with crome and ff but not with any version of internet explorer 7 , 11
The problem is: the text field prod_partnumver1 is field to write barcode scanned by barcode gun, and when a put barcode with a gun if is crome work perfect with internet explorer, not for working need I click with the mouse in another text field.
With chrome it works perfect when a write with barcode scanner verify the field and if is correct go to the next... like java ceck_modulo1 work.....
Thanks for any help.

A: onchange support in IE7 is limited, you should use onclick instead. Further reading on the subject.

A: ok guy's i find solution and i write for other....need mybe tomorrow
ie not work with onchange so....

in this way use the onkeyup function,(not onchange) but wait 200ms in order to give me time
for shot with barcode gun
thank's


text:
Q: How do I identify Ad Distribution Network in BigQuery I have a case statement which produces Default Channel Grouping channel definitions
Does someone know how I can identify the column Ad Distribution Network (open Paid Serach in my link and you will see where that column is needed)?

A: Not all dimensions/metrics are available into BigQuery.  In this case, this dimension (Ad Distribution Network) is only available in Google Analytics because Google AdWords is linked to the Google Analytics view.  That link is not available to Google BigQuery.  This is why you don't see metrics like: impression, clicks, cpc in BigQuery.


text:
Q: postgresql psql command \d does not list indexes I created a table in PGSQL (version 13) using the following command:
db1=# create table temp2(
foo int PRIMARY KEY,
bar varchar(20) UNIQUE NOT NULL
);
CREATE TABLE

The \d or d+ command does not list the associated indexes for the table (contrary to what I gathered from reading various sites.)
db1=# \d temp2
 foo    | integer               |           | not null |
 bar    | character varying(20) |           | not null |

db1=# \d+ temp2
 foo    | integer               |           | not null |         | plain    |              |
 bar    | character varying(20) |           | not null |         | extended |              |

Is there a way I get list indexes associated with a table?
Thank you,
Ahmed.

A: You have tuples_only set to on.
 create table temp2(
foo int PRIMARY KEY,
bar varchar(20) UNIQUE NOT NULL
);

test(5432)=# \d temp2
                      Table "public.temp2"
 Column |         Type          | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
 foo    | integer               |           | not null |
 bar    | character varying(20) |           | not null |
Indexes:
    "temp2_pkey" PRIMARY KEY, btree (foo)
    "temp2_bar_key" UNIQUE CONSTRAINT, btree (bar)

test(5432)=# \pset tuples_only on

test(5432)=# \d temp2
 foo    | integer               |           | not null |
 bar    | character varying(20) |           | not null |

test(5432)=# \pset tuples_only off
test(5432)=# \d temp2
                      Table "public.temp2"
 Column |         Type          | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
 foo    | integer               |           | not null |
 bar    | character varying(20) |           | not null |
Indexes:
    "temp2_pkey" PRIMARY KEY, btree (foo)
    "temp2_bar_key" UNIQUE CONSTRAINT, btree (bar)

Verify by doing:
\pset
border                   1
columns                  0
csv_fieldsep             ','
expanded                 off
fieldsep                 '|'
fieldsep_zero            off
footer                   on
format                   aligned
linestyle                ascii
null                     'NULL'
numericlocale            off
pager                    1
pager_min_lines          0
recordsep                '\n'
recordsep_zero           off
tableattr
title
tuples_only              on
unicode_border_linestyle single
unicode_column_linestyle single
unicode_header_linestyle single

A: You need \di to get the index information. Check the manual:

the letters E, i, m, s, t, and v stand for foreign table, index,
materialized view, sequence, table, and view, respectively.


text:
Q: Why adb is under platform tools? I was going through ADB in android. Why it is under Platform Tools? No matter, what is the platform, it should be able to install app on emulator or real device... then it should come under tools directory  right

A: Generally speaking, the platform-tools/ directory contains binaries that are specific to a development machine's OS. For example, I am running Ubuntu Linux, and so I have Linux versions of adb, etc. Somebody else running Windows would have adb.exe, etc.
The tools/ directory is mostly shell scripts and batch files. It used to be that both were shipped to all development machines. I see that nowadays, they do split them up by development OS (e.g., I have android, not android.bat).


text:
Q: Mobx how to wait till Promise is done then run a different function I have a Mobx Promise that I need to be finished first 100 % then run another function. when I have the function after the .then ... it runs first before the promise is done. but I need all the actions in promise is done first then run the next function
basically i need to know how I can make this sequential
Mobx
    a function(){
        promise<axiosResponse>().then(resp =>{
                console.log('1')
                do this();
                and this();
         })

             now do this function();
              console.log('2')
     }

the results is in this order..
2
1
but I want 1 to be done first
and then start to do 2


text:
Q: File lock not working as expected I have a Thread-extending class that is supposed to run only one instance at a time (cross-process). In order to achieve that, I'm trying to use a file lock. Here are bits of my code:
class Scanner(Thread):

  def __init__(self, path):
    Thread.__init__(self)
    self.lock_file = open(os.path.join(config.BASEDIR, "scanner.lock"), 'r+')
    fcntl.lockf(self.lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)

  # Stuff omitted

  def run(self):
    logging.info("Starting scan on %s" % self.path)

    # More stuff omitted

    fcntl.lockf(self.lock_file, fcntl.LOCK_UN)

I was expecting the lockf call to throw an exception if a Scanner thread was already running and not initialize the object at all. However, I can see this in the terminal:
INFO:root:Starting scan on /home/felix/Music
INFO:root:Starting scan on /home/felix/Music
INFO:root:Scan finished
INFO:root:Scan finished

Which suggests that two Scanner threads are running at the same time, no exception thrown. I'm sure I'm missing something really basic here, but I can't seem to figure out what that is. Can anyone help?

A: Found the solution myself in the end. It was to use fcntl.flock() instead of fcntl.lockf(), with the exact same parameters. Not sure why that made a difference.

A: You're opening the lock file using r+ which is erasing the previous file and creating a new one. Each thread is locking a different file.
Use w or r+a

A: Along with using flock, I had to also open the file like so :
fd = os.open(lockfile, os.O_CREAT | os.O_TRUNC | os.O_WRONLY)

It does not work other wise.


text:
Q: FreePBX / Asterisk: use inbound routes to block spammers/hackers My FreePBX / Asterisk configuration was recently forced into allowing both anonymous inbound calls and SIP guests.  So of course we're now getting blasted with spam/hack attempts.
They show up in the log as:

[2020-05-02 11:09:53] WARNING[30801]: res_pjsip_registrar.c:1051
  registrar_on_rx_request: Endpoint 'anonymous' has no configured AORs

And we get dozens per second.
Can I make a configuration change to essentially block each of these by some mechanism that just makes the caller wait some huge time (like an hour), then hangs up?  I think that would tie up the spammers' resources, and slow the bandwidth they're drawing by orders of magnitude.
So first, is this possible? How do you do it securely?
Second, are there serious downsides to this?  E.g., slowing down any configuration reload by an order of magnitude or some such.
Any related thoughts or advice?

A: I would add in some iptables.
I would start by looking at sip show channels and or using tcpdump and some direct asterisk console commands
tcpdump -i eth0 port sip -l -A | egrep -i 'INVITE sip'
tcpdump -i eth0 port sip -l -A | egrep -i 'User-Agent'

# tcpdump -i ens3 port sip -l -A | egrep -i 'INVITE sip'
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on ens3, link-type EN10MB (Ethernet), capture size 262144 bytes
15:58:28.377294 IP ns542407.ip-144-217-77.net.7112 > 10.0.0.11.sip: SIP: INVITE sip:+10390237920793@107.179.205.23:5060 SIP/2.0
...........INVITE sip:+10390237920793@107.179.205.23:5060 SIP/2.0

asterisk -rx "sip show channels"
Peer             User/ANR         Call ID          Format           Hold     Last Message    Expiry     Peer

13.78.236.138    7780             1317157998-1339  (nothing)        No       Rx: INVITE                 <guest>
144.217.77.27    8888942908       00lFxPc9nsGj22f  (nothing)        No       Rx: ACK                    <guest>

if your requests are INVITE or REGISTER like my example. you can slow them down by iptables manually or learn how to add this at boot depending on your version of Linux. (microsft i have no idea)
iptables -A INPUT -p udp -m udp --dport 5060 -m string --string "INVITE sip:" --algo bm --to 65535 -m recent --update --seconds 60 --hitcount 12 --rttl --name VOIPINV --rsource
iptables -A INPUT -p udp -m udp --dport 5060 -m string --string "INVITE sip:" --algo bm --to 65535 -m recent --set --name VOIPINV --rsource
iptables -A INPUT -p udp -m udp --dport 5060 -m string --string "REGISTER sip:" --algo bm --to 65535 -m recent --update --seconds 60 --hitcount 12 --rttl --name VOIP --rsource
iptables -A INPUT -p udp -m udp --dport 5060 -m string --string "REGISTER sip:" --algo bm --to 65535 -m recent --set --name VOIP --rsource

You can play with different variables (seconds/hitcount/string). I find this effective with fail2ban in slowing them down.  not to mention blocking ranges of countries with ipset that this phone system would not have people connecting from helps alot.


text:
Q: Understanding MOSFET forward-bias safe operating area I am planning to use some power MOSFETS as simple on/off switches for a high voltage battery discharge circuit I'm designing. The circuit will consist of several parallel resistors of relatively high resistance. I want to be able to switch off individual rungs of the ladder in order to add or remove parallel resistance paths to manipulate the overall resistance of the circuit. It will look sort of like this.

simulate this circuit – Schematic created using CircuitLab
I know I haven't shown how I'll drive the gates of the MOSFETs, I left that out of this schematic for simplicity's sake because I have that part of the equation well figured out. R1, R2, and R3 will actually be comprised of multiple 100w resistors in series. Heat dissipation has been considered! Once again, they're represented this way schematically for simplicity.
M4 is supposed to be a master on/off for the circuit. It's sort of redundant given the circuit breaker, but it's easier to automate voltage to a gate than physically throwing a breaker- and the whole purpose of this design is automation.
Also, I'm not really sure if the 300k ohm resistor is necessary, but in my head the idea is to allow a very small current through the circuit when the MOSFETS are turned off, which should mean that if I throw the circuit breaker switch to OFF that the circuit will bleed off any residual charge into the negative terminal of the battery. Correct me if that is wrong or unnecessary or I should go about it in a different way.
I believe I have properly sized the MOSFETS I want to use, but I've run across the following graph in a data sheet that I somehow overlooked before. At first glance I thought it disqualified the MOSFET I'm looking at, but I think I was misinterpreting. Here is the digikey page for the actual FET in question and here is the graph I'm a bit puzzled by:

Now here is how I think I can interpret this:
If, for instance, M1 and M4 are both ON given R1's resistance the current through each FET should be about 240 mA. And if I look at the graph above, it would seem that at 240v that 240mA is beyond the Safe Operating Limit for continuous DC.
Except the Vds isn't actually 240 when the M1 is ON, it is actually basically zero since R1 drops almost all of the voltage. So both M1 and M4 are going to be seeing decent current but at very low Vds. In other words, they'll be operating in the safe region.
When M1, M2, and/or M3 are ON but M4 is OFF, R1, R2, and/or R3 won't drop the voltage, so the Vds of M1, M2 and M3 will indeed be 240v, however the current will be near zero. In other words, they'll be operating in the safe region.
Is this correct? Do I have it right?
If I do have it right, it would seem that the only time this would be an issue is if I were to, say, swap the positions of M4 and the Circuit Breaker. If I did that, there would be no resistive load to drop the voltage before the FET, so Vds would actually be 240v and current would be the same, moving things outside of the Safe Operating Area.
Perhaps this is exactly what the term "Forward-Bias" means in this context. I admit to not fully understanding the term as applied here.

A: The FET doesn't switch instantaneously. The "OFF" point (I=0, V=Max) has zero dissipation, and the "ON" point (I=Max,V=0) has low dissipation. When switching, both I and V will go around on a trajectory that you can plot, for example using the simulator. At each point where V and I are not zero, there is a non-zero instantaneous dissipation V*I, and somewhere along the line there is a dissipation peak.

The SOA graph has V and I as axes, and lines labeled with time. So if your MOSFET is going to spend 1 second at 100V AND 1A, which means 100W, this would be point "A" (red). This is quite far to the right of the "1 second" line, which means it will absolutely blow up. However, 100V and 0.4A (point B) is survivable for one second (note Tc=25°C means this will only happen if the MOSFET is well cooled, and "single pulse" means it has to cool down before doing it again).
The point C "high voltage and zero amps" is not on the graph, because zero doesn't fit on the log scale. But it's as good as there, and this is in the "DC" zone, which means an unlimited amount of time. Same thing for point D, the MOSFET being ON with little voltage and some current. Note this one depends more on the heat sink than the other, because it will dissipate RdsON x I^2.
In fact, you can plot the entire curve of I,V during the switching event.
The red and blue lines simply represent I and V varying together as it switches. The problem with this plot is it doesn't say how long it stays at each point, but that will do.
If the load was inductive, that would be the blue line, current stays rather constant until the FET switches fully. For a resistive load, current will vary more smoothly, so the peak dissipation is lower.
On the graph that the I/V trajectory doesn't even cross the DC line. So if you switch it at a reasonable speed, say 100µs, to make sure it doesn't make EMI, it's going to spend less than a few tens of µs at a peak dissipation that it would be able to tolerate for an unlimited amount of time with a proper heat sink.
Basically, this means your MOSFET is way too chunky, which is bad if you want to save 50 cents on the cost. But if it's a prototype, then it's nice, because it means the FET won't blow due to SOA.
If switching frequency is high (for example you try to PWM the resistors) and it switches too slowly, then cumulative switching losses may overheat it. So if you plan to PWM it, you got to put numbers on the switching losses. If you don't plan to, no need to bother.
Now...

The wires at (1) are probably a mistake if you want to control each resistor.
When all FETs are off, the potential of point 2 is not known. It depends on leakage through M1-3. That could raise the voltage on their sources quite a bit. If one of M1-3 is turned on while M4 is off, then the voltage at point 2 will rise to 240V.
This could be a problem for the drivers. The whole point of low-side FETs is they're simple to drive, but in this case, you can't use low-side drivers for M1-3.
Another thing is the resistors. If they are big wirewounds, they'll have some inductance. A flywheel diode across them could be a good idea. It depends on the inductance and the switching time.

A: Your first question has to do with M1 and M4 conducting.  Because they both have \$550 \text{ m}\Omega \$ resistance, a little over \$1\text{ }\Omega\$ in all, they will drop so little voltage that they both will be operating well within the safe zone.
Your second question has to do with M4 not conducting, which means that M1, M2, and M3 also will not be conducting.  There will be current through R4, though, and it will drop nearly all of the 240 V.  This will expose M4 to this voltage, but without any current.  The datasheet says the device can tolerate 650 V in the off state, so this still is in the safe operating region.
Your third question has to do with interchanging the circuit breaker and M4.  If there is no conduction, the 650 V tolerance still is ample.  With conduction, the resistors still drop nearly all the voltage, so the transistors remain in the safe operating zone.
Your transistors are chosen well:  they withstand the off-voltage and they tolerate the on-current.  Using the bleed resistor incurs a small loss of efficiency during normal operation, but is fine for removing charge once the circuit breaker is open.
There is an issue associating with swapping the positions of M4 and the circuit breaker:  the gate will need to be high relative to its source voltage.  This is feasible with a voltage shifter, but generally inconvenient.


text:
Q: Big oh and big Omega? I have question is about big oh and big omega
if $f(n)$ is $\Omega(n^2)$ is $f(n)$ $O(n)$?

A: No. The first means that for some $n_0$ and a positive $c$ it is $f(n) \ge c n^2$; the second one says that for some $n_0'$ and a positive $c'$ it is $f(n) \le c' n^2$. For example, $n^3 = \Omega(n^2)$ but $n^3 \ne O(n^2)$; while $n \ne \Omega(n^2)$ but $n = O(n^2)$.


text:
Q: How come I get NA values when joining non-spatial object to geometry data/polygon? I am trying to join a non-spatial object (Merged_Census2011) to a shapefile polygon (LDN_wards) by "ward.name". It seems to work fine until I look at the newly created object and see that all data has turn into NAs. Here's how I proceeded.
#Join Merged_Census2011 data to LDN_wards shapefile
LDN_wards <- readOGR(dsn = "data", layer = "LDN_wards")
head(LDN_wards@data)
#Explore the object
plot(LDN_wards)
summary(LDN_wards)
names(Merged_Census2011)
names(LDN_wards)
names(LDN_wards) <- c("Code", "ward.name") #rename LND-wards name heading to ward.name so it can be matched later

#Join datasets
LDN_wards@data <- left_join(LDN_wards@data, Merged_Census2011)
head(LDN_wards@data)

And I get:
LDN_wards@data <- left_join(LDN_wards@data, Merged_Census2011)
Joining by: "ward.name"
Warning message:
In left_join_impl(x, y, by$x, by$y) :
joining factors with different levels, coercing to character vector
> head(LDN_wards@data)
   Code    ward.name ward.code.x electorate votescast ward.code.y per.owner per.white per.noquals per.degree per.couple
1 E05000001   Aldersgate        <NA>         NA        NA        <NA>        NA        NA          NA         NA         NA
2 E05000002      Aldgate        <NA>         NA        NA        <NA>        NA        NA          NA         NA

I have the intuition this is because there is a different number of row between the two sets. Could that be the issue? Is it not possible to join datasets with different row levels (whereby the missing data in one just remains unmatched by the corresponding observations)?
I had compared the two datasets  as follows:
#Compare the two datasets
nrow(LDN_wards)
nrow(Merged_Census2011)
LDN_wards$ward.name %in% Merged_Census2011$ward.name
LDN_wards$ward.name %in% Merged_Census2011$ward.name
> nrow(LDN_wards)
[1] 787
> nrow(Merged_Census2011)
[1] 668
> LDN_wards$ward.name %in% Merged_Census2011$ward.name
  [1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSEFALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [21] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
  [41]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE ETC...
> summary(LDN_wards$ward.name %in% Merged_Census2011$ward.name)
   Mode   FALSE    TRUE    NA's
logical      24     763       0

Could it be because of the FALSE=24? If it is, how do I delete those FALSE?
Apologies if this sounds obvious, I'm fairly new :)
Thanks for your help!

A: I have just tried again using the (newly discovered) inner_join function and it seemed to work. If I understood well, the inner_join function only merges the matching rows... So I thought it would be better. And indeed, I do not get NA values anymore. But strangely I get duplicated observations... So if anyone has a better suggestion, you're very welcome to share. See my proceedings below.
#Join datasets
LDN_wards@data <- inner_join(LDN_wards@data, Merged_Census2011)
head(LDN_wards@data, n=10)

> #Join datasets
> LDN_wards@data <- inner_join(LDN_wards@data, Merged_Census2011)
Joining by: c("ward.name", "ward.code.x", "electorate", "votescast","ward.code.y", "per.owner", "per.white", "per.noquals", "per.degree", "per.couple", "per.higher.managerial", "per.christian", "per.no.car", "per.limill", "per.goodhealth", "per.males", "per.aged60plus")
Warning message:
In inner_join_impl(x, y, by$x, by$y) :
joining character vector and factor, coercing into character vector
> head(LDN_wards@data, n=10)
    Code      ward.name ward.code.x electorate votescast ward.code.y per.owner per.white per.noquals per.degree per.couple
1  E05000007         Bridge   E05000497       8677      5654   E05000497      69.8      71.9        19.9       29.9       55.3
2  E05000026          Abbey   E05000026       8110      4712   E05000026      32.7      28.1        16.4       34.5       47.2
3  E05000026          Abbey   E05000026       8110      4712   E05000455      48.5      73.4        10.1       55.4       52.4
4  E05000026          Abbey   E05000455       7250      4808   E05000026      32.7      28.1        16.4       34.5       47.2
5  E05000026          Abbey   E05000455       7250      4808   E05000455      48.5      73.4        10.1       55.4       52.4
6  E05000027         Alibon   E05000027       6971      4127   E05000027      45.1      70.1        31.2       16.7       49.2
7  E05000028      Becontree   E05000028       7535      4538   E05000028      46.7      58.8        28.0       20.6


text:
Q: Исполнение JS-кода из расширения для chrome Недавно начал писать расширения для chrome. Мне нужно, чтобы, например, при нажатии в расширении на кнопку, на внешней странице исполнялся JS код.
Как это возможно сделать?


text:
Q: AngularJS : index not updating after removing array item(s) by index I am trying to remove an item from AngularJS's scope array variable using the index of the item.
(if you're to stop reading here thinking this is a duplicate, please jump to foot note links, I was able to find similar but not same questions which were answered - Or, I could have missed something so if you find EXACTLY same question I'd appreciate if you would please share the SO link for it ! Thx)
here is my example :
http://jsbin.com/seyaje/3/edit?html,output

The problem I see is, the index does not get updated automatically - every time - hence wrong item gets deleted or if the index is 'out of bounds' the item does not get deleted at all.
What I personally prefer is to pass index in my scenario, and I think it is relatively less work about not having to figure out indexes repetitively. (if the index is correct !)
How could I possibly fix this using AngularJS 1.25 ? Your constructive help is always appreciated !

This might be a similar question to followings :
AngularJS remove item from scope
How to remove an Item from scope AngularJS
What I am trying to accomplish, seems little similar to :
https://stackoverflow.com/a/23810035 or http://plnkr.co/edit/51SNVMQjG3dsmpYI5RyY?p=preview
Somewhat similar unanswered question (finds the object and deletes by index):
remove clicked item angularjs

A: The myIndex property gets set by the initialization of the repeat and it isn't updated appropriately.  Instead you could just work with $index.  This will update appropriately when the array changes and delete the correct elements.

    {{$index}}
    {{i.Id}}
    {{i.Name}}
    {{i.Type}}

        <button data-ng-click="deleteItemByIndex($index)">×</button>


text:
Q: Is this a 'justified' double negative? The answer may require some Old English knowledge. The following is is my translation of a sentence from Bede's Account of the Conversion of King Edwin. Old English tolerated the double negative, and I am trying to translate the text in such a way that would carry the spirit of the original language. Can I have thoughts on the grammaticality of the translation?  It does sound odd, I know, but it is not supposed to feel like ME. I particularly am interested in feedback about my use of 'neither nothing' which I am highly suspecting to sound 'off'.
The original Text:

Ic þe soðlice andette, þæt ic cuðlice geleornad hæbbe, þæt eallinga
  nawiht mægenes ne nyttnes hafað sio æfæstnes, þe we oð ðis hæfdon &
  beeodon.

The translation and the construct in doubt

I truthfully confess to you that I clearly learned that, neither
  nothing of virtue, nor nothing of usefulness does that religion have,
  which we till this day had and practiced.

P.S: I am aware that the forum does not accept translation questions. My question is NOT about the accuracy of the translation; it is more about clearing out the doubt I have about the said construct.

A:
I truthfully confess to you that I clearly learned that, neither
  nothing of virtue, nor nothing of usefulness does that religion have,
  which we till this day had and practiced.

I would suggest that a cleaner, more modern translation might be something like:

I truthfully confess to you that I clearly learned that nothing of
  virtue or of usefulness does that religion have, which we till this
  day had and practised.

or:

I truthfully confess to you that I clearly learned nothing of
  virtue nor of usefulness that that(this?) religion has, which we till this
  day have had and practised.

The 'of', wherever it is, is largely is largely an oratorical flourish these days:
"We want a community of honesty, of hard work, of religion----" Etc, Etc.
or even:
"We want a community of honesty, a community of hard work, a community of religion----" Etc, Etc.
Hope this helps
dmk

A: Not knowing Old English, I can say that double negatives do appear in translations of Classic texts if I remember correctly, so to a scholarly or academic audience it might be fine.


text:
Q: Rendering Json response in grails view I am querying twitter api to get the tweets with a hashtag in grails 2.1.1.
My Controller is
import grails.converters.*
import org.codehaus.groovy.grails.web.json.*; // package containing JSONObject, JSONArray,...
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

    class NepTweetController {
        def index() {
              //def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
              def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
              def http = new HTTPBuilder(restEndpointUrl);

              // perform a GET request, expecting JSON response data
              http.request( GET, JSON ) {
                    //uri.path = '/search.json'
                    //uri.query = [ q: '%23nepal' ]
                                response.success = { resp, json ->
                                             // def tweetsResult = json.results;
                                             // List parsedList = JSON.parse(json) as List;
                                             // JSONObject tweetJson = JSON.parse(json);
                                             //def tweetJson = JSON.parse(json);
                                              def tweets = new JSON(json) as Map;

                                              render(view: "index", model: [message: "Request sent" , tweets: tweets]);
                                 }
              }//end of request
        }//end of method
    }

I successfully get the json response as follows :
  {
      "completed_in": 0.017,
      "max_id": 271907240007581696,
      "max_id_str": "271907240007581696",
      "next_page": "?page=2&max_id=271907240007581696&q=%23nepal%2F",
      "page": 1,
      "query": "%23nepal%2F",
      "refresh_url": "?since_id=271907240007581696&q=%23nepal%2F",
      "results": [
        {
          "created_at": "Fri, 23 Nov 2012 09:25:12 +0000",
          "from_user": "iBshnu",
          "from_user_id": 25051623,
          "from_user_id_str": "25051623",
          "from_user_name": "Bishnu Bhattarai",
          "geo": null,
          "id": 271907240007581696,
          "id_str": "271907240007581696",
          "iso_language_code": "ne",
          "metadata": {
            "result_type": "recent"
          },
          "profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2622309791\/42z33jnw1kak9ttyqkrf_normal.jpeg",
          "profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2622309791\/42z33jnw1kak9ttyqkrf_normal.jpeg",
          "source": "web<\/a>",
          "text": "RT @dipakbhattarai: \u0930\u093e\u0937\u094d\u091f\u094d\u0930\u092a\u0924\u093f \u0921\u093e. \u0930\u093e\u092e\u092c\u0930\u0923 \u092f\u093e\u0926\u0935\u0926\u094d\u0935\u093e\u0930\u093e \u092e\u0919\u094d\u0938\u093f\u0930 \u0967\u096a \u092d\u093f\u0924\u094d\u0930 \u0926\u0932\u0939\u0930\u0941\u0932\u093e\u0908 \u0930\u093e\u0937\u094d\u091f\u094d\u0930\u093f\u092f \u0938\u0939\u092e\u0924\u093f\u0915\u094b \u0938\u0930\u0915\u093e\u0930 \u092c\u0928\u093e\u0909\u0928 \u0906\u0935\u094d\u0939\u093e\u0928\u0964 #Nepal",
          "to_user": null,
          "to_user_id": 0,
          "to_user_id_str": "0",
          "to_user_name": null
        },
        {
          "created_at": "Fri, 23 Nov 2012 09:24:58 +0000",
          "from_user": "Phanindra07",
          "from_user_id": 63104333,
          "from_user_id_str": "63104333",
          "from_user_name": "Phanindra Dahal",
          "geo": null,
          "id": 271907179404095488,
          "id_str": "271907179404095488",
          "iso_language_code": "en",
          "metadata": {
            "result_type": "recent"
          },
          "profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2417859753\/febstuo4p4zltimnpky0_normal.jpeg",
          "profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2417859753\/febstuo4p4zltimnpky0_normal.jpeg",
          "source": "web<\/a>",
          "text": "RT @DeepakAdk: Chef's assault on #Nepal #Maoist reflects grassroots anger, excellent piece by my #AFP colleague @FrankieTaggart http:\/\/t.co\/M47qJeoD",
          "to_user": null,
          "to_user_id": 0,
          "to_user_id_str": "0",
          "to_user_name": null
        }
[....more....]

My /views/nepTweet/index.gsp is
<meta name='layout' content='main'/>
${message}

Tweets

<g:each in="${tweets}" var="tweet">

${tweet.text}

</g:each>

But, I get error parsing json to grails Map.
Error I get is :
Error 500: Internal Server Error
URI
/WhoTweetsNepal/nepTweet
Class
groovy.lang.MissingMethodException
Message
No signature of method: grails.converters.JSON.entrySet() is applicable for argument types: () values: [] Possible solutions: every()

I went through How do I access A JSON Object(String) from GSP page?, but couldn't get help.
Helpppp!!!

A: You definitely want
def tweetJson = JSON.parse(json);

(which will return a JSONObject, which is a Map) instead of
def tweetJson = new JSON(json) as Map;

but it looks like you have a bit of a name clash in your code - presumably the JSON in
http.request( GET, JSON )

is intended to be the HTTPBuilder content type rather than grails.converters.JSON.  If you can clear up this name clash (i.e. remove the import static and say ContentType.JSON) then things may run more smoothly.

A: With to the point suggestions from Ian Roberts, I got the solution with my final Controller to be(realising there is no need to parse it) :
import grails.converters.*
import org.codehaus.groovy.grails.web.json.*; // package containing JSONObject, JSONArray,...
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

    class NepTweetController {
        def index() {
              def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
              def http = new HTTPBuilder(restEndpointUrl);

              // perform a GET request, expecting JSON response data
              http.request( GET, ContentType.JSON ) {
                    //uri.path = '/search.json'
                    //uri.query = [ q: '%23nepal' ]
                                response.success = { resp, json ->
                                             def tweetsResult = json.results;

                                              render(view: "index", model: [message: "Request sent" , tweets: tweetsResult]);
                                 }
              }//end of request
        }//end of method
    }


text:
Q: Best way to keep the list of servers, OSs, Databases and so on I have a Microsoft Visio file in which I list the list of sever my organization has, but not only that, also wich OS they have, Databases, and so on. The problem with the Visio file is that is something static and very graphic oriented. I would like to have a more structured approach while having at the same time a graphical representation of this information.
Do you have a better approach?
Thanks for your help


text:
Q: what is the default AES config in crypto-js? https://cryptojs.gitbook.io/docs/ just said "CryptoJS supports AES-128, AES-192, and AES-256. It will pick the variant by the size of the key you pass in. If you use a passphrase, then it will generate a 256-bit key."
But what is default config like mode, padding, iv ? I notice there is a CipherOption for mode & padding
interface CipherHelper {
    encrypt(message: WordArray | string, key: WordArray | string, cfg?: CipherOption): CipherParams;
    decrypt(ciphertext: CipherParams | string, key: WordArray | string, cfg?: CipherOption): WordArray;
}

But I can't figure what the default value, e.g. it does not look like ECB mode by default.
My second question is how does it decide to use ace-128, aes-192, ase-256 based on the key I input, e.g. if I use a short string key like "my password" will it decide to use ace-128 then ? How ?
--- update ---
Except for the answer, I find cryptojs: How to generate AES passphrase is also helpful to understand the passphrase used in CryptoJS.

A: Your link to the CryptoJs-docs (https://cryptojs.gitbook.io/docs/) reveals the answers to your questions but we do have two scenarios.

*

*you are feeding the encrypt function with a passphrase or 2) you are giving an explicit key as input.

Scenario 1: you feed a password/passphrase like "myPassword" to the function:
CryptoJS.AES.encrypt("Message", "Secret Passphrase");

Now CryptoJs derives a 32 byte long encryption key for AES-256 and a 16 byte long initialization vector (iv) from the password, encrypts the "Message" using this key, iv in AES mode CBC and (default) padding Pkcs7.
Scenario 2: you feed a key to the function:
var key = CryptoJS.enc.Hex.parse("000102030405060708090a0b0c0d0e0f");
var iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");
var encrypted = CryptoJS.AES.encrypt("Message", key, { iv: iv });

Now CryptoJs takes the key for AES-128/192/256 depending on the key length (16/24/32 bytes) and the 16 byte long initialization vector (iv) from the password, encrypts the "Message" using this key, iv in AES mode CBC and (default) padding Pkcs7.
more options: You can use other modes or padding when using the options like this (key + iv derivation from passphrase, AES mode CFB and padding AnsiX923):
var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase", {
  mode: CryptoJS.mode.CFB,
  padding: CryptoJS.pad.AnsiX923
});


text:
Q: Can't run scrapy command on heroku I'm trying to get the scrapy command to run when I type heroku run scrapy. However I just get bash: scrapy: command not found.
I have Scrapy in my requirements.txt file as well as a scrapy.cfg file. I can run scrapy locally just fine.
Anybody know what I'm possibly missing here?


text:
Q: KERN_PROTECTION_FAILURE at address using static map and std::make_pair I get this error
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0xb064425c

When the following function is called:
const std::map<FunctionID, std::string> getEnumElementsStringRepresentation() {
  static bool is_initialized = false;
  static std::map<FunctionID, std::string> enum_string_representation; // Fails here
  if (false == is_initialized) {
    enum_string_representation.insert(std::make_pair(FunctionID.capabilities, "capabilities"));
    ... many more similar inserts
    is_initialized = true;
  }
  return enum_string_representation;
}

It appears to be a read/write error but I'm not sure the best way to debug.

A: You said your code is multi-threaded. Because of the function-static map instance, getEnumElementsStringRepresentation is not re-entrant (usually). You would have to protect the function with a mutex, or use thread-local storage.


text:
Q: How to upload a file in a Sharepoint library subfolder using c#? I need to upload a file using c# console app in a sharepoint library. I manage to upload it to the parent library only. But the requirement is to upload it on its sub folder.

So here's the Folder Structure:
Root Folder
-Sub Folder 1
---Sub Folder 2
----Sub Folder 3
I need to upload it in Sub Folder 3. Right now, I'm only able to upload on the Root Folder.
It throws an error when I tried to input the Sub Folder 3 in the GetByTitle method, but when it's the root folder, it is succeeding to upload.
Here's my code.
using (ClientContext clientContext = new ClientContext(siteURL))
{
    clientContext.Credentials = new System.Net.NetworkCredential(@"username", "password", "domain");

    var web = clientContext.Web;

    // Create the new file
    var newFile = new FileCreationInformation();
    newFile.Content = System.IO.File.ReadAllBytes(@"C:\filepath\test.xlsx");
    newFile.Overwrite = true;
    newFile.Url = "Test Upload.xlsx";

    List list = web.Lists.GetByTitle("Service Oriented Architecture (SOA)");
    clientContext.Load(list);
    clientContext.ExecuteQuery();
    clientContext.Load(list.RootFolder);
    clientContext.Load(list.RootFolder.Folders);

    clientContext.ExecuteQuery();

    foreach (Folder SubFolder in list.RootFolder.Folders)
    {
        if (SubFolder.Name.Equals("07 - SOA Environment"))
        {
            //What's next?
        }
    }
}

A: There are several options how to specify sub folder while uploading the file using CSOM
There are two assumptions about the provided solutions below:

*

*The library name(url) is Documents and has the following folder structure:
Folder/Sub Folder/Sub Sub Folder/Sub Sub Sub Folder/

*Folder structure already exists
Using FileCreationInformation.Url property
Use FileCreationInformation.Url property to specify the folder url for a uploaded file.
The following example demonstrates how to specify relative url (a slightly modified version of your example, the main difference comes in specifying FileCreationInformation.Url)
var uploadFilePath = @"c:\tmp\SharePoint User Guide.docx";
var fileCreationInfo = new FileCreationInformation
{
    Content = System.IO.File.ReadAllBytes(uploadFilePath),
    Overwrite = true,
    Url = Path.Combine("Documents/Folder/Sub Folder/Sub Sub Folder/Sub Sub Sub Folder/", Path.GetFileName(uploadFilePath))
 };

 var list = context.Web.Lists.GetByTitle("Root Folder");
 var uploadFile = list.RootFolder.Files.Add(fileCreationInfo);
 context.Load(uploadFile);
 context.ExecuteQuery();

Using Web.GetFolderByServerRelativeUrl method
Use Web.GetFolderByServerRelativeUrl method to retrieve a folder where file have to be uploaded:
public static void UploadFile(ClientContext context,string uploadFolderUrl, string uploadFilePath)
{
    var fileCreationInfo = new FileCreationInformation
    {
            Content = System.IO.File.ReadAllBytes(uploadFilePath),
            Overwrite = true,
            Url = Path.GetFileName(uploadFilePath)
    };
    var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
    var uploadFile = targetFolder.Files.Add(fileCreationInfo);
    context.Load(uploadFile);
    context.ExecuteQuery();
}

Usage
using (var ctx = new ClientContext(webUri))
{
     ctx.Credentials = credentials;

     UploadFile(ctx,"Documents/Folder/Sub Folder/Sub Sub Folder/Sub Sub Sub Folder",filePath);
}

A: You need to get sub folder within folder. like below
docs.RootFolder.SubFolders

Remaining things is same, just need to add in same folder.
try to go into folder like below
docs.Folders["FolderName"]


text:
Q: ORA-06503: PL/SQL: Function returned without value web service call i am using the oracle apex and 10g database i use the following code to call the web service it gives me the folowing error
ORA-06503: PL/SQL: Function returned without value
any one can help me thnx
the code i use is
{
    declare
    l_envelope CLOB;
    l_xml XMLTYPE;
    l_movie VARCHAR2(4000);
    BEGIN
    l_envelope := ' <?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:tns="http://www.ignyte.com/whatsshowing"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
          <tns:GetTheatersAndMovies>
            <tns:zipCode>43221</tns:zipCode>
             <tns:radius>5</tns:radius>
           </tns:GetTheatersAndMovies>
               </soap:Body>
                 </soap:Envelope>';

       l_xml := apex_web_service.make_request(
        p_url => ' http://www.ignyte.com/webservices/ignyte.whatsshowing.webservice   \/moviefunctions.asmx',
     p_action => ' http://www.ignyte.com/whatsshowing/GetTheatersAndMovies',
     p_envelope => l_envelope );

   l_movie := apex_web_service.parse_xml(
     p_xml => l_xml,
     p_xpath => ' //GetTheatersAndMoviesResponse/GetTheatersAndMoviesResult/Theater/Movies/Movie/Name[1]',
     p_ns => ' xmlns="http://www.ignyte.com/whatsshowing"' );

         END;}


text:
Q: What to save in Preference.onSaveInstanceState I'm creating a few custom preferences for an Android application.
The two I'm creating is a SeekBarPreference and a MultiSelectPreference.
The SeekBarPreference is quite simple, it inherits from DialogPreference and has a custom content view in which it displays a SeekBar.
The MultiSelectPreference is a bit more advanced, it opens a Dialog when clicked which has a custom ListView and a button. When the button is pressed another Dialog is opened which has a generic ListView.
What should I save in onSaveInstanceState() for these preferences?
For the SeekBarPreference I assumed that I needed to save the value if isPersistant() is false and also the current slider progress (so I could restore) but after browsing the android source code doesn't seem like EditTextPreference cares about storing it's current text, only the saved value.
The DialogPreference does however save the current state of the dialog but it doesn't seem like that saves the state for its children, but it's quite hard to tell, I got lost when I came to what a Window will do when onSaveInstanceState is called since it's abstract and I didn't find any subclasses.
Any insight to this problem would be greatly appreciated, my goal is to open source the code later so I want to do this right.

A: After a lot of testing and code browsing these are my conclusions:

*

*You do not need to save the state of views if they are connected to a root view because they are saved when the root view gets saved, in my case that means I don't have to save the state of the SeekBar, that's handles when the dialog is saved by the super class.

*You should always save your value if you aren't persistant

*You should save all instance variables that change/can change after the preference is created, this means variables that can be changed with a setter or that can change over time.

Even though the last point is not followed by Google them selves they are wrong and an easy example shows why:
Imagine you have a PreferenceActivity which contains two things; a ListPreference with 10 items and a generic preference that when pressed adds an item to the end of the ListPreference.
Now imagine that the user starts the application and presses the generic preference, the ListPreference now has 11 items.
The user now opens the ListPreference.
If the application is closed and then killed the instance is saved, but the ListView only saves the stored value (if it isn't persistant), so when it reopens it only contains the initial 10 item.
Below is an example of a minimal app that displays the problem, just click on the button, open the list (there should be 4 items), close the app with the list open, kill the app from adb and reopen it, the list now has three items.
PreferenceTest.java
package com.example;

import java.util.ArrayList;
import java.util.Arrays;

import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;

public class PreferenceTest extends PreferenceActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        getPreferenceScreen().findPreference("button").setOnPreferenceClickListener(new OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                ListPreference lp = (ListPreference) getPreferenceScreen().findPreference("list");

                ArrayList<CharSequence> al = new ArrayList<CharSequence>(Arrays.asList(lp.getEntries()));
                CharSequence items[] = new CharSequence[al.size()+1];
                al.add("Item " + items.length);
                lp.setEntries(al.toArray(items));

                al = new ArrayList<CharSequence>(Arrays.asList(lp.getEntryValues()));
                al.add("Value " + items.length);
                lp.setEntryValues(al.toArray(items));

                return true;
            }
        });
    }
}

res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">

  <ListPreference
    android:key="list"
    android:entries="@array/list_entries"
    android:entryValues="@array/list_values"
    android:title="Example list"
    android:summary="This list contains 3 items by default" />

  <Preference
    android:key="button"
    android:title="Example button"
    android:summary="When clicked this adds an item to the list" />

</PreferenceScreen>

res/values/list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="list_entries">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
    </string-array>

    <string-array name="list_values">
        <item>Value 1</item>
        <item>Value 2</item>
        <item>Value 3</item>
    </string-array>
</resources>


text:
Q: OpenQA.Selenium.StaleElementReferenceException stale element reference: element is not attached to the page document I am building a c# app that scrapes a website. I think this problem is caused because the page is reloaded after submitting the form again and again. I have to select an option from a select list then press enter and wait for the page to reload with the new results. But after reload this results in this error;
Exception thrown: 'OpenQA.Selenium.StaleElementReferenceException' in WebDriver.dll
An exception of type 'OpenQA.Selenium.StaleElementReferenceException' occurred in WebDriver.dll but was not handled in user code
stale element reference: element is not attached to the page document (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64)

My code looks like this;
SelectElement departmentSelect = new SelectElement(driver.FindElement(By.Id("select")));
IList<IWebElement> departmentOptions = departmentSelect.Options;
foreach (IWebElement option in departmentOptions)
{
    new SelectElement(driver.FindElement(By.Id("select"))).SelectByText(option.Text);
    driver.FindElementById("butSearchByType").Click();
}

I have also tried something like;
WebDriverWait wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(2));
new SelectElement(driver.FindElement(By.Id("select"))).SelectByText(option.Text);
driver.FindElementById("butSearchByType").Click();
var ready = wait.Until(ExpectedConditions.ElementExists(By.Id("select")));

This just runs out of time and I get an exception of time has out.

A: You have a problem with situation when you want do something on page but page isn't fully loaded.
In my project before any action I'm waiting for page fully loaded, and also for ajax.
it is a sample code:
Wait.Until(driver1 => ((IJavaScriptExecutor)Driver.WebDriver).ExecuteScript("return document.readyState").Equals("complete"));

Where Wait is a WebDriverWait.
For ajax is similar:
ExecuteScript("return jQuery.active == 0")


text:
Q: bash for loop with range defined not working When I define range for a for loop, it doesn't seem to work.
If I define the numbers instead it does work.
This doesn't work:
range="10 {4..28..8}"
for i in $range; do
echo $i
done

Output:
10
{4..28..8}

This works:
for i in 10 {4..28..8}; do
echo $i
done

Output:
10
4
12
20
28

A: The docs say that brace expansion happens before parameter expansion. When you define range="10 {4..28..8}" no brace expansion happens because it is quoted. When you execute for i in $range it doesn't work like you intend because of the precedence.

A: Use an array.
range=(10 {4..28..8})
for i in "${range[@]}"; do
  echo "$i"
done

(The brace expression is expanded when the array is created, not when the for loop is executed. But it really doesn't make much difference.)


text:
Q: Error updating styles paperclip I want to update my styles in paperclip, but when i run the command, a error is returned. Here is the code of my styles:
image.rb
class Image < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
  validates_presence_of :image
  has_attached_file :image, :processors => [:ffmpeg],
    :styles => { :video => { :geometry => "640x480", :format => 'mp4' },
    :thumb => { :geometry => "100x100>", :format => 'jpg' },
    :large => { :geometry => "400x300>", :format => 'jpg' },
    :medium => { :geometry => "400x200>", :format => 'png' },
    :icon => { :geometry => "36x36>", :format => 'jpg' },
    :profile => { :geometry => "28x28>", :format => 'jpg' } },
    :default_url => "/images/:style/missing.png"

end

Returned Error:
Regenerating Image -> image -> [:icon, :large, :medium, :profile, :thumb, :video]
rake aborted!
Cocaine::CommandNotFoundError

How i solve this error?

A: It seems to be that you have not installed the "paperclip-ffmpeg" gem.
See this link: https://github.com/owahab/paperclip-ffmpeg#requirements


text:
Q: How to control layout of polymorphic Kotlinx serialization? I have a json that holds a list of polymorphic objects,
{
  "someList": [
    { "type": "A", "value": {"aProp": false } },
    { "type": "B", "value": {"bProp": "1" } },
  ]
}

which represents a type hierarchy like this one:
sealed class Base
class A(val aProp: Boolean): Base()
class B(val aProp: String): Base()

class BaseList(val someList: List<Base>)

I would like to deserialize the JSON into such types,
but the default seales/polymorphic kotlinx serializer reads & writes the discriminator in the object itself, like this:
{
  "someList": [
    { "type": "A", "aProp": false },
    { "type": "B", "bProp": "1" }
  ]
}

while I got the discriminator outside of the object itself.
How can I deserialize such a JSON into this Kotlin type hierarchy?

A: If you don't want to write a custom serializer you have to match the structure of your JSON. Your original JSON represents an object inside an object, so you'll have to do something like:
data class A(val value: AValue): Base()

data class AValue(val aProp: Boolean)

A: Good question! It annoys me so much there still isn't a standard for polymorphism in JSON.
I don't think writing a custom serializer is a desirable approach here. You'd have to apply custom serializers all over the codebase. Instead, you are probably better off introducing a pre- and postprocessing step wherever you serialize JSON. Thus intercept the JSON and convert it to a format supported by kotlinx.serialization.
Kotlinx serialization also supports "array polymorphism" in the JSON configuration, which I personally prefer but is much less common. It stores the type in the first element, and value in the second, of an array. This seems similar in intent to your target format. Using a JSON transformer it should be fairly trivial to covert all type and value objects to an array with two elements.
P s. I suggest you post about your use case as a feature request on GitHub. The maintainers are very receptive to feedback. It sounds like some type of strategy pattern to deal with different formats of polymorphism is in order.


text:
Q: I purchased App APK file and seller told me is 100% editable and can be modify, But All files and folders have their company tag and name on the codes I purchased App APK file and seller told me is 100% editable and can be modify,They give me instruction to how to change the App , But after I open the folders  I noticed all files and folders have their company tag and name on the codes.As an example , Layout, all codes have their initials ,
Activity, every single code have their initials and tags like this
package in.techware.lataxi.listeners;

import in.techware.lataxi.model.CarBean;
import in.techware.lataxi.model.DriverBean;

public interface AppStatusListener {

void onLoadFailed(String error);

void onLoadCompleted(DriverBean driverBean);

Here is my concerns, does it matter if they have their initial on all codes? Unfortunately I am not a mobile app or programming  expert.
What should do ? should completely forget about the app and think of it as lost do to future security problems , or should I pay more to someone to go over the files and change every single codes with our initial and company name ? Please if you are expert help me and instructed  to make right decision.


text:
Q: Setting page numbering on Word  I have a word document. The first four pages are title and index. After that, the "Chapter 1" starts. I want page numbers to begin from the "Chapter 1" onwards only. The first 4 pages should not have any page number.
How do I achieve this?

A: This is possible, but first you have to "separate your table of contents and your chapters section by inserting a "break".  Put your cursor where you want a break (in this case, at the end of your table of contents, at the bottom of your 4th page), then go to the "Page Layout" tab, and click "Breaks" in the Page Setup section of the ribbon interface.  Choose the "Next page" section break option, and it will create a new section.

Then put your cursor at the top of the 5th page, the first page of the 2nd section of your document.  Go to the 'Insert' tab, then click on 'Page Number' in the 'Header and Footer' Section.  When you click it, it shows a drop down menu, and you can click 'Format Page Numbers...

In the dialog box that pops up:

Choose "Start at:" and pick your first page number - if you want your chapter page to say '1' page on at the top, then put in a '1'.  If you want it to say page '5', then put in a '5'...
Hope that helps!


text:
Q: Portal site connection node not showing in SiteMapPath breadcrumb I have several site collections with portal site connections set pointing to a root site collection.
In my custom master page i have added a SiteMapPath breadcrumb, based on the breadcrumb from the night and day master, here is the markup:
<asp:SiteMapPath
    runat="server"
    SiteMapProviders="SPSiteMapProvider,SPXmlContentMapProvider"
    RenderCurrentNodeAsLink="true"
    NodeStyle-CssClass="breadcrumbNode"
    CurrentNodeStyle-CssClass="breadcrumbCurrentNode"
    RootNodeStyle-CssClass="breadcrumbRootNode"
    HideInteriorRootNodes="false"
    SkipLinkText="">
    <PathSeparatorTemplate>
        <SharePoint:ClusteredDirectionalSeparatorArrow ID="ClusteredDirectionalSeparatorArrowBreadCrumb" runat="server" Visible="true"/>
    </PathSeparatorTemplate>
</asp:SiteMapPath>

On my dev machine this works perfectly and i see the portal site as the root node in the bread-crumb. Now I have gone to a test environment and the portal site no longer shows (it is still showing in the SharePoint drop down bread crumb in the ribbon). The site collections concerned where set up exactly the same way so i can't figure out what could be wrong.
Is there anything at the web application, or farm levels that could effect this, or possibly something in the hive that is effecting it?
Any suggestions would be greatly appreciated.


text:
Q: When does "1..10" make sense? I have a vague memory of a programming language where 1..10 meant "the range 1 inclusive to 10 exclusive", similar to python's range(1, 10), but I haven't the foggiest which, and this doesn't particularly lend itself to searches. Any help?
If the answer's "python", please forgive me. I know very little python.

A: Pascal supports that syntax. You can actually use this as a type, and I believe it's also used in specifying array bounds. (I'm not sure how much of this is standard Pascal and how much is Turbo Pascal extensions.)

A: It is Perl, called the "Range Operator"
http://www.cs.cf.ac.uk/Dave/PERL/node38.html

A: Haskell does it.

A: Groovy uses this syntax, too.
http://groovy.codehaus.org/Collections

A: F#, they are called Sequence Expressions
http://msdn.microsoft.com/en-us/library/dd233209.aspx (select the F# examples to see the code)

A: Ruby!

A: Since the OP already got the answer they were looking for, and this has kind of become a list of languages that use 1..n syntax, I'll add one more.
Maple
The wiki page shows a good example
myfac := n -> product( i, i=1..n );

Note however that this is 1 to 10 inclusive

A: Ruby has VERY similar syntax...
You can read more here:
http://www.ruby-doc.org/core/classes/Range.html

A: If it's a vague and distant memory, then I'd guess that Pascal or Delphi is the most likely candidate for the language you're thinking of.
It's most commonly used in Pascal in a case statement. See here for example syntax: http://en.wikipedia.org/wiki/Switch_statement#Pascal
It could also be any of a number of other languages that use this syntax, but without knowing a bit more about your programming history, my guess would still be Pascal / Delphi.


text:
Q: Spyder won't start in any environment or standalone Spyder won't start in any environment or standalone.

*

*In the command window (both conda terminal and cmd ) it doesn't throw any error just silently doesn't work.

*When I try to start it by anaconda navigator it throws "Exit code: 3221225477".

I've tried,

*

*Deleting the Anaconda and doing the clean installation several times.

*Setting the Anaconda preferences as default.

*python spyder --reset

*checking hard disk health

*diagnose memory problems


text:
Q: DayPilot Scheduler - Vertical Scrollbar never appears This question is for the Angular implementation of DayPilot Scheduler.
It seems that no matter what I do, I cannot get a vertical scrollbar to appear where the events are rendered. When there are more rows than can fit into the scheduler, they are simply cut off and hidden from view.
I have read the documentation for setting the height here, here and here, as well as this help topic. I have used different combinations of settings for the heightSpec property, with the following results:

*

*Parent100Pct - does as the documentation suggests and fills the parent element. Does not expand when there are more rows than fit on the screen, does not show any scrollbar.

*Max - grows up to the fixed size that I specify, but again when there are more rows than fit on the screen, does not show any scrollbar.

*Fixed - renders at exactly the height that I specify, but again no vertical scrollbar.

I've basically run out of ideas. I'm using Bootstrap as the framework, I had thought that maybe something there wasn't playing nicely with DayPilot but I couldn't find any conflicts.
It looks like my code should work, so I would be grateful for any suggestions. This is the code I've been working with. I'm sure it's something small that's staring me right in the face, it usually is.
Markup:

                    <daypilot-scheduler id="dp" config="vm.schedulerConfig" events="vm.events" publish-as="vm.scheduler"></daypilot-scheduler>

Javascript:
var minutesInDay = 60 * 24;

vm.schedulerConfig = {
    startDate: '2017-01-01',
    days: 90,
    cellDuration: minutesInDay,
    floatingEvents: false,
    floatingTimeHeaders: false,
    cellSweeping: false,
    useEventBoxes: 'Never',
    scrollDelayEvents: 0,
    timeHeaders: [
        { groupBy: 'Month', format: 'MMMM yyyy' },
        { groupBy: 'Week'},
        { groupBy: 'Day', format: 'ddd dd' }
    ],
    separators: [
        { color: 'Orange', location: new DayPilot.Date(), width: 5 }
    ],
    treeEnabled: true,
    cssClassPrefix: 'scheduler',
    widthSpec: 'Parent100Pct',
    heightSpec: 'Fixed',
    height: 500,
    durationBarVisible: false,
    weekStarts: 1
}

CSS:
#page-container, #page-wrapper {
    height: 100% !important;
}

#main-content {
    height: 100%;
}

#am-main {
    height: 89% !important;
}

.scheduler_cell {
    background: transparent;
    border: none;
    margin: 5px 0;
    padding: 5px;
    min-width: 10px;
}

.scheduler_default_divider_horizontal {
    background-color: white !important;
}

.scheduler_default_scrollable {
    overflow-y: hidden !important;
    font-family: 'Roboto', sans-serif !important;
}

.scheduler_default_rowheader_scroll, .scheduler_rowheader, .scheduler_corner {
    width: 150px !important;
}

.scheduler_event_inner {
    border-right: 0.5px solid black;
}

.scheduler_timeheadergroup, .scheduler_timeheadercol {
    border: thin solid white;
}

.scheduler_timeheadergroup_inner, .scheduler_timeheadercol_inner, scheduler_timeheader_float_inner {
    padding: 2px 0 0 4px;
}

A: overflow-y: hidden !important;
Just from what you've posted, it appears that line of css is likely the cause. I'm guessing it's on a parent container to the mark-up you provided. That says, whatever you do, DON'T EVER SHOW A VERTICAL SCROLL BAR!
Try removing that line and see what luck you have.


text:
Q: XMPP Room Invitation In my chatting application I want to implement Group Chatting functionality. For the same I want to create rooms and send the invitations to my friends to join the room. Here is my code to join and invite the friend to room.
To Create the Room
//Create Room
    btn_CreateRoom = (Button)findViewById(R.id.btn_usermenu_CreateRoom);
    btn_CreateRoom.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            try {
                muc = new MultiUserChat(connection, "room1@conference.abc.com");

                muc.join("Sunil","123456");
                muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));

            } catch (XMPPException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("Room Created");
        }
    });

    btn_Invite = (Button)findViewById(R.id.btn_usermenu_InviteToRoom);
    btn_Invite.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            muc.invite("sunil@abc.com", "Please join this room");

        }
    });

}

To recieve the invitation I have implemented an Invitation Listener in my Service Class. But I am unable to receive the invitaion via notification. Wats the problem with the code.
Here is my Invitation Listener.
MultiUserChat.addInvitationListener(connection, new InvitationListener() {

            @Override
            public void invitationReceived(Connection arg0, String arg1, String arg2,
                    String arg3, String arg4, Message arg5) {
                // TODO Auto-generated method stub

                System.out.println("Received??");
                notification("Invitation Received");

Please let me know Why I am not receiving the invitation.??
Thanks

A: you write this code after xmppconnection.connect()
MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener() {
                    @Override
                    public void invitationReceived(XMPPConnection conn, MultiUserChat room, String inviter, String reason, String password, Message message) {
                        MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(conn);
                        try {
                            room.join("pandian");
                        } catch (SmackException.NoResponseException e) {
                            e.printStackTrace();
                        } catch (XMPPException.XMPPErrorException e) {
                            e.printStackTrace();
                        } catch (SmackException.NotConnectedException e) {
                            e.printStackTrace();
                        }
                    }

                });

its work for me ..try it

A: You can try this
public class myclass extends Activity implements InvitationListener{
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
                MultiUserChat.addInvitationListener(Connection,myclass.this);
}
@Override
    public void invitationReceived(Connection conn, final String room,
            String inviter, String reason, String password, Message message) {

        Log.e("inviter", inviter);
        Log.e("message", message.getBody());
        Log.e("reason", reason);
        Log.e("room", room);

    }
}

This might solve your problem.

A: We missed Thread here:
Just add below code to join group:
private void setChatRoomInvitationListener() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                MultiUserChat.addInvitationListener(xmppConnection, new InvitationListener() {
                    @Override
                    public void invitationReceived(Connection connection,String room, String inviter, String reason,String unKnown, Message message) {
                        XMPPConnectionUtils.configureChatStandards();
                        MultiUserChat muc = new MultiUserChat(connection, room);
                        try {
                            muc.join("My_Name_Here");
                        } catch (XMPPException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        thread.start();
    }

Hope this will help a lot.


text:
Q: Name of resistor roles in circuits I don't have a formal education in Electronic Engineering, and after some reading, I learned that a resistor could have different roles in a circuit. The roles I've learned so far are the following:

*

*Current Limiting Resistor

*Pull Up Resistor

*Pull Down Resistor

*Voltage Divider Resistors

What are the rest of a resistor roles categories? Is the term "Role" correct for this context? Where canI read more aboy resistir roles in circuits?


text:
Q: Decomposing Sheaves into a direct sum I have two questions about sheaves inspired by representation theory:

*

*Is there a theorem that tells me when a sheaf of vector spaces can be decomposed into the direct sum of two "smaller" sheaves?

*Let's call a sheaf of vector spaces "irreducible" if it cannot be decomposed into a direct sum of smaller sheaves. Is there a theory that tells us how sheaves are composed into these smaller "irreducible" components? For example, is such a decomposition unique, are there criteria for telling what components a sheaf has, etc.

A: What you call irreducibility is usually called indecomposability; irreducibility is the stronger condition that an object (in an abelian category, say) has no nontrivial subobjects.
The analogy to the representation theory of, say, finite groups fails in an important respect: categories of sheaves of vector spaces are almost never semisimple. That is, objects almost never decompose into direct sums of irreducible objects. Instead, one must solve extension problems, the solution to which can be expressed in terms of the Ext functor. People usually first encounter this sort of issue in module theory.
For example, the category of locally constant sheaves of vector spaces on $S^1$ is equivalent to the category of representations of the fundamental group $\mathbb{Z}$. This is not a semisimple category: there is a representation
$$\mathbb{Z} \ni n \mapsto \left[ \begin{array}{cc} 1 & n \\\ 0 & 1 \end{array} \right]$$
which is indecomposable but not irreducible. It is a nontrivial extension of the trivial representation by the trivial representation.
The idea in the representation theory of finite groups to try to understand all representations in terms of irreducible representations just doesn't work in general. Sheaves of vector spaces is a huge category, and trying to understand every object in it is hopeless. This isn't a category you try to understand all the objects in, it's a convenient starting point from which you can do other things.


text:
Q: How does the distorted_inputs() function in the TensorFlow CIFAR-10 example tutorial get 128 images per batch?

I was going through the CIFAR-10 example at TensorFlow getting started guide for CNN
Now in the train function in cifar10_train.py we get images as
images,labels = cifar10.distorted_inputs()

In the distorted_inputs() function we generate the filenames in a queue and then read a single record as
 # Create a queue that produces the filenames to read.
 filename_queue = tf.train.string_input_producer(filenames)

 # Read examples from files in the filename queue.
 read_input = cifar10_input.read_cifar10(filename_queue)
 reshaped_image = tf.cast(read_input.uint8image, tf.float32)

When I add debugging code, the read_input variable contains only 1 record with an image and its height, width, and label name.
The example then applies some distortion to the read image/record and then passes it to the _generate_image_and_label_batch() function.
This function then returns a 4D Tensor of shape [batch_size, 32, 32, 3]  where batch_size = 128.
The above function utilizes the tf.train.shuffle_batch() function when returns the batch.
My question is where do the extra records come from in the tf.train.shuffle_batch() function? We are not passing it any filename or  reader object.
Can someone shed some light on how we go from 1 record to 128 records? I looked into the documentation but didn't understand.

A: The tf.train.shuffle_batch() function can be used to produce (one or more) tensors containing a batch of inputs. Internally, tf.train.shuffle_batch() creates a tf.RandomShuffleQueue, on which it calls q.enqueue() with the image and label tensors to enqueue a single element (image-label pair). It then returns the result of q.dequeue_many(batch_size), which concatenates batch_size randomly selected elements (image-label pairs) into a batch of images and a batch of labels.
Note that, although it looks from the code like read_input and filename_queue have a functional relationship, there is an additional wrinkle. Simply evaluating the result of tf.train.shuffle_batch() will block forever, because no elements have been added to the internal queue. To simplify this, when you call tf.train.shuffle_batch(), TensorFlow will add a QueueRunner to an internal collection in the graph. A later call to tf.train.start_queue_runners() (e.g. here in cifar10_train.py) will start a thread that adds elements to the queue, and enables training to proceed. The Threading and Queues HOWTO has more information on how this works.


text:
Q: Dynamics 365 - Create workflow on new Eventbrite contact New to Dynamics 365, ClickDimensions and Eventbrite integration.
When a user registers on Eventbrite it creates a new contact within our CRM as it's meant to do.  What I cannot figure out is how to create a workflow that sends an email back to the user from the CRM but only if it has come from Eventbrite.
I know how to create a workflow when a contact is created, but not with the extra check.


text:
Q: toString() returns different value than expected (however toFixed returns the right one). Why? Why toString() returns a value different to expected? I expect the toString result to be the same as the toFixed result.
const a = 2929539092180640938;
console.log(a.toString());
// prints '2929539092180641000'

console.log(a.toFixed());
// prints '2929539092180640938'

As a result of this "feature", the simple and correct line like this gives completely unpredictable result const b = `Value ${a}`;

A: Neither of those print the number accurately, because 2929539092180640938 is above Number.MAX_SAFE_INTEGER, which is 9007199254740991.
Calling .toFixed gives you 2929539092180640768.
Calling .toString gives you 2929539092180641000.
The result of .toFixed can sometimes be different from (and more accurate than) .toString because:

The output of toFixed may be more precise than toString for some values because toString only prints enough significant digits to distinguish the number from adjacent Number values. For example,
(1000000000000000128).toString() returns "1000000000000000100",

while
(1000000000000000128).toFixed(0) returns "1000000000000000128".

A: The number in a is larger than Number.MAX_SAFE_INTEGER (2^53-1), so string conversions of such a large number may have a loss of precision.
If you use a BigInt, toString() will work as expected:
const b = BigInt('2929539092180640938');
console.log(b.toString()); //2929539092180640938


text:
Q: TensorFlow can't convert from float32 to float32_ref while restoring frozen_graph I've having this issue where I want to import a TensorFlow graph I've previously frozen.
The error :
graph_def is invalid at node 'block1/conv2d/kernel/Assign': Input tensor 'block1/conv2d/kernel:0' Cannot convert a tensor of type float32 to an input of type float32_ref.

I've built a custom model mainly for proof of concept purpose within my application. I'm using the tf.layers wrappers for the conv2d and batch_norm.
The custom model code :
...

@staticmethod
def conv_batch_relu(inputs, filters, kernel_size, is_training):
    cv = tf.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, use_bias=True, activation=None)
    bn = tf.layers.batch_normalization(inputs=cv, training=is_training, fused=True)
    return tf.nn.relu(bn)

def build_network(self):

    x = tf.placeholder(tf.float32, [None] + self.dataset['input_dims'], name='input')
    y = tf.placeholder(tf.float32, [None] + [self.dataset['output_dims']], name='labels')
    is_training = tf.placeholder(tf.bool, name='is_training')

    with tf.variable_scope('block1'):
        conv1 = CNN.conv_batch_relu(inputs=self.x, filters=64, kernel_size=3, is_training=self.is_training)
        conv2 = CNN.conv_batch_relu(inputs=conv1, filters=64, kernel_size=3, is_training=self.is_training)
        pool1 = tf.layers.max_pooling2d(inputs=conv2, pool_size=2, strides=2)

    with tf.variable_scope('block2'):
        conv3 = CNN.conv_batch_relu(inputs=pool1, filters=128, kernel_size=3, is_training=self.is_training)
        conv4 = CNN.conv_batch_relu(inputs=conv3, filters=128, kernel_size=3, is_training=self.is_training)
        pool2 = tf.layers.max_pooling2d(inputs=conv4, pool_size=2, strides=2)

    next_shape = int(pool2.shape[1] * pool2.shape[2] * pool2.shape[3])
    next_output = (next_shape // 4)

    with tf.name_scope('fc1'):
        flat_fc1 = tf.layers.flatten(inputs=pool2)
        fc1 = tf.layers.dense(inputs=flat_fc1, units=next_output, activation=tf.nn.relu)

    with tf.name_scope('dropout'):
        fc1_drop = tf.layers.dropout(inputs=fc1)

    with tf.name_scope('logits'):
        self.yhat = tf.layers.dense(inputs=fc1_drop, units=self.dataset['output_dims'], activation=None, name='yhat')

    with tf.name_scope('loss'):
        self.cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.y, logits=self.yhat), name='cross_entropy')

    self.optimizer = tf.train.AdamOptimizer(self.hyperparams['learning_rate']['user'], name='optimizer').minimize(self.cross_entropy)

An external function is responsible for freezing the graph for inference. I found a blog post (https://blog.metaflow.fr/tensorflow-how-to-freeze-a-model-and-serve-it-with-a-python-api-d4f3596b3adc) and followed it for freezing the graph.
The code responsible for freezing the graph :
absolute_model_dir = '{0}/frozen_model.pb'.format('.')

with tf.Session(graph=tf.Graph()) as sess:

    saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=True)
    saver.restore(sess, input_checkpoint)

    node_names = [n.name for n in tf.get_default_graph().as_graph_def().node]

    output_graph_def = tf.graph_util.convert_variables_to_constants(sess, tf.get_default_graph().as_graph_def(), node_names)

    with tf.gfile.GFile(absolute_model_dir, 'wb') as outfile:
        outfile.write(output_graph_def.SerializeToString())

Another function is responsible for loading the frozen graph for inference.
The code responsible for loading the graph :
with tf.gfile.GFile('{0}/frozen_model.pb'.format(path), 'rb') as infile:

    graph_def = tf.GraphDef()
    graph_def.ParseFromString(infile.read())

    # fix nodes for batch_norm
    # based on https://github.com/tensorflow/tensorflow/issues/3628
    for node in graph_def.node:
        if node.op == 'RefSwitch':
            node.op = 'Switch'
            for index in range(len(node.input)):
                if 'moving_' in node.input[index]:
                    node.input[index] = node.input[index] + '/read'
        elif node.op == 'AssignSub':
            node.op = 'Sub'
            if 'use_locking' in node.attr: del node.attr['use_locking']
        elif node.op == 'Assign':
            if 'use_locking' in node.attr: del node.attr['use_locking']

    graph = tf.import_graph_def(graph_def) # <---- This is the line that breaks !

My TensorFlow version is 1.7 (tensorflow-gpu 1.7) and I've tried 1.6 before, resulting in the same error. I'm currently using Python 3.6.3 in a virtualenv.
Looking at the discussion of the github issue (link in one of the comments above) I'm aware that the 'Assign' keyword in 'block1/conv2d/kernel/Assign' seems like a good candidate for the source of the error, but I'm really unsure about how's it being used within tensorflow and why it's causing errors. This all feels a little too much 'black-magic'-ish for me right now.
Did any of you stumbled upon something similar and found an explanation about what is going wrong ?
Any help appreciated, thanks !


text:
Q: Projectile motion in Pygame I'm basically trying to make a basketball game where the user can decide the direction of the ball and the intensity of the force applied to it.
I haven't done the basket yet because I got stuck trying to do the projectile motion.
The main idea is to decide the force by pressing the letter "r" in the keyboard and then with "w" start a rotation of a vector who will give the direction for the parabolic motion of the ball.
But the motion of the ball is not working. I'm sorry that I couldn't provide the image of the ball that I used but every image can work.
I tried to follow a code that I found online but still the ball is not following the direction of the vector and is not following a correct parabolic motion.
This is my full code:
import pygame
import math

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
FPS = 60
clock = pygame.time.Clock()
screen_x = 900
screen_y = 500
ball_x = 40
ball_y = 40
time = 0
screen = pygame.display.set_mode((screen_x, screen_y))
pygame.display.set_caption("Basketball Game")

jumping = False
X_POSITION = 400
Y_POSITION = 375
Y_GRAVITY = 1
JUMP_HEIGHT = 20
Y_VELOCITY = JUMP_HEIGHT

VEL_BALL = 15
ARROW_X = 500
ARROW_Y = 300
LENGHT_FORCE = 49

ANGLE = 0

ball = pygame.image.load("ball.svg.png")
ball = pygame.transform.scale(ball, (80, 80))
ball_rect = ball.get_rect(center = (X_POSITION, Y_POSITION))
ball_width = ball.get_width()

def ball_path():
    Vx = math.cos(angle)* JUMP_HEIGHT
    Vy = math.sin(angle)* JUMP_HEIGHT
    distx = Vx * time
    disty = (Vy * time) +((-4.9 * (time)**2)/2)

    newx = round(distx + X_POSITION)
    newy = round(Y_POSITION-disty)

    return(newx, newy)

    #X_POSITION = newx
    #Y_POSITION = newy

def find_angle(pos):

    sX = X_POSITION
    sY = Y_POSITION
    try:
        angle = math.pi / 2
    except:
        angle = math.pi / 2
    if pos[1] < sY and pos[0] > sX:
        angle = abs(angle)
    elif pos[1] < sY and pos[0] < sX:
        angle = math.pi - angle
    elif pos[1] > sY and pos[0] < sX:
        angle = math.pi + abs(angle)
    elif pos[1] > sY and pos[0] > sX:
        angle = (math.pi * 2) - angle

    return angle

run = True
while run:
    VECTOR_STARTPOINT = pygame.math.Vector2(X_POSITION, Y_POSITION)
    VECTOR_ENDPOINT = pygame.math.Vector2(100, 100)
    CURRENT_ENDPOINT = VECTOR_STARTPOINT + VECTOR_ENDPOINT.rotate(ANGLE)

    screen.fill(BLACK)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys_pressed = pygame.key.get_pressed()

    if keys_pressed[pygame.K_SPACE]:
        jumping = True
    if keys_pressed[pygame.K_d] and X_POSITION < screen_x-ball_width//2:
        X_POSITION += VEL_BALL
    if keys_pressed[pygame.K_a] and X_POSITION > 0 + ball_width//2:
        X_POSITION -= VEL_BALL

    screen.fill(BLACK)

    #draw force line, red below, white above
    FORCE_MAX = pygame.draw.line(screen, (255, 0, 0) , (400, 50), (50, 50), 5)
    FORCE = pygame.draw.line(screen, WHITE , (LENGHT_FORCE, 50), (50, 50), 5)

    if keys_pressed[pygame.K_r] and LENGHT_FORCE <= 400:
        LENGHT_FORCE += 5

        #coould do it with no hard coding
        if LENGHT_FORCE <= 200 and LENGHT_FORCE > 99:
            print("low")
            JUMP_HEIGHT = 20
            Y_VELOCITY = JUMP_HEIGHT

        if LENGHT_FORCE > 200 and LENGHT_FORCE < 300:
            print("medium")
            JUMP_HEIGHT = 25
            Y_VELOCITY = JUMP_HEIGHT

        if LENGHT_FORCE >= 300 and LENGHT_FORCE < 400:
            print("strong")
            JUMP_HEIGHT = 30
            Y_VELOCITY = JUMP_HEIGHT

        if LENGHT_FORCE == 399:
            print("maximum")
            JUMP_HEIGHT = 35
            Y_VELOCITY = JUMP_HEIGHT

    #start moving vector
    if keys_pressed[pygame.K_w]:
        ANGLE = (ANGLE + 5) % 360
        VECTOR_LINE = pygame.draw.line(screen, WHITE, VECTOR_STARTPOINT, CURRENT_ENDPOINT, 4)

    #stop moving vector
    if event.type == pygame.KEYUP :
        if event.key == pygame.K_w :
            if Y_POSITION < screen_y and Y_POSITION >= 0:
                pos = CURRENT_ENDPOINT[0], CURRENT_ENDPOINT[1]
                angle = find_angle(pos)

                VECTOR_LINE = pygame.draw.line(screen, (255, 0, 0), VECTOR_STARTPOINT, CURRENT_ENDPOINT, 4)

                time += 0.05
                po = ball_path()
                X_POSITION = po[0]
                Y_POSITION = po[1]

            else:
                time = 0
                Y_POSITION = 375

    if jumping:
        Y_POSITION -= Y_VELOCITY
        Y_VELOCITY -= Y_GRAVITY
        if Y_VELOCITY < -JUMP_HEIGHT:
            jumping = False
            Y_VELOCITY = JUMP_HEIGHT
        ball_rect = ball.get_rect(center = (X_POSITION, Y_POSITION))
        screen.blit(ball, ball_rect)
    else:
        ball_rect = ball.get_rect(center = (X_POSITION, Y_POSITION))
        screen.blit(ball, ball_rect)

    pygame.display.flip()
    clock.tick(FPS)

A: if you have an angle of say 45 degrees you can convert it to radians
radians = (degrees * math.PI)/180

once you have radians you can get the x and y components using sin/cos
x1 = x0 + math.cos(radians)*speed
y1 = y0 + math.sin(radians)*speed

where x0,y0 are your origin point and x1,y1 is the next point ...
if you wanted to go the other way ie you have x0,y0 and x1,y1 and you need to find the angle that is even easier just use math.atan2(y1-y0, x1-x0)
i honestly have no idea if this answers your question ... but I noticed a lack of these formula in your code


text:
Q: Arch Linux on an external HDD GPT-Partitioned I have an Alienware M14x-R1 and had an Arch Linux System installed on its 750Gb HDD, everything working fine, GPT-partitions (on BIOS, not EFI) and GRUB bootloader.
Then I bought a new Corsair SSD, replaced my old HDD and installed Windows 7 on it for work purposes. I also bought an external HDD casing from SilverStone (Raven RVS02) thats USB 3.0 and I can mount my linux GPT Partitions just fine.
But when I try to boot the ArchLinux system from the USB I get no options on F12 (Chose Boot Disk) for it.
I found this site that someone says he could use an OpenSuSe 12 but only on the USB 2.0 port.
So my questuin is, Is there a way I can use Arch Linux (or any other distro, I don't think the distro matters that much) on a GPT-Partitioned external HDD booting from USB 3.0 on a BIOS system?


text:
Q: Android getExternalFilesDir permissions I know that for Android 4.4 you can create the "application specific" folder in external storage using this method.
getExternalFilesDir("myfiles").getAbsolutePath();

Which creates the folder
    /storage/sdcard/Android/data/com.abc.zyz/files/myfiles
However is it safe to create it this way (my preferred) without the extra folder "files"?
String mfolder = Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName() + "/myfiles";
File sd = new File(mfolder);
if(!sd.exists() || !sd.isDirectory()) {
sd.mkdirs();
}

I've run it on API19 emulator and the folder is created using both methods, but I am concerned that when done on a real device that there could be a permissions issue doing it with the second preferred method.
Can anyone advise or test with a Kitkat device please?

A: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
                 android:maxSdkVersion="18"/>

This will allow you to write to the external storage( i.e. save files) for for SDK earlier than 18 when it was required to give permission after that no permission is required. I know this question has been posted long back but thought the answer may help someone else cause it took me sometime to find this out

A: I had a similar problem when reading this way. Works fine before 4.4, but on 4.4 it doesn't like it.
Add this to your AndroidManifest.xml file:
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Worked for me. Let me know if it does for you!


text:
Q: Update Xml file with namespace in element names (PowerShell) I have a xml file which I want to update based on a value from a variable.
I would like to to something like this
$ns = @{ dts = 'www.microsoft.com/SqlServer/Dts' }
$xml2 =  [XML](Get-Content "C:\Users\David\Documents\New.dtsx")

$xml2 |
Select-Xml -XPath "/dts:Executable/dts:Variables/dts:Variable[@dts:ObjectName = 'BATCH_JOB_ID']/dts:VariableValue"  -Namespace $ns |
Select-Object -ExpandProperty Node |
Select-Object -ExpandProperty '#text' = "$BATCH_JOB_ID"

That is, I am trying to extract a specific XML element of interest and to update its ObjectName attribute.
Why does this not work?
Another option is to use dot notation, which is what I prefer, but I do not know how to filter the attribute after this point:
$xml2.Executable.Variables.Variable

I have to use the filter @dts:ObjectName = 'BATCH_JOB_ID' I can do like:
$xml2.Executable.Variables.Variable.VariableValue[0].'#text'

But instead of [0] I would like to write ObjectName = 'BATCH_JOB_ID. Is that possible? How can I write something like:
$xml2.Executable.Variables.Variable.VariableValue[BATCH_JOB_ID].'#text'

A: $ns = @{ dts = 'www.microsoft.com/SqlServer/Dts' }
$xml2 = [xml](Get-Content -Raw C:\Users\David\Documents\New.dtsx)
$xpathQuery = "/dts:Executable/dts:Variables/dts:Variable[@dts:ObjectName = 'BATCH_JOB_ID']"

# Use XPath to target the element of interest, as a
# [Microsoft.PowerShell.Commands.SelectXmlInfo] instance whose .Node property is
# the targeted [System.Xml.XmlElement] instance.
# Call .SetAttribute() to update the 'ObjectName' attribute in-place.
(Select-Xml -Xml $xml2 -XPath $xpathQuery -Namespace $ns).
  Node.SetAttribute('ObjectName', $NEW_BATCH_JOB_ID)
}

# Save back to original file.
$xml2.Save("C:\Users\David\Documents\New.dtsx")

However, since you're parsing the XML yourself first anyway, there is no reason to involve
Select-Xml:
$xml2 = [xml](Get-Content -Raw C:\Users\David\Documents\New.dtsx)
$xpathQuery = "/dts:Executable/dts:Variables/dts:Variable[@dts:ObjectName = 'BATCH_JOB_ID']"

# Create the namespace-manager instance.
$nsm = [System.Xml.XmlNamespaceManager]::new($xml2.NameTable)
$nsm.AddNameSpace('dts', 'www.microsoft.com/SqlServer/Dts')

# Locate the element of interest...
$targetEl = $xml2.SelectSingleNode($xpathQuery, $nsm)
# ... and update its attribute.
$targetEl.SetAttribute('ObjectName', $NEW_BATCH_JOB_ID)

# Save back to original file.
$xml2.Save("C:\Users\David\Documents\New.dtsx")

The alternative is to let Select-Xml parse the XML file into a DOM for you, without the need to create an [xml] instance manually first:
$ns = @{ dts = 'www.microsoft.com/SqlServer/Dts' }
$xpathQuery = "/dts:Executable/dts:Variables/dts:Variable[@dts:ObjectName = 'BATCH_JOB_ID']"

# Use XPath to target the element of interest, as a
# [Microsoft.PowerShell.Commands.SelectXmlInfo] instance whose .Node property is
# the targeted [System.Xml.XmlElement] instance.
$targetEl = (Select-Xml -LiteralPath C:\Users\David\Documents\New.dtsx -XPath $xpathQuery -Namespace $ns).Node

# Call .SetAttribute() to update the 'ObjectName' attribute in-place.
$targetEl.SetAttribute('ObjectName', $NEW_BATCH_JOB_ID)

# Save back to original file; the .OwnerDocument property provides
# access to the enclosing document.
$targetEl.OwnerDocument.Save("C:\Users\David\Documents\New.dtsx")


text:
Q: Date conversion from dd/mm/yyyy to yyyy/mm/dd using javascript I need to convert a date from dd/mm/yyyy to yyyy/mm/dd.
I am getting the input from a text box in dd/mm/yyyy format.When i try to convert it to yyyy/mm/dd i got the error invalid date.How can i convert it properly.

A: Here's the snippet I found working

date="21/01/2015";
var newdate = date.split("/").reverse().join("-");
console.log(newdate)

A: Try this
var date= '21/01/2015';
var d=new Date(date.split("/").reverse().join("-"));
var dd=d.getDate();
var mm=d.getMonth()+1;
var yy=d.getFullYear();
var newdate=yy+"/"+mm+"/"+dd;

Working Demo