text:
Q: How can you set SourceData in a macro to count only rows needed? I have an Excel Workbook in which I am building as a Master.  Part of what I have to do is have pie charts on my master sheet.  So I have created a sheet that has formulas pulling over selected information to use for the pie charts (SortedPie).  Then I have another sheet that will be populated by macro creating the pivot tables for the pie charts (PieSheet).  My problem is that the information on SortedPie changes in the amount of rows from 1 to 500.  In my macro I have the SourceData set to 500, but then it leaves blanks in the pivot tables to equal all 500 rows.  I have tried using   lr=SortedPie.Range("A" & Rows.Count).End(xlUp).Row with set rng=SortedPie.range("A:X" & lr) then for SourceData=:rng.Address(True, True,xlR1C1,True).Refresh  and when run gives me compile error on the Address.  I should say my code also has Dim lr As Long and Dim rng As Range.  This is the macro as it is now.
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "SortedPie!R1C1:R500C5", Version:=xlPivotTableVersion14).CreatePivotTable _
    TableDestination:="PieSheet!R1C1", TableName:="PivotTable2", _
    DefaultVersion:=xlPivotTableVersion14
Sheets("PieSheet").Select
cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable2").PivotFields("Credit Score")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable2").AddDataField ActiveSheet.PivotTables( _
    "PivotTable2").PivotFields("CustomerAccountID"), "Count of CustomerAccountID", _
    xlCount
Sheets("SortedPie").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "SortedPie!R1C1:R185C5", Version:=xlPivotTableVersion14).CreatePivotTable _
    TableDestination:="PieSheet!R10C1", TableName:="PivotTable3", _
    DefaultVersion:=xlPivotTableVersion14
Sheets("PieSheet").Select
cells(10, 1).Select
With ActiveSheet.PivotTables("PivotTable3").PivotFields("PanelType")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables( _
    "PivotTable3").PivotFields("CustomerAccountID"), "Count of CustomerAccountID", _
    xlCount
Sheets("SortedPie").Select
ActiveWorkbook.Worksheets("PieSheet").PivotTables("PivotTable3").PivotCache. _
    CreatePivotTable TableDestination:="PieSheet!R20C1", TableName:= _
    "PivotTable4", DefaultVersion:=xlPivotTableVersion14
Sheets("PieSheet").Select
cells(20, 1).Select
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Status")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables( _
    "PivotTable4").PivotFields("CustomerAccountID"), "Count of CustomerAccountID", _
    xlCount
Sheets("SortedPie").Select
ActiveWorkbook.Worksheets("PieSheet").PivotTables("PivotTable4").PivotCache. _
    CreatePivotTable TableDestination:="PieSheet!R30C1", TableName:= _
    "PivotTable5", DefaultVersion:=xlPivotTableVersion14
Sheets("PieSheet").Select
cells(30, 1).Select
With ActiveSheet.PivotTables("PivotTable5").PivotFields("BillingMethod")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable5").AddDataField ActiveSheet.PivotTables( _
    "PivotTable5").PivotFields("CustomerAccountID"), "Count of CustomerAccountID", _
    xlCount

End Sub

A: You can use the activesheet.usedrange.address to get the actual address of the entire worksheet, or assign the range to a variable via:
    Dim rUsedRange as range
set rUsedRange = activesheet.usedrange

UsedRange always gives the active area of a worksheet and updates anytime additional rows or columns are added. If you use the clearcontents command to clear a worksheet before repopulating, the usedrange will reset to a smaller size if needed.
You can also get the bottom row via:
lRow = activesheet.usedrange.rows.count


text:
Q: Not well formed XML error on I-Phone I am working on a product which needs to display the site created on i-phone. However there is some content in the site which is causing the bad XML parsing error on I-Phone only. Is there any way to tell the I-Phone and other mobiles to ignore such type of errors .

A: As far as i am concerned there is no other way to parse a bad XML and tell iPhone that there is  a bad XML.Whenever you tried to parse the XML in iPhone , the didfailwththe error delegate method will be called.
Hope it helps you...........

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are there ad blocker that filters YouTube advertisements on Mojave Safari Version 12.0? Who knows an AdBlocker for the latest Safari that is able to block youtube ads. I've tried AdBlock & AdBlock Plus which both are now 'full' applications instead of extensions.

*

*AdBlockPlus slows down your browser to the point that entering text, or clicking a link has a lag of around 1.5 ~ 2 seconds.

*AdBlock works for a while, and then hangs taking 600% cpu utilization.

It works again after dis&enabling it in the extension preferences. But AdBlock's biggest problem is it doesn't block that much on youtube.
I'm not here to ask how to get AdBlock or AdBlockPlus going. I'm here to ask who has a blocker for youtube.
I've used AdBlock in the past before the new extension architecture, and it blocked all youtube ads. Now YouTube is encoding the advertisements in to the streams and come up with harder to block advertisements.
Can anyone recommend software that either blocks more or uses less CPU?

A: I use  uBlock Origin with Safari 12 on macOS Mojave. It has been several months since I watched an Youtube ad.
This blog was of extreme help in making the extension work using extension builder. It also has an AppleScript to enable the extension quickly.

*

*https://georgegarside.com/blog/macos/install-any-safari-extension-macos-mojave/
I couldn't get preferences saving to work, so I export the settings to a file and import it back after every safari restart.
Unfortunately, the extension system has been removed from Safari in Safari 13. So I plan to switch to Brave or Firefox to continue using uBlock Origin.

*

*https://github.com/el1t/uBlock-Safari/issues/158

*https://github.com/el1t/uBlock-Safari/issues/156
For safari, uBO suggests

*

*Adguard

*Ka-Block!

*Ghostery lite

*Wipr

NOT recommended:

*

*uBlock (not origin)

*AdBlock Plus for Safari

*AdBlock for Safari (made by BETAFISH INC)

Not affiliated with any product.

A: "Wipr" does the Job guys. No slowdowns, no cpu hogging, and it's not able to get to your passwords & payment info.
https://itunes.apple.com/us/app/wipr/id1320666476?mt=12
Edit: Wipr no longer blocks YT ads.


text:
Q: reference functions to array slices in python Is the following was possible in python?
(I am pretty new to python, not sure what the appropriate search term would be)
I have a class that stores and manipulates a large numpy array.
Now I would like to access parts of this array via an alias 'reference function'
Here is a dummy example for illustration
import numpy as np
class Trajectory(object):
   def __init__(self,M=np.random.random((4,4))):
      self.M=M

   def get_second_row(self):
      return self.M[1,:]

   def set_second_row(self,newData):
      self.M[1,:]=newData

t=Trajectory()
print t.M
initialData=t.get_second_row()
t.set_second_row(np.random.random(4))
print t.M

What I don't  like about this is that I have to write separate set and get functions. is there a simpler way to use just one function to refer to the parts of the array M that would work for both getting and setting values?
so speaking in dummy code, something that would allow me to do this:
values=t.nth_row
t.nth_row=values+1

I would like to use t.nth_row as a reference for both getting and setting the value if that makes sense

A:
is there a simpler way to use just one function to refer to the parts of the array M that would work for both getting and setting values?

Yes, and you've written it. It is your get function:
initialData=t.get_second_row()
t.get_second_row()[:] = np.random.random(4)
t.get_second_row()[0] = 1997


text:
Q: PhpStorm cannot debug remotely I can successfully validate debugger via Run -> Web Server Debug Validation.
You can see the snapshot below:

But after I create a Web Application in run/debug configure and click on debug button, what I got is only the message "Waiting for incoming connection with ide key '18779' (random number)" in debug console.
Here is the setting in run configuration

BTW: deploy server and server are not the same thing, which makes me confusing. And I can also debug locally.


text:
Q: how to perform addition operation using string template in Javascript 1.Sample input:

let arr = [1,3];
console.log(`Addition is ${arr[0]? arr[0]: 0} + ${arr[1] ? arr[1] : 0}`);

2.Sample input:

let arr = [{card:0, cash:0},{card:1, cash: 2}];
 for(let i = 0; i < arr.length; i++){
     console.log(`No. of payments ${(arr[i].card || 0)} + ${(arr[i].cash ||  0)}`);
}

A: Maybe this is what you are looking for...

let arr = [1,3];
console.log(`Adittion is ${arr[0]? arr[0]: 0} + ${arr[1] ? arr[1] : 0}`);

// or

console.log(`Addition is ${(arr[0]? arr[0]: 0) + (arr[1] ? arr[1] : 0)}`);

// If the socond one is the one you wanted, you can do it using reduce instead summing all positions

console.log(`Addition is ${arr.reduce((a,b)=>a+b)}`);

Update
This is your second sample. This is completely different because in here you are not using an array of numbers, you are using an array of objects and the implementation is not the same.
PD: Consider asking a new question when is something different from what you asked before

//In Your second sample you are using an array of objects, not an array of numbers so the implementation is different

let arr = [{card:0, cash:0},{card:1, cash: 2}];

arr.map(a=>{console.log(`No. of payments ${a.card + a.cash}`)})

//If you only want the total it would be

console.log(`No. of payments ${arr.map(a=>a.card + a.cash).reduce((a,b)=>a+b)}`)

A: To make it work you need to put both operands inside the same brackets
`${(arr[0] || 0) + (arr[1] || 0)}`

Also I used the || (operand selector operator or logical or) to achieve the same result (I think it's more readable).

A: Ways to achieve this :

let arr = [1,3];

// Method 1
console.log('Addition is ', (arr[0] ? arr[0]: 0) + (arr[1] ? arr[1] : 0));

// Method 2
console.log(`Addition is ${(arr[0]? arr[0]: 0) + (arr[1] ? arr[1] : 0)}`);

// Method 3
var sum = [1,3].reduce((a, b) => a + b, 0);
console.log('Addition is ', sum);

// Method 4
function addition(...elements) {
    let total = 0;
    for (const elem of elements) {
        total += elem;
    }
    return total;
}

console.log('Addition is ', addition(...arr));


text:
Q: Node registry error at the time of npm install I am getting registry error at the time of npm install.

npm ERR! code EPROTO
npm ERR! errno EPROTO
npm ERR! request to https://registry.npmjs.org/react failed, reason: write EPROTO 101057795:error:14077419:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert access denied:openssl\ssl\s23_clnt.c:802:
npm ERR!

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\badis\AppData\Roaming\npm-cache\_logs\2018-02-16T10_46_21_806Z-debug.log

A: Open the command prompt with admin privileges and follow the below steps:
1) Clear the npm cache using the following command:
npm cache clean --force
or
npm cache verify
2) Remove the .npm directory and the node_modules directory.
3) Also, Remove following:

*

*C:\Users\username\AppData\Roaming\npm\ and

*C:\Users\username\AppData\Roaming\npm-cache
4) Set npm registry to the public repository using the following command:
npm config set registry http://registry.npmjs.org/.
5) Try running curl https://registry.npmjs.org/package-name from your terminal to make sure that network call is not blocking the package requests to npm registry.
If you are running behind a proxy, then you also have to configure npm to use it. You can set using:

*

*npm config set proxy http://proxyhost:proxyport

*npm config set http-proxy http://proxyhost:proxyport

*npm config set https-proxy http://proxyhost:proxyport

A: Could be something wrong with your permission.
Check this: https://github.com/npm/npm/wiki/Troubleshooting#permission-error


text:
Q: how to have an model that is assigned to an object use an Active Model Serializer class for rendering I am not sure if this is possible but I am currently assigning some values to a Ruby object that I am then outputting via to_json
Like:
def current_results
  @post=Post.find(params[:id])
  r={}
  r[:name]=@post.name
  ....
  mi[:notes]=mi.notes
  r[:associated_items]  << mi
  ...
  render :json => r.to_json

end
Right now, notes outputs everything as I would somewhat expect. But I have a NoteSerializer which I thought would be invoked by the to_json (that's how I'm reading this section https://github.com/rails-api/active_model_serializers#render-json but not really sure). How could I get mi.notes to use the NoteSerializer rather than returning back the default of the whole object (updated_at, create_at ...)?
thx


text:
Q: The past of run, ran, has also the meaning of crash into something? I drove off the road and ran into a tree.
In some of my texts of English studies, there is this expression, and the meaning of ran is related to a crash in this phrase, is this correct? I didn't find any info about it.

A: The phrasal verb to run into has several possible meanings, one of which is "to accidentally hit or collide with something." This applied to any tense of the verb, not just the past.
The verb to run does not mean "to crash" except in this particular construction with into. If you follow the link above,  you'll see that even with into, it doesn't always mean a physical collision. If I say, "I ran into Bob at the grocery store yesterday," it's very likely that I just met him unexpectedly, not that we crashed into each other.

A: As a native speaker I don't think of this as a special meaning of run. But into still means into.
You can run into a tree. You can walk into a wall. You can fall into a hole. You can fly into a mountain. All of these involve a collision. But I'd consider that a sense of the meaning of into, not special meanings of the different verbs used with it.


text:
Q: How to generate a vector that has zero correlation with another vector (in R)? Suppose I have a vector v1 with values in the set {-1,0,1}
> v1
0  0 -1  1  0  0  0  0  0  0  0  0  0  0 -1  1  0  0  0  0  0  0  0  0  0  0  1 -1  0  0  0  0  0  0  0  0  0  0 -1  1  0  0  0  0

How to generate a vector v2 (with values in the set {-1,0,1}) that has zero correlation (or close to zero) with v1?

A: You can generate a vector that has, on average, zero correlation simply by randomly permuting your original vector.
v2 = v1[sample(length(v1),length(v1)]

This won't get you a zero-correlation vector every time, but if you run this many times, you'll see that the average correlation value is zero. The method is simple and fast enough that you could permute the vector many times until you find one that does, in fact, have sufficiently small correlation with the original vector.
As a bonus, this method preserves some aspects of your original vector, like the values appearing and their relative frequencies, which might be desirable depending on your application.

A: Very simple. You can easily create three vectors by taking any number in the set and repeating that number till the length of v1. R code:
rep(1, length(v1))
or take value 0 or -1

A: Here is an inelegant R algorithm that works. It makes use of https://math.stackexchange.com/a/3385346. x is the input vector and y is the output vector (instead of v1 and v2). Not extensively checked. Build a function out of it.
x <- sample(c(-1, 0, 1), 100, replace=TRUE)
v <- x[x != 0]
done <- FALSE
while(done == FALSE){
  w <- sample(c(-1, 0, 1)*sqrt(2), length(v), replace=TRUE)
  u <- (w - ((t(v)%*%w)/(t(v)%*%v))%*%v)[1,]
  if(min(abs(u)) < 10e-12){done <- TRUE}
}
u <- round(u, 0)
u%*%v
y <- rep(NA, length(x))
y[x==0] <- sample(c(-1, 0, 1), length(x[x==0]), replace=TRUE)
y[x!=0] <- u
x
y
x%*%y


text:
Q: Bounds for Basin-Hoping method on a single variable function For the Basing-Hoping method on a multivariable function with specific boundaries, I write the code as follows:
import scipy.optimize as opt
bnds = ((1, 100), (1, 100), (1,100))# the bounds

def F(X):# Multivariable function
    a,b,c = X[0],X[1],X[2]
    return a**2+b**2+c**2

x0 = [10., 10., 10.]
minimizer_kwargs = { "bounds":bnds }
minimum = opt.basinhopping(F, x0, minimizer_kwargs=minimizer_kwargs)
print(minimum)

And it does gives the answer within the mentioned boundaries.
But my question is, if I follow the same pattern for a single variable function, I get an error saying that: "length of x0 != length of bounds".
The example that I used was:
bnds = ((1, 100))#  bounds

def F2(X):# Single variable function
    return X**2

x0 = [10]
minimizer_kwargs = { "bounds":bnds }
minimum = opt.basinhopping(F2, x0,minimizer_kwargs=minimizer_kwargs)
print(minimum)

Appreciate your help on how to resolve this issue..


text:
Q: Racket/Scheme embed list within existing list I'm attempting to embed a list in to an existing list, the problem is explained below.
list1
bla
bla
bla
bla

list2
useful stuff
is here

while my function iterates list1 it picks a random point where it will then insert:
useful stuff
is here

the issue is that list2 now looks like:
bla
bla
useful stuff is here
bla
bla

instead of:
bla
bla
useful stuff
is here
bla
bla

I'm totally confused, I've googled and read the documentation but I just can not find an answer, everything I have tried has failed.

A: #lang racket
(define list1 '("bla" "bla" "bla" "bla"))
(define list2 '("useful stuff" "is here"))

(define insertion-point (random (length list1)))

(append (take list1 insertion-point)
        list2
        (drop list1 insertion-point))

The result on the first run:
'("bla" "useful stuff" "is here" "bla" "bla" "bla")


text:
Q: Why EXC_BAD_ACCESS does not happen? I create a single mutable string object. Now I have released the object many times, even though I allocated them only once. According to basic memory management rules, this is wrong. But then it should crash, but this never happens. I was expecting some EXC_BAD_ACCESS error.
I received the error :
malloc: *** error for object 0x6d5ac60: double free
*** set a breakpoint in malloc_error_break to debug

Why the app does not crash?
NSMutableString *firstOwner = [[NSMutableString alloc] init];
[firstOwner release];
[firstOwner release];
[firstOwner release];
NSMutableString *temporaryObject = firstOwner;
[temporaryObject release];
[temporaryObject release];

A: Just because a crash doesn't happen for you doesn't mean it won't happen for somebody else.
You're just illustrating a case where the app can continue to limp along after making memory management errors. The crash may not be happening because aside from blatantly over-releasing, you're not doing anything else with the object references.
But if you attempted to use or access "firstOwner" or "temporaryObject" later, you'd absolutely crash with EXC_BAD_ACCESS then and there.  Access to non-existent or over-released objects are a primary cause of these kinds of crashes.


text:
Q: TableView: get value of textField in HeaderCell how can I get the value of a header Cell of an UITableView?
With the following code I get the values of a cell within a section. But how can I change this that it will work with header cells?
      let indexPath = NSIndexPath(forRow: row, inSection: h)
      tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: false)

      let currentCell = tableView.dequeueReusableCellWithIdentifier("TeamInput", forIndexPath: indexPath) as! TeamInputTableViewCell

A: If you want to access a headerView in a UITableView you can do it like this:
let headerView = tableView.headerViewForSection(indexPath.section)

By the way if you want to access an existing cell in your table view you should not use dequeueReusableHeaderFooterViewWithIdentifier, because that method returns a new cell from the queue and not one that is currently displayed. To access one of the displayed cell you should use:
let cell = tableView.cellForRowAtIndexPath(indexPath)


text:
Q: Wifi module stops connect to any access points After an update wifi stops connecting to any network (excluding router at work). It just tries to connect and after that asks for the password again and again.
I tried to reinstall the driver but that doesn't help.
12:00.0 Network controller: Broadcom Corporation BCM4313 802.11b/g/n Wireless LAN Controller (rev 01)
Ubuntu 12.04.2 LTS \n \l

It's strange because this is a Dell Vostro 1440 which is in certified Ubuntu laptop list.

A: There problems with broadcom chipset and wpa-supplicant driver. I buy external wifi module on realtek chipset and all works fine.


text:
Q: Can I change the output format of the "last" command to display the year? I'm trying to find a way to report on the most recent login for all users on my Solaris 10 server.  I'm starting with the output of the last command.  Using that command, I get output like this:
bd9439    pts/1        vpn-xxx-xx-xxx-x Fri Oct 25 10:46   still logged in
vf7854    pts/1        vpn-xxx-xx-xxx-x Fri Oct 25 10:23 - 10:38  (00:15)

According to the man page, the date and time formats are controlled by locale.  I've very rarely used locale settings.  Is there something I can use that will change the display to include the "year" portion of the date?  I'm hoping to get an output line similar to this:
bd9439    pts/1        vpn-xxx-xx-xxx-x Fri Oct 25 2013 10:46   still logged in
vf7854    pts/1        vpn-xxx-xx-xxx-x Fri Oct 25 2013 10:23 - 10:38  (00:15)

It's not clear to me if the man page was referring to the output of the last command itself or how the data is actually stored in /var/adm/wtmpx.
If there is another way to get this "last login" attribute, I'd be happy to learn it.

A: In which I half-provide context, half rant
You're running into an example of the main reason I don't like managing Solaris systems: Nothing is ever just easy.
I don't know if the locale's really going to do anything except change the order of certain portions of the timestamp around. I'm interested if anyone knows of a way to coax Solaris's last into giving the year, but I'm not going to hold my breath. Sun's software development mantra seems to have been "It Technically Works."
Sun seems to have pretty much developed something right up to the point absolutely required of them, and then pretty much stopped there. So you end up with generally accepted solutions being like these and you just keep a listed collection of workarounds for common problems.
The only way I've ever found of doing this is to use /usr/lib/acct/fwtmp to dump the entire contents of /var/adm/wtmpx to a pipe to some other program that I use for manipulating the text output (grep, tac, sed, etc).
Bonus: Since seeking the end of the file and just moving back by the fixed wtmpx record length would be asking too much, fwtmp can only print out the contents of wtmpx as they appear in the file. So you have to use some other means (probably tac) of reversing the lines, unless you're actually interested in the oldest information (which is the least likely use case, but I digress).
Depending how long your system has been in operation wtmpx might be kind of large, so you may want to go get a cup of coffee, maybe go check to see if your tires are underinflated, and maybe go read a book or two while you're at it.
The Actual Answer to your question:
This is a command that emulates last in way that is usable to most people interested in looking at login records:
# cat /var/adm/wtmpx | /usr/lib/acct/fwtmp | tac | head

You'll notice I have to pipe wtmpx in since they don't give you a means of just giving the file to fwtmp. That's because feeding it in via stdin Technically Works™ in the majority of use cases and they wouldn't have had to write a few extra lines of code. So they'd rather just make Admins do that.
This is example output of the above on on of the systems I look after:
[root@atum root]# cat /var/adm/wtmpx | /usr/lib/acct/fwtmp | tac | head
jadavis6                         ts/1 pts/1                                19410  7 0000 0000 1382723864 157168 0 19 ditirlns01.xxx.edu Fri Oct 25 13:57:44 2013
jadavis6                              sshd                                 19404  7 0000 0000 1382723864 133973 0 19 ditirlns01.xxx.edu Fri Oct 25 13:57:44 2013
oracle                                sshd                                  6640  8 0000 0000 1382713401 157107 0 0  Fri Oct 25 11:03:21 2013
oracle                           ts/1 pts/1                                 6647  8 0000 0000 1382713401 150489 0 0  Fri Oct 25 11:03:21 2013
oracle                           ts/1 pts/1                                 6647  7 0000 0000 1382712445 24488 0 23 a0003040148735.xxx.edu Fri Oct 25 10:47:25 2013
oracle                                sshd                                  6640  7 0000 0000 1382712442 304729 0 23 a0003040148735.xxx.edu Fri Oct 25 10:47:22 2013
jadavis6                              sshd                                 23537  8 0000 0000 1382560970 410725 0 0  Wed Oct 23 16:42:50 2013
jadavis6                         ts/1 pts/1                                23544  8 0000 0000 1382560970 404795 0 0  Wed Oct 23 16:42:50 2013
jadavis6                         ts/1 pts/1                                23544  7 0000 0000 1382552999 619524 0 19 ditirlns01.xxx.edu Wed Oct 23 14:29:59 2013
jadavis6                              sshd                                 23537  7 0000 0000 1382552999 602215 0 19 ditirlns01.xxx.edu Wed Oct 23 14:29:59 2013
[root@atum root]#

EDIT:
I know I'm whining about something small up there, but after a while I just get tired of every little thing (such as simply asking "what's the year?") turning into an hour long googlefest or something that's more or less just tribal knowledge (such as the existence of fwtmp).

A: GNU/Linux's last offers the -F switch.  I'd be surprised if Solaris does, though.
Internally, the wtmp file should have epoch timestamps and thus if you would care to write something in C or Perl you can create your own last command.  You will need to look at the appropriate C-header file for the structure.  The wtmp is a "binary" file and isn't amenable to evaluation with standard parsing tools.
Consider periodically archiving and truncating your wtmp file so that you know what year to which it applies.

A: I had a similar case, but needed the login date in my custom format. This works for me:
date -d "`last -F | head -n1 | sed -r 's/.*\.[0-9]+\s+//' | sed -r 's/\s(still|-).*//'`" +"%F_%R"


text:
Q: enable_shared_from_this derived class methods are undefined reference I'm using apache's parquet-cpp library (click the link to see the file in question). Line 82 is defined the class RowGroupStatistics that inherits from std::enable_shared_from_this, and line 132 the class TypedRowGroupStatistics that inherits from RowGroupStatistics.
In my code I only have:
shared_ptr<RowGroupStatistics> stats = ...;
shared_ptr<Int32Statistics> stats2 = static_pointer_cast<Int32Statistics>(ccm.statistics());

Where Int32Statistics is defined at the end of the statistics as a templated class of TypedRowGroupStatistics.
When I try to use the min or max method of the TypedRowGroupStatistics pointer as such
stats2->min();

I get a compilation error:
undefined reference to `parquet::TypedRowGroupStatistics<parquet::DataType<(parquet::Type::type)1> >::min() const'
collect2: error: ld returned 1 exit status

My guess is I'm using the enable_shared_from_this feature wrong, but I can't figure out what is the correct way to cast the base pointer to a derived class and use its methods.


text:
Q: Pass username to flask and retrieve the data using sqlite3 So I have just started studying on flask and am just moving to database with flask. I have a database "testdatabase.db" with a table named "Students". What I want to do is. When i pass a username onto the url I need the details of the that specific row.
Here is my python code
from flask import Flask, render_template, request
import sqlite3
conn = sqlite3.connect('testdatabase.db')
c = conn.cursor()

app = Flask(__name__)

@app.route("/students/<name>")
def students(name):
    return jam()

def jam():
    c.execute("select * from students where name = '" + name + "'")
    print(c.fetchall())
    conn.close()

if __name__ == "__main__":
    app.run(debug=True)

The error being shown is that name 'name' is not defined. How do I define the name to be passed to the url?

A: Name is being passed correctly to the url
@app.route("/students/<name>")
def students(name):
    return jam()

Your only problem is that you are not passing it to the jam function
solution
@app.route("/students/<name>")
def students(name):
    return jam(name)

def jam(name):
    c.execute("select * from students where name = '" + name + "'")
    print(c.fetchall())
    conn.close()
    # Return the data jsonfied.

A: There is no variable 'name' in jam, try:
from flask import Flask, render_template, request
import sqlite3
conn = sqlite3.connect('testdatabase.db')
c = conn.cursor()

app = Flask(__name__)

@app.route("/students/<name>")
def students(name):
    return jam(name)

def jam(name):
    c.execute("select * from students where name = '" + name + "'")
    print(c.fetchall())
    conn.close()

if __name__ == "__main__":
    app.run(debug=True)


text:
Q: What happen first, casting or shifting bits [C++] What's happening first here in C++, shift or casting?
(dword)header[2]<<8

A: From here Operator precedence you can see that bitwise shift has lower precedence than type cast. So that is equivalent to:
((dword) (header[2])) << 8

Always use parentheses for things that are not clear, even if you check that it is actually ok, because it improves code readability. (you might not want to enclose the subscript like I did to emphasis all the precedences here, but use the other parenthesis).


text:
Q: Opencv 2 Mat- Error on runtime I am starting with the basics of image processing and I am trying to convert a RGB image into grey scale using averaging.
My code is
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

#include<iostream>

using namespace cv;

int main()
{

    Mat image = imread("a.jpg");
    namedWindow("Original ");
    namedWindow("Grey");
    imshow("Original", image);
    Mat grey;
    std::cout << "hello\n";
    for (int i = 0; i < image.rows; i++)
    {
        for (int j = 0; j < image.cols; j++)
        {
            grey.at<Vec3b>(i, j) = (image.at<Vec3b>(i, j)[0] + image.at<Vec3b>(i, j)[1] + image.at<Vec3b>(i, j)[2]);
        }
    }
    imshow("Grey", grey);
    return 0;

}`

I think there is some problem with the Mat Grey , while accessing the element inside the for loop.

A: You need to initialize your grey,
Mat grey(image.rows, image.cols, CV_8UC1);

And then, during processing,
    for (int j = 0; j < image.cols; j++)
    {
        grey.at<Vec3b>(i, j) = ((image.at<Vec3b>(i, j)[0] + image.at<Vec3b>(i, j)[1] + image.at<Vec3b>(i, j)[2]))/3;
    }

The /3 will give you the true grayscale value.
HTH

A: Of course, You have not initialized it, so it is empty, you cannot access the elements.
Mat grey = Mat::zeros(image.rows, image.cols, CV_8UC1); Should fix it.
Try using an if statement before accessing the elements of a Mat:
if (grey.empty())
{
  std::cout << "Empty Mat!\n";
  return -1;
}

Another thing is that adding the image channels are not the true grayacale, see this.


text:
Q: how to call a form, which is define as a service, from the controller? how can I call a form (which is defined as a service) from the controller
//Here my code in the controller befor I define Form_NameType() as a service
$form = $this->createForm(new Form_NameType(), $obect_that_hydrate_my_form);

.
 // SERVICE
 blogbundle.Form_Nameform:
    class: BlogBundle\Form\Form_NameType
    arguments: [@security.context]
    tags:
      - {name: form.type, alias: FormAsAService }

A: To call any service in Symfony you need to use get method of ContainerInterface. So in Controller class you should call:
$form = $this->container->get('blogbundle.Form_Nameform');

If your Controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller then there is an alias for that method, and you can use this syntax (which is shorter):
$form = $this->get('blogbundle.Form_Nameform');

Check documentation of how to use services.

A: I just found how to do it... I tried before but I mispelled it so could not work.
$form = $this->createForm( 'FormAsAService' , $obect_that_hydrate_my_form);

FormAsAService is the name define in the service as an Alias and should be the same as the name define in the form class in the getName() function.
public function getName(){ return 'FormAsAService';}


text:
Q: The effect of using coordinating conjunctions at the beginning of a sentence As a volunteer tutor I recently noticed that several of my students use coordinating conjunctions to start a sentence. From what I know this is permitted, but often frowned upon.
I am wondering if there are rules about this usage, and also whether these conjunctions are used to provide any particular effect in English essay writing.
Thank you

A: The rule, if one is to accept rules as absolute, is to avoid beginning sentences with conjunctions.
This is the recommendation of Warriner and Lunsford, two reliable authorities used in US classrooms.
Like most rules, it is sometimes broken by artists and professionals who know what they are doing.  Beginning with a conjunction can add rhetorical weight to the sentence, particularly if the preceding thought is well and succinctly developed.
When my students (US native-speaking, university-bound adolescents) try this, they often achieve a horribly childish polysyndeton effect, and are generally roasted over a slow fire by their instructor.
If one is certain enough in one's convictions to stand up to a fiendish teacher or an unforgiving editor, one may try it.  But do so at your own risk.


text:
Q: How to control main timeline from external swf I have a main.swf and inside it is just a plain container movieclip. Using the Loader function I load an external swf  called content.swf inside that container. Container.swf has a button inside it.
Now when external swf is loaded in container mc which is on the main.swf stage, I want to move to another frame by clicking the button of the loaded external swf.
If I try to control it from the main timeline I get error saying
cannot convert flash.display::Loader@117e7041 to flash.display.MovieClip.

If I try to control it from the external swf I can trace the click on the button but timeline doesn't move to the wanted frame.

A: From the error message it seems that you are trying to cast a loader into a movie clip. Use the loader.content property instead.
var mc:MovieClip = loader.content as MovieClip;
//do whatever you want with mc

A: Make sure you're using event handlers as shown here because in your case loader.content has not loaded 'content.swf' yet when you try to add it to your container.
Also it is preferable to cast like this:
var mc:MovieClip = MovieClip(loader.content);

For the simple reason that 'as' won't throw you an error is the object you're trying to cast is null or can't be casted.


text:
Q: results of two feature selection algo do not match I am working on two feature selection algorithms for a real world problem where the sample size is 30 and feature size is 80. The first algorithm is wrapper forward feature selection using SVM classifier, the second is filter feature selection algorithm using Pearson product-moment correlation coefficient and Spearman's rank correlation coefficient. It turns out that the selected features by these two algorithms are not overlap at all. Is it reasonable? Does it mean I made mistakes in my implementation? Thank you.
FYI, I am using Libsvm + matlab.

A: It can definitely happen as both strategies do not have the same expression power.
Trust the wrapper if you want the best feature subset for prediction, trust the correlation if you want all features that are linked to the output/predicted variable. Those subsets can be quite different, especially if you have many redundant features.
Using top correlated features is a strategy which assumes that the relationships between the features and the output/predicted variable are linear, (or at least monotonous in case of Spearman's rank correlation), and that features are statistically independent one from another, and do not 'interact' with one another. Those assumptions are most often violated in real world problems.
Correlations, or other 'filters' such as mutual information, are better used either to filter out features, to decide which features not to consider, rather than to decide which features to consider. Filters are necessary when the initial feature count is very large (hundreds, thousands) to reduce the workload for a subsequent wrapper algorithm.

A: Depending on the distribution of the data you can either use spearman or pearson.The latter is used for normal distribution while former for non-normal.Find the distribution and use appropriate one.


text:
Q: Why am I getting a PX.Data.PXLockViolationException when I am try to create an item programmatically? I have an action button that is taking an item row and creating a new stock item based on that information. Here is the code:
public PXAction<CFBSCatalogHeader> ConvertToItem;
[PXButton()]
[PXUIField(DisplayName = "Convert to Item")]
protected void convertToItem()
{
    CFBSCatalogDetail row = Details.Current;
    if (row == null)
        return;

    InventoryItemMaint graph = PXGraph.CreateInstance<InventoryItemMaint>();
    graph.Item.Current = graph.Item.Insert();
    graph.Item.Current.InventoryCD = row.VendorPartID;
    graph.Item.Current.Descr = row.Descr;
    graph.Item.Current.ItemClassID = 526;
    graph.Item.Current.ItemType = "M";
    graph.Item.Current.ValMethod = "F";
    graph.Item.Current.TaxCategoryID = "TAXDEFAULT";
    graph.Item.Current.PostClassID = "INVDEFAULT";
    graph.Item.Current.LotSerClassID = "LOTSNDEFAU";
    graph.Item.Current.BaseUnit = "EA";
    graph.Item.Current.SalesUnit = "EA";
    graph.Item.Current.PurchaseUnit = "EA";

    graph.Item.Update(graph.Item.Current);

    graph.Actions.PressSave();
}

I get this error:

Despite the error, the item still saves. I'm assuming the record is attempting to save more than once, but I'm not sure why.
EDIT:
Here is the trace for the error:

11/7/2018 8:21:48 AM Error:
    Error: Another process has added the 'InventoryItem' record. Your changes will >>be lost.
at PX.Data.PXCache`1.PersistInserted(Object row)
      at PX.Data.PXCache`1.Persist(PXDBOperation operation)
       at PX.Data.PXGraph.Persist(Type cacheType, PXDBOperation operation)
       at PX.Data.PXGraph.Persist()
       at PX.Objects.IN.InventoryItemMaint.Persist() in F:\Bld\AC-FULL2018R112-JOB1\sources\WebSites\Pure\PX.Objects\IN\NonStockItemMaint.cs:line 2421
       at JAMS.AEF.InventoryItemMaintAMExtension.Persist(Action del)
       at CFBSModificationsTSC.VendorCatalog.convertToItem() in d:\Program Files\Acumatica ERP\TexasScenic\App_RuntimeCode\VendorCatalog.cs:line 70
       at PX.Data.PXAction`1.<>c__DisplayClass3_0.<.ctor>b__0(PXAdapter adapter)
       at PX.Data.PXAction`1.a(PXAdapter A_0)
       at PX.Data.PXAction`1.d__31.MoveNext()
       at PX.Data.PXAction`1.d__31.MoveNext()
       at PX.Web.UI.PXBaseDataSource.tryExecutePendingCommand(String viewName, String[] sortcolumns, Boolean[] descendings, Object[] searches, Object[] parameters, PXFilterRow[] filters, DataSourceSelectArguments arguments, Boolean& closeWindowRequired, Int32& adapterStartRow, Int32& adapterTotalRows)
       at PX.Web.UI.PXBaseDataSource.ExecuteSelect(String viewName, DataSourceSelectArguments arguments, PXDSSelectArguments pxarguments)

A: You need to set the CD value on the insert...
graph.Item.Current = graph.Item.Insert(new InventoryItem { InventoryCD = row.VendorPartID });

Then set the rest of your fields in the update as you have in your sample.


text:
Q: How to hide checkbox of the certain TreeNode in TreeView control using C#4.0 Win Form Application? In my C# Windows Form Application, I have Treeview control with checkboxes.
I want to hide check box of the certain tree node in TreeView control from user.How i do it?.
Please Guide me to get out of this issue...

A: This article explains on how you can hide the checbox of a certain node in a treeview.
Update
Explanation and code from the article:
Currently, there is not build-in support to get this done. But we can send
a TVM_SETITEM message to the treeview control, set TVITEM structure's state
field to 0, and TVITEM's hItem field to the treenode's handle. Then this
treenode will be got rid of the checkbox.
Sample code lists below:
public const int TVIF_STATE = 0x8;
public const int TVIS_STATEIMAGEMASK = 0xF000;
public const int TV_FIRST= 0x1100;
public const int  TVM_SETITEM = TV_FIRST + 63;

public struct TVITEM
{
    public int mask;
    public IntPtr hItem;
    public int state;
    public int stateMask;
    [MarshalAs(UnmanagedType.LPTStr)]
    public String lpszText;
    public int cchTextMax;
    public int iImage;
    public int iSelectedImage;
    public int cChildren;
    public IntPtr lParam;
}

[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

private void button1_Click(object sender, System.EventArgs e)
{
    TVITEM tvi=new TVITEM();
    tvi.hItem=this.treeView1.SelectedNode.Handle;
    tvi.mask=TVIF_STATE;
    tvi.stateMask = TVIS_STATEIMAGEMASK;
    tvi.state=0;
    IntPtr lparam=Marshal.AllocHGlobal(Marshal.SizeOf(tvi));
    Marshal.StructureToPtr(tvi, lparam, false);
    SendMessage(this.treeView1.Handle, TVM_SETITEM, IntPtr.Zero, lparam);
}

This code hides the selected treenode's checkbox and it works well on my
side. You may copy and paste in your project to have a test.


text:
Q: Azure Pack REST API Authentication After hours of search in Microsoft messed up API documentation for its products, i am still no where on how to authenticate a rest API request in windows azure pack distribution.
Primarily i want to create an API which automate the process of deploying virtual machine, but I cant find any documentation on how to acquire the authentication token to access the resources.
Some documentation states the use of ADFS, but don't provide any reference on the ADFS REST API for authentication.
And I don't want to use ADFS in the first place. I want to authenticate using AZURE tenant and admin interface.
In conclusion, if anyone can provide any help on the REST API authentication, it will make my day.
Thanks in advance.

A: You can use the following PowerShell to acquire an access token.
Add-Type -Path 'C:\Program Files\Microsoft Azure Active Directory Connect\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'

$tenantID = "<the tenant id of you subscription>"
$authString = "https://login.windows.net/$tenantID"

# It must be an MFA-disabled admin.
$username = "<the username>"
$password = "<the password>"

# The resource can be https://graph.windows.net/ if you are using graph api.
# Or, https://management.azure.com/ if you are using ARM.
$resource = "https://management.core.windows.net/"

# This is the common client id.
$client_id = "1950a258-227b-4e31-a9cf-717495945fc2"

$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" `
    -ArgumentList $username,$password

$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" `
    -ArgumentList $authString

$authenticationResult = $authContext.AcquireToken($resource,$client_id,$creds)

# An Authorization header can be formed like this.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken

A: I am doing some similar job like you did.
        static string GetAspAuthToken(string authSiteEndPoint, string userName, string password)
    {

        var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + "/wstrust/issue/usernamemixed"));

        var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
        identityProviderBinding.Security.Message.EstablishSecurityContext = false;
        identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
        identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

        var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
        {
            TrustVersion = TrustVersion.WSTrust13,
        };
        //This line is only if we're using self-signed certs in the installation
        trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };

        trustChannelFactory.Credentials.SupportInteractive = false;
        trustChannelFactory.Credentials.UserName.UserName = userName;
        trustChannelFactory.Credentials.UserName.Password = password;

        var channel = trustChannelFactory.CreateChannel();
        var rst = new RequestSecurityToken(RequestTypes.Issue)
        {
            AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
            TokenType = "urn:ietf:params:oauth:token-type:jwt",
            KeyType = KeyTypes.Bearer,
        };

        RequestSecurityTokenResponse rstr = null;
        SecurityToken token = null;

        token = channel.Issue(rst, out rstr);
        var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
        var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));

        return jwtString;
    }

Parameter "authSiteEndPoint" is your Tenant Authentication site url.
default port is 30071.
You can find some resource here:
https://msdn.microsoft.com/en-us/library/dn479258.aspx
The sample program "SampleAuthApplication" can solve your question.


text:
Q: Visualforce - Having an issue with page redirection intermittently I have 2 visualforce pages. When we click the close button from one page, it should redirect to the second page. It's working fine in almost all cases. But in between, it's failing. The page gets refreshed and stays there. No redirection happens.
Page Relevant code -
<apex:commandButton value="Close" action="{!redirectToParent}" />
Controller Code -
public PageReference redirectToParent() {
        //PageReference p = new PageReference('/apex/ParentPage');
        PageReference p = page.ParentPage;
        p.setRedirect(true);
        return p;
    }


text:
Q: How can you distinguish an original post from a reblog in Tumblr using Python? I have started using pytumblr to get posts from Tumblr. My goal is to see which are reblogs and which are original posts. I tried looking at the data that the Tumblr API provides for each post, but I can't find a difference between reblogs and original posts. Also, there is not a parameter stating something like that.
I use the following function but neither the reblog_info or notes_info gives me more information.
blog_posts = client.posts(example_blog, notes_info=True, reblog_info=True)

Any insights ? Thanks.

A: I found the problem. Instead of reblog_info=True, it needs to be reblog_info='true'.


text:
Q: How do i make a modal disappear after button has been clicked? I need to add a exit button to the top left corner of the modal, also I would like for the modal to disappear after the link has been copied. How would i go about doing this ?

            <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-100" viewBox="21 21" fill="currentColor">
              <path fill-rule="evenodd" d="M12.586 4.586a2 2 0 112.828 2.828l-3 3a2 2 0 01-2.828 0 1 1 0 00-1.414 1.414 4 4 0 005.656 0l3-3a4 4 0 00-5.656-5.656l-1.5 1.5a1 1 0 101.414 1.414l1.5-1.5zm-5 5a2 2 0 012.828 0 1 1 0 101.414-1.414 4 4 0 00-5.656 0l-3 3a4 4 0 105.656 5.656l1.5-1.5a1 1 0 10-1.414-1.414l-1.5 1.5a2 2 0 11-2.828-2.828l3-3z" clip-rule="evenodd" />
              <text x='35' y='18' style='fill:#444444' class='text-2xl'>Share Link</text>
            </svg>

<%= @vacancy.slug %>

                  <button onclick= "Copy(document.querySelector('#text').innerText)('#closemodal').click(function() {$('#modalwindow').modal('hide');});">
                    <svg class="align:right w-30 h-9" fill="none" stroke="currentColor" viewBox="0 0 25 25" xmlns="http://www.w3.org/2000/svg">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2"></path>
                    </svg>
                  </button>

A: I looked at the site for the library you're using, SweetAlert2 and here is what I found...
To add a close button, add showCloseButton: true to the object passed to Swal.fire()
https://sweetalert2.github.io/#configuration
To close the modal call Swal.close()
https://sweetalert2.github.io/#methods


text:
Q: How to integrate Foxit PDF Reader in Android? I have followed these steps in order to compile the Foxit library:
1) Download and install the Eclipse IDE (http://www.eclipse.org/), the Android SDK, ADT plugin for Eclipse, and the Android NDK (http://developer.android.com/sdk/index.html).
a) For Windows use, also download and install Cygwin (http://www.cygwin.com/). During Cygwin setup, make sure to include the "Devel -> make" package.
2) Download the Foxit embedded SDK Package.
3) Extract the Foxit embedded SDK Package to any directory.
4) Place the Foxit embedded SDK library and header files in fpdfemb_android/examples/demos/bin and include directory.
5) Build the NDK layer.
a) Open the Android.mk makefile in fpdfemb_android/examples/demos/demo(like "demo_view")/jni/ in a text editor and fill in the Foxit library name in the area designated for LOCAL_LDLIBS, dropping the lib prefix:
The demo is shipped as:
LOCAL_LDLIBS +=../bin/# fill in library name here
To add downloaded libfoxit.a from step 2, fill in as:
LOCAL_LDLIBS :=../bin/libfoxit.a
If the library provide is not named "libfoxit.a" please adjust accordingly.
b) Open Cygwin (Windows), or a terminal (Linux based), and navigate to the fpdfemb_android/examples/demos/demo(like "demo_view") directory. Run "ndk-build –B" to build the NDK/JNI layer.
Example:
me@myStation /myProjectPath/ > ndk-build –B
This assumes that the ndk directory is part of the $PATH environment variable. The command can also be qualified with the path to the NDK directory.

But then I'm getting this error in the terminal:
Android NDK: WARNING:jni/Android.mk:fpdfembedsdk: non-system libraries in linker flags: jni/../../bin/libfoxit.a
Android NDK:     This is likely to result in incorrect builds. Try using LOCAL_STATIC_LIBRARIES
Android NDK:     or LOCAL_SHARED_LIBRARIES instead to list the library dependencies of the
Android NDK:     current module
make: * No rule to make target `–B'.  Stop.
Could you please tell me if there is any way to resolve this?
Thank you.

A: I recommend trying Foxit's new MobilePDF SDK for Android which will provide most of the functionality found in the embedded PDF SDK that you've previously tried but it includes a user interface and can be integrated into your Android projects quickly.
http://www.foxitsdk.com/products/mobile-pdf-sdk/
This SDK replaces Foxit's embedded SDK.


text:
Q: Symfony Custom Field or Dynamic Form? I'm asking you for a litte advice in creating specific form in Symfony 3.
After reading Symfony Docs I have some solution in mind, but I'm asking you for sharing best aproach to achieve this.
I need to get output form like this: link for expected example form
As you see i need to make single field constiting of one checkbox and one input type. It should work like if user ticks the checkbox, the input will be active.
Should it be custom field with getParent() method from FormType as parent? Maybe this form should be created dynamically with event listener and some Javascript? Or it should be CollectionType field (but how it can store two different form field types?) or maybe you know different solution?
Basically one field should consist of two different field type depending from each other.
Any help, sharing knowledge or some code examples will be very welcome.

A: First, you have to build a custom FormType that composes a CheckboxType and a TextType. This is the server-side form part.
But, in order to enable/disable the text field on the fly, you'll have to use Javascript.
Finally, if you want to store the result information a single nullable text field (like a nullable varchar), you need a DataTransformer to convert data from persistece layer to view.
Let's see a kind of FormType :
<?php

namespace Form\Type;

use Form\DataTransformer\NullableTextTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class NullableTextType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('isNotNull', CheckboxType::class)
            ->add('text', TextType::class, array('required' => false))
        ;

        $builder->addModelTransformer(new NullableTextTransformer());
    }
}

And now the transformer :
<?php

namespace Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

class NullableTextTransformer implements DataTransformerInterface
{
    public function transform($value)
    {
        $nullableText = ['isNotNull' => false, 'text' => null];

        if (null !== $value) {
            $nullableText['isNotNull'] = true;
            $nullableText['text'] = (string) $value;
        }

        return $nullableText;
    }

    public function reverseTransform($array)
    {
        if (!is_array($array) || empty($array) || !isset($array['isNotNull']) || !isset($array['text'])) {
            return;
        }

        if ($array['isNotNull']) {
            return (string) $array['text'];
        } else {
            return;
        }
    }
}

Some twig for the form theming of the custom field :
{% block nullable_text_widget %}
{% spaceless %}

      {{ form_widget(form.isNotNull, {attr: {class: 'is-not-null-widget'}}) }}

    {{ form_widget(form.text, {attr: {class: 'text-widget'}}) }}

{% endspaceless %}
{% endblock nullable_text_widget %}

And finally, a bunch of JS lines to handle the front interactions :
$(document).ready(function() {
    $.each($('body').find('.nullable-text-widget'), function () {
        syncNullableTextWidget($(this));
    });
});

$(document).on('click', '.nullable-text-widget .is-not-null-widget', function (e) {
    var $nullableTextWidget = $(e.currentTarget).parents('.nullable-text-widget');
    syncNullableTextWidget($nullableTextWidget);
});

function syncNullableTextWidget($widget)
{
    if ($widget.find('.is-not-null-widget').prop('checked')) {
        $widget.find('.text-widget').prop('disabled', false);
    } else {
        $widget.find('.text-widget').prop('disabled', true);
        $widget.find('.text-widget').val('');
    }
}


text:
Q: How to eliminate number input arrows? I was wondering... is there a way to remove those arrows set by default to increase/decrease quantity in number inputs like in the image below?
Arrows

A:

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type="number"] {
    -moz-appearance: textfield;
}
<input type="number" />

But you still can use your mouse wheel to increase or decrease the number


text:
Q: Meaning of bottle her back up I need help with a word in some part of the book Born to Run by Christopher McDougall (Random House, 2018)

The Tarahumara immediately gave chase. The two canny old vets,
Sebastiano and Herbolisto, boxed Jenn in from the front while the
three other Tarahumara surrounded her on the sides. Jenn looked for a
gap, then burst loose and pulled away. Instantly, the Tarahumara
swarmed and bottled her back up.

I can't understand what is the meaning of "bottle her back up"?

A: From Merriam-Webster

bottle
transitive verb
1b to put or keep in a position or situation that makes free activity,
progress, or escape difficult or impossible —usually used with up

So, approximately:

got her back into a position where escape was impossible

A:
Instantly, the Tarahumara swarmed and bottled her back up.

The verb is "to bottle  up", e.g.
We bottled him up.
You can think of this as metaphor of keeping something confined inside a bottle.

The word back is not part of the verb - it is an adverb. It means roughly "again" or "once more", e.g.
We bottled her back up means We bottled her up again/once more.

A stricter definition of this sense of back, is given here:

back
adverb

*so as to return to an earlier or normal position or condition: "she put the book back on the shelf" https://languages.oup.com/

A: I can't help but think the bottling up is a different idea than the surrounding actions of the group. One bottles up a wild spirit or Genii. Her name is Jenn. One surrounds and captures the escaped fugitive. It looks to me as if they went overboard with the descriptions of surrounding, blocking off gaps and closing in. Finally when the capture is on he cannot help but use the bottle up description.


text:
Q: Sum of normally distributed random variables / moment generating functions I consider n independent random variables with $X_1$ ~ $ N(\mu_1, \sigma_1^2)......,$ $X_n$ ~ $ N(\mu_n, \sigma_n^2$)
I want to show that, $ \sum_{i=1}^n a_i X_i +b$~$ N(\sum_{i=1}^n a_i X_i+b, \sum_{i=1}^n a^2_i X_i )$
Using moment-generating functions I can show that $X_1+X_2 $ ~ $N(\mu_1+\mu_2, \sigma_1^2 +\sigma_2^2) $  and $M_{X_1+X_2}(t) = exp(\mu_1+\mu_2)t + \frac{(\sigma_1^2 +\sigma_2^2) \cdot t}{2}) $
Can I use this to prove my problem above?

A: I believe you want to show that
$$\sum_{i=1}a_iX_i+b \sim N(\sum_{i=1}^n a_i\color{red}\mu_i +b, \sum_{i=1}^na_i^2\color{red}\sigma_i^2)$$
Guide:

*

*Show that $a_iX_i \sim N(a_i\mu_i, a_i^2\sigma^2)$, possibly by using mgf.

*Show that $X_1+X_2 \sim N(\mu_1+\mu_2, \sigma_1^2+\sigma_2^2)$. That is the sum of two independent normal is normal with the mean being the sum of the mean, and the variance being the sum of the variance.

*Now, you can use induction to prove that.


text:
Q: Error when restoring 9.5 pgdump files on 9.6 postgres We have been using 9.5 postgres.
And we use pgdump to get backup files from that database and then subsequently use it to restore on a 9.6 postgres.
We were unable to restore successfully. Usually the minor version upgrade does not mean backwards breaking.
I am wondering what's the issue causing us to be unable to successfully restore on a 9.6 database.
We need to do so just in case we need to restore from archived data backups.

A: I was facing the same error when upgrading from 9.3 to 9.6.
The restore failed every time I tried but the dump was successful.
My solution to this problem was not to use the custom format! Instead I used the plain format. So I tried plain format with file extension sql, with utf8 encoding as user postgres. And obviously don't forget to include pre-data, data and post-data because otherwise your restore won't be complete. This works perfectly.
If your dump is ok, also try a full vacuum before the dump. If the vacuum is not ok, this might be your problem.

A: To Take Dump
pg_dump --username=postgres --format=c --file=e:/testdbdump.sql testdb

OR
pg_dump -U username databasename >>sqlfile.sql

To Restore
pg_restore --username=postgres --dbname=testdb<d:\sqlfile.sql

pg_restore --username=postgres --dbname=testdb <d:\sqlfile.sql

pg_restore --username=postgres --dbname=testdb <d:\testDBApr18.sql

pg_restore --username=postgres --dbname=testdb <c:\Backup\testdbDBApr18.sql

// PG DUMP & RESTORE THAT WORKS FOR ME
pg_dump -U postgres -h localhost --format=c testdb > db_dump_file.dump

pg_restore -U postgres -h localhost -v -d testdb db_dump_file.dump


text:
Q: HTAccess: Rewrite Subdomain to HTTPS Main site I want to rewrite a subdomain to a folder in my main site.
For example, test.example.com --> example.com/test.
I only have an SSL (CA-verified) certificate for example.com, but not a wildcard certificate. So, test.example.com is encrypted but not verified. So, is it possible to rewrite https://test.example.com to https://example.com/test, while also maintaining verification? Or should I just use a redirect?
Currently, this is my folder structure:
.htaccess
public_html/ # this is the document root for example.com
    ...
test/ # document root for test.example.com
    ...

A: Place this rule in /test/.htaccess:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(test)\.(example\.com)$ [NC]
RewriteRule ^ http://%1/%2%{REQUEST_URI} [L,NE,R=302]

This will redirect test.example.com --> example.com/test


text:
Q: Unknown column in 'field list" i keep getting this error when trying to update/insert a record:

Unknown column 'test' in 'field list' SQL=INSERT INTO oovea_vehiclemanager_feature_vehicles (fk_vehicleid, fk_featureid, fk_value) VALUES (13, 56, test)

Here is the form I have setup:
<?php
if (isset($_POST['feature'])){
    $feature = $_POST['feature'];
    $featureInput = $_POST['featureInput'];
    $database->setQuery("DELETE FROM #__vehiclemanager_feature_vehicles WHERE fk_vehicleid = " . $vehicle->id);
    $database->query();
    for ($i = 0; $i < count($feature); $i++) {
        $database->setQuery("INSERT INTO #__vehiclemanager_feature_vehicles (fk_vehicleid, fk_featureid, fk_value) VALUES (" . $vehicle->id . ", " . $feature[$i] . ", " . $featureInput[$i] . ")");
        $database->query();
    }
}
?>

And here is my form fields:
<?php
if($vehicle_feature[$i]->name): ?>

    <input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[]" value="<?php echo $vehicle_feature[$i]->id; ?>">
    <label for="checkbox_addveh<?php echo $i; ?>"><?php echo $vehicle_feature[$i]->name; ?>
    <input type="text" class="" id="input_addveh<?php echo $i; ?>" name="featureInput[]" value="<?php echo $vehicle_feature[$i]->value; ?>">

<?php endif; ?>

Obviously, from the error above, I can see that the value for the featureInput field is being posted, and the syntax for my "INSERT INTO" looks correct. Also, it will work if i simply remove the column for "fk_value","$featureInput[$i].

A: Try to use single quotes:
VALUES ('" . $vehicle->id . "', '" . $feature[$i] . "', '" . $featureInput[$i] . "')

A: You haven't properly quoted your string data in your query.
Try this:
<?php
if (isset($_POST['feature'])) {
    $feature = $_POST['feature'];
    $featureInput = $_POST['featureInput'];
    $database->setQuery("DELETE FROM #__vehiclemanager_feature_vehicles WHERE fk_vehicleid = $vehicle->id");
    $database->query();
    for ($i = 0; $i < count($feature); $i++) {
        $database->setQuery("INSERT INTO #__vehiclemanager_feature_vehicles (fk_vehicleid, fk_featureid, fk_value) VALUES ($vehicle->id,$feature[$i],'$featureInput[$i]')");
        $database->query();
    }
}
?>

You also have some serious SQL injection issues you need to deal with otherwise an attacker could very easily hack your database.


text:
Q: Extra space preceding change of language in XəLaΤεχ Polyglossia I am writing in Portuguese with some English words thrown in.  The issue is that when a line with English text breaks, the English text gets preceded by extra spacing:
\documentclass {scrbook}

\usepackage {polyglossia}

\setmainlanguage {portuguese}
\setotherlanguage {english}

\begin {document}
no \textenglish {Hillsdale college}, na primavera de 2006, e sou grato
ao professor \textenglish {Donald Westblade} pela oportunidade de
palestrar em minha

\end {document}

Results in something like 'no__Hillsdale college', where __ denotes extra spacing.

A: So the issue is a Polyglossia 1.46 bug.  Installing a user local 1.47 with tlmgr solved the issue, even if it caused another one.


text:
Q: Как подключиться к интернет через iexplore? Делаю проект Windows Forms приложения на Visual Studio 2010. Программа работает со службой WCF опубликованной в интернете. Т.е. для нормальной работы этого приложения, нужно активное соединение с интернет.
Сейчас нормальная работа возможна, только, если есть прямое подключение компьютера к интернет. Обычно в программах бывают настройки подключения к интернет: прокси-сервер, как у браузера. Например, некоторые программы используют настройки iexplore, отображается диалог авторизации на сервере.
Как я могу реализовать тоже самое в своем приложении, настрйки подключение к интернет?
Не важно, на чем и какой проект приложения, лишь бы можно было добавлять ссылки на службы WCF и работать с ними.
UPD
Остался вопрос: как подключиться к интернет используя настройки iexplore?

A: Добавить настройки прокси в приложение можно в конфиге, например так:
  <system.net>
    <defaultProxy useDefaultCredentials="true">
      <proxy proxyaddress="server:port"/>
    </defaultProxy>
  </system.net>

UPD: Про диалог браузера ничего не могу сказать, но программно устанавливать прокси можно, как в этом примере с МСДН.


text:
Q: Change a Paid Android app to a Free app with in-app purchasing I have a successful paid for application on Google Play Store and want to update this app to be a free application with in-app purchasing.
I have just completed developing the free version of the app which gives users restricted access which can then be unlocked using an in-app purchase system.
The issue i have is that all my existing users who have paid for the app will upgrade and then be prompted to pay again, which of course isn't right.
Is there any way to check the purchase history of the user, identify that they have paid for the app previously and unlock the extra features without the in-app purchase?
Thanks for any help.
Lewis

A: It's been a year, so the OP probably doesn't need this, but in case anyone else happens upon this one...
You could approach this a couple of ways.  Obviously there is some business logic on your new in-app purchasing app to track who has/hasn't paid.  So the two ways I see you being able to go about this is as follows:
Idea 1:
You could do a preliminary update to your paid app that stores a SharedPreference or some other persistence in the app (you could store the versionCode, so you know what you're upgrading from and have business logic around that).  Then update to the free version, and have the free version check your shared preference and do the right thing on an update from a "paid" versionCode.
Idea 2:
You could keep both apps separate (have a paid version and a free with in-app purchases) and push an update to the paid version to have a BroadcastReceiver that doesn't really do anything other than listen to specific intents and have your in-app purchase check to see if something will receiver your custom intent.  If your old paid-version exists, then they paid for it, if not they didn't.  (If they paid for the paid version then uninstalled you'll have problems obviously...)
Idea 3:
You could keep both apps separate (have a paid version and a free with in-app purchases), and push an update to the paid version that just posts an Intent to open the in-app purchase app (if it's installed) with some special arguments, to let you know they opened it via a paid app and do the right thing to set them up as having paid for it in-app.  That opens yourself up to some detection problems though... (Solvable but kind of clunky)

A: You can keep the existing paid version and create another free version.
If you really don't want to have 2 versions, just make it free and tell users something like 'Contact us if you have bought the paid version. We will give you redeem code to unlock xxx'.

A: https://developer.android.com/distribute/tools/launch-checklist.html#decide-price
This link seems relevant, hope it helps

On Google Play, you can publish apps as free to download or priced. Free apps can be downloaded by any Android user in Google Play. Paid apps can be downloaded only by users who are in a country that supports paid downloads and have registered a form of payment in Google Play, such as a credit card or Direct Carrier Billing.
Deciding whether you apps will be free or paid is important because, on Google Play, free apps must remain free.
Once you publish an app as a free app, you cannot change it to being a priced app. However, you can still sell in-app products and subscriptions through Google Play's In-app Billing service.
If you publish your app as a priced app, you can change it at any time to be a free app (but cannot then change it back to priced). You can also sell in-app products and subscriptions.
If your app is be priced, or if you'll be selling in-app products, you need to set up a Google payments merchant account before you can publish.

A: I feel the most easy way is to use theese line of codes
This gives you the old version code
SharedPreferences prefs = getSharedPreferences("Name_of_Prefs", MODE_PRIVATE);
int oldVersionCode = prefs.getInt("version_code", -1);

This gives you the current version code
int currentVersionCode = getPackageManager().getPackageInfo(getPackageName(),0).versionCode;

Now you can compare and do what you want. Don't forget to update after every time
with this line of code
prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).commit();

A: In my case (affirmations counter app)
my paid app is running based on sharepreference value "lastaffirmationcount"
in my new iap app i just changed the way of I'm saving the affirmations counter values like "lastaffirmationscount_foriap"
So what i did in my free with In app purchase app is,just cross checked the "lastaffirmationcount" value is not null,if its null then it means new user,if not null then it means he is old user who bought the paid app
so the old user will not suffer forever
(Optionally Once its checked i immediately ask this user to sign in with google and saved his email as a premium user to ur database)

A: For Google Play there's no distinction between having paid for an app or downloading it for free. For example, if an user download an app while it's free and it's later changed to paid that user will still have full access to it, even being able to download it on other devices.
There are some lame workarounds for that:

*

*Enable google play game services on the paid version and try to convince users to connect to it. Use google play services to store "bought while paid" information to the cloud and restore it whenever that user logins

*Give all the users who've bought some key to unlock features

*Create a different for the free version of the game

That said, keep in mind that many games have become free after some time. Maybe the users won't mind it that much.


text:
Q: Scrapy - bug in custom DownloaderMiddleware I have list of thousands of URL which I scrape using one Spider. Some URLs has the same domain. I want to count a number of Timeout errors per domain. If for domain x, is a number of Timeouts higher than LIMIT, I want to avoid scraping all URLs of this domain. Instead, I want to treat them as it were normal Timeout (without real requesting) - my spider then handle Timeouts in errback function.
So the point is that I don't have to keep trying to scrape URLs from domain X if this domain raised 5 Timeouts already. I just want to fake those Timeouts without actually sending requests.
I've created a middleware for this purpose, which seems to be a good way but it has some bugs.
For example, if an URL has to be automatically Timeouted (without real request), it seems that scrapy tries to repeat this request multiple times.
LOG:
2017-05-22 20:37:16 [engineapp.engine.scrapy.scrapytest.scrapytest.middlewares] INFO: Arbitrary Timeout! OCID: 12751
2017-05-22 20:37:16 [engineapp.engine.scrapy.scrapytest.scrapytest.middlewares] INFO: Arbitrary Timeout! OCID: 12751
2017-05-22 20:37:16 [engineapp.engine.scrapy.scrapytest.scrapytest.middlewares] INFO: Arbitrary Timeout! OCID: 12751

Maybe the problem is that I'm not returning anything from process_request and process_exception functions.
This is the middleware:
class TimeoutProcessMiddleware():
    timeouts = defaultdict(int)

    def process_request(self,request, spider):
        logger.debug(self.timeouts)
        occ = request.meta['occ']
        domain = Site.parse_site_from_url(request.url)

        if self.timeouts[domain] >= settings.TIMEOUT_COUNT_LIMIT: # If we detected timeout for more than x URLs with the same domain
            logger.info('Arbitrary Timeout! OCID: {}'.format(occ.id))
            raise TimeoutError()

    def process_exception(self,request, exception, spider):
        logger.debug('Processing exception: EXC: {}'.format(exception))
        if exception.__class__ in [TimeoutError,TCPTimedOutError]:
            domain = Site.parse_site_from_url(request.url)
            self.timeouts[domain]+=1

This is a part of Spider errback:
class MainSpider(scrapy.Spider):
     ...

     def err(self, failure):
            if failure.check(HttpError):
                ....
            elif failure.check(TimeoutError, TCPTimedOutError): # HERE I WANT TO PROCESS ALL TIMEOUTS
                self.process_timeout_error(occ)

Do you know what to do?


text:
Q: Issues with corner radius I have the following code
class CourseItemCollectionViewCell: UICollectionViewCell {
    var imageView: UIImageView!
    var label: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)

        imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.isUserInteractionEnabled = false
        contentView.addSubview(imageView)

    }

    override func layoutSubviews() {
        super.layoutSubviews()

        var frame = imageView.frame
        frame.size.height = 120
        frame.size.width = 212
        frame.origin.x = 0
        frame.origin.y = 0
        imageView.frame = frame

        imageView.layoutIfNeeded()
        imageView.layer.masksToBounds = true
        imageView.layer.cornerRadius = 8

Unfortunately, corner radius is not working on the image view. What happens is that the top upper edges of the image look rectangular, while the bottom looks circular. It works for the bottom but not for the top. What I'm I doing wrong?
Update I tried:
let imageView: UIImageView = {
    let imageView = UIImageView(frame: .zero)
    imageView.contentMode = .scaleAspectFill
    return imageView
}()
override init(frame: CGRect) {
      super.init(frame: .zero)
      setupViews()
      setupLayouts()
}

private func setupViews() {
    contentView.clipsToBounds = true
    contentView.backgroundColor = .clear
    contentView.isUserInteractionEnabled = true

    imageView.layer.masksToBounds = true
    imageView.setRoundedEdge(corners: [.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 8)

    contentView.addSubview(imageView)
    contentView.addSubview(label)
}

extension UIImageView {
    func setRoundedEdge(corners:UIRectCorner, radius: CGFloat){
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
}

Before I see

Now I see

Note images are loaded via URL.

A: Try to add a containerView in your collectionViewCell, add the imageView in it (I set my image, you set your url image) and set constraints with Auto Layout like this:
let containerView: UIView = {
    let v = UIView()
    v.backgroundColor = .red
    v.layer.cornerRadius = 12
    v.layer.masksToBounds = true
    v.translatesAutoresizingMaskIntoConstraints = false

    return v
}()

now set imageView and Label:
let dummyImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.image = UIImage(named: "yourImage")
    imageView.contentMode = .scaleAspectFill
    imageView.layer.cornerRadius = 8
    imageView.clipsToBounds = true
    imageView.translatesAutoresizingMaskIntoConstraints = false

    return imageView
}()

let dummyLabel: UILabel = {
    let label = UILabel()
    label.backgroundColor = .clear
    label.isUserInteractionEnabled = false
    label.text = "Lean Methodology"
    label.font = UIFont.systemFont(ofSize: 30, weight: .regular)
    label.textColor = .black
    label.translatesAutoresizingMaskIntoConstraints = false

    return label
}()

after that set constraints with Auto Layout
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    backgroundColor = .white

    contentView.addSubview(containerView)
    containerView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
    containerView.heightAnchor.constraint(equalToConstant: 230).isActive = true
    containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
    containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true

    containerView.addSubview(dummyImageView)
    dummyImageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    dummyImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    dummyImageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
    dummyImageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true

    addSubview(dummyLabel)
    dummyLabel.topAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
    dummyLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
    dummyLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
    dummyLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}

This is the result:

A: Try this, some views might clip the layer and extend outside of its designated frame. Usually, when cornerRadius doesn't work, I would use this extension:
extension UIImageView {
    func setRoundedEdge(corners:UIRectCorner, radius: CGFloat){
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
}

with usage being
imageView.setRoundedEdge(corners: [.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 8);

Let me know if this fixes your issue.


text:
Q: Insert picture/logo at a specific position Im using the MastersDoctoralThesis template
and i want to add a logo of my university on the title page. I marked the desired position of the logo with a black dot, as you can see in the following picture:

The logo should not change the position of text.

A: You can use TikZ's remember picture,overlay:
\documentclass{book}
\usepackage{tikz}
\begin{document}
\begin{titlepage}
  \centering
  \vspace*{10cm}
  {\huge Your title page here}

  \tikz[remember picture,overlay]
    \path (current page.north east) ++ (-5,-3) node {\includegraphics{example-image-duck}};
\end{titlepage}
\end{document}

A: I'd do this with eso-pic. You can put pictures in the background of the page. With \AddToShipoutBG* you add something to the next page that is shipped out, and with \put you can put stuff at arbitrary places inside the argument of \AddToShipoutBG*.
(in the following I use report, but it should also work with MastersDoctoralThesis)
\documentclass[]{report}

\usepackage{eso-pic}
\usepackage[]{graphicx}
\AddToShipoutPictureBG*
  {%
    \put(\LenToUnit{.6\paperwidth}, \LenToUnit{.8\paperheight})
      {\includegraphics{example-image-duck}}%
  }

\usepackage{duckuments}% dummy content for following pages

\begin{document}
\author{Someone}
\title{Something}
\date{Somewhen}

\maketitle

\duckument
\end{document}

Resulting title page:


text:
Q: inequality in finite group representation theory I would like to understand the first inequality of the proposition below.
Suppose $Q$ is constant on conjugacy classes of $G$, i.e. for all $g,h\in G$, $Q(hgh^{-1}) = Q(g)$. For an
irreducible representation $\rho$ let
\begin{equation}
    \tilde{Q}(\rho) = \frac{1}{d_\rho} \sum_{g \in G}Q(g)\chi_\rho(g)
\end{equation}
where $\chi_\rho(g) = \operatorname{Tr}(\rho(g))$ is the trace of $\rho(g)$. Then for each $g \in G$,
$$
1 - |G|Q(g) \le \sum_\rho d_\rho |\chi_\rho(g) \tilde{Q}(\rho)| \le \sum_\rho d_\rho^2 |\tilde{Q}(\rho)|
$$
where $\sum_\rho$ denotes summation over all non-trivial irreducible representations.
Moreover, in the article the authors say the inequality is a consequence of the inverse Fourier transform formula for $Q$. The Fourier transform of $Q$ is given by
$$
\hat{Q}(\rho) = \sum_g\rho(g)Q(g),
$$
and the inverse Fourier transform is given by
$$
Q(g) = \frac{1}{|G|}\sum_{\rho}d_{\rho}\operatorname{Tr}\left(\hat{Q}(\rho)\rho(g^{-1})\right),
$$
where $\operatorname{Tr}$ is the trace.
This inequality is in the article by Diaconis and Aldous, Proposition 6.3, which can be seen at this link:
Diaconis and Aldous

A: First of all, notice that the Fourier inversion formula is given by
$$Q(g) = \frac{1}{|G|}\sum_{\hat G}d_{\rho}\operatorname{Tr}\left(\hat{Q}(\rho)\rho(g^{-1})\right),$$
where the summation is taken over all (inequivalent) irreducible representations of $G$.
Second, if $Q$ is constant on conjugacy classes and $\rho$ is an irreducible representation, then a corollary of Schur's lemma says that
$$\hat Q(\rho)=\tilde Q(\rho)I$$
(for example, see Serre (GTM 42), $\S$ 2.5, Proposition 6).
Thus,
\begin{align}
1 - |G|Q(g)&\leq |1-|G|Q(g)|\\
&=|1-\sum_{\hat G}d_{\rho}\operatorname{Tr}\left(\hat{Q}(\rho)\rho(g^{-1})\right)|\\
&=|1-\sum_{\hat G}d_{\rho}\operatorname{Tr}\left(\tilde Q(\rho)I\rho(g^{-1})\right)|\\
&=|1-\sum_{\hat G}d_{\rho}\tilde Q(\rho)\chi_\rho(g)|\\
&=|1-d_{\rho_1}\tilde Q(\rho_1)\chi_{\rho_1}(g)-\sum_\rho d_\rho \chi_\rho(g) \tilde{Q}(\rho)|,
\end{align}
where $\rho_1$ denotes the trivial representation. We have $d_{\rho_1}=1=\chi_{\rho_1}(g)$. Moreover, $$\tilde Q(\rho_1)=\sum_{g \in G}Q(g)\chi_\rho(g)=\sum_{g \in G}Q(g)=1.$$
The desired inequality follows.


text:
Q: How can i solve : Configuration with name 'compileClasspath' not found As i found when we want to use specific version of dependency in Gradle we have 3 ways :
The first one is strict version like this :
implementation("com.squareup.okhttp3:okhttp") {
   version {
       strictly("3.12.12")
   }
}

This way does not work on okhttp for me and i dont know why!
The second way using force like this :
implementation("com.squareup.okhttp3:okhttp:3.12.12") {
   isForce = true
}

This way work for me but it is deprecated
The third way using resolutionStrategy like this :
configurations {
    "compileClasspath" {
        resolutionStrategy.force("com.squareup.okhttp3:okhttp:3.12.12")
    }
}

In this way i faced with this error :
Configuration with name 'compileClasspath' not found.

So my question is how can i use the third way? if it be located at the bottom of the dependency block its enough?

A: You should be using configurations.all like :
configurations.all {
    resolutionStrategy.force("com.squareup.okhttp3:okhttp:3.12.12")
}


text:
Q: Extent of topic complexity for 15-minute demo lesson Following a recent job interview, I was invited to give a demo lesson. As is mostly the case, I suppose, the hiring staff are going to pose as students. The school did not give any specific instructions except that it should be between 10 and 15 minutes. By asking, I found out that competence levels of starting students range between A2 and B1 (CEFR).
The way I see it, I have two options: either to fully address a simple theme that could lend itself to being taught in 15 minutes; or to partially tackle a more complex topic. At first I was leaning toward the latter, because it would allow the committee to decide how successful I am at breaking down complexity. A much more experienced teacher than I am also advised me to take this route: 'If I was a hiring manager, I would definitely give you extra points for not choosing something simple.' I was thinking of doing the difference between the present perfect simple and past simple. But then I thought that such a lesson would have to assume the students are comfortable with a wider range of structures (Affirmative, interrogative and negative structures of both the PP simple and past simple; irregular verbs; WH-questions, strong and weak forms …). It would not go well if, after the lesson, each time the committee asked me why I did not address a certain point, I responded by saying I 'assumed' the students had already learnt it.
Now, I am considering going with the first option. I am thinking I could do some/any, gone/been, should/shouldn't … These subjects require much less background knowledge and can fit a 15-minute time frame.
Here are my questions:

*

*If you were in my place, which option would you go for?

*Could you suggest some additional topics?
Any general advice would also be highly appreciated.
Many thanks,
absconditus

A: What is the class size for which you are interviewing? I assume that the committee won't be much more than five people. In this case I would say that your lesson should be designed for a five person classroom. A smaller class size gives you some flexibility to adapt a lesson to the relative skills of the students.
To this end, I would recommend my tutoring philosophy: start ambitiously and be well prepared to adjust. A discussion of the differences between PP simple and past simple is sufficiently ambitious. It has been my experience that the students will most clearly show their deficiencies when required to draw from previous lesson concepts. If you begin your discussion and find that students are completely confused about irregular verbs, then change your lesson to reflect that.
With this strategy you shouldn't get attached to finishing the original lesson within the 15 minutes. Discovering debilitating lapses of knowledge that must be addressed is part of being a teacher. Never say that you "assumed" that students already learned a certain point. Merely say that you chose the most efficient way to discover student proficiency and knowledge holes, and then went about patching those holes. In a normal classroom you attempt to teach the curriculum in the allotted time. If lack of fundamentals on the part of the students forces you to adjust a little bit, then adjust.
I recognize that the strategy stated above might be the completely wrong way to go about it, depending on the context of the job. A 15 minute discussion that perfectly explains low-reaching fruit might be just what the job requires. However, I would much prefer to hire a teacher that knows how to adapt when concepts get tough and students have knowledge deficiencies.
Most of all, explain your reasoning! Don't leave the committee wondering why you did something. They might assume you missed something for which you in fact accounted.


text:
Q: What is the C++ equivalent to GetObject in JavaScript and VBScript? What is the C++ equivalent to GetObject in JavaScript and VBScript?
The closest match I found to my question is:
http://codewiz51.blogspot.com/2008/06/vb-script-getobject-c-api-cogetobject.html
However the sample use an unexisting interface and asking for the IUnknown returns null. Did someone have an example that works?

A: I figured out the issue. The object I wanted to access was

winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv

I mistakenly took \\ for an escapement. In C++ the correct query is :

::CoGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\default:StdRegProv", NULL, IID_IUnknown, (void**)&pUnk);

Thank you :)

A: The article you linked to is correct. You may be providing the wrong interface ID, or the display name could be wrong. You should check the return value from the CoGetObject call.

A: If asking for IUnknown returns NULL, there is no object by that name. Each COM object implements IUnknown.

A: Have you initialized COM before making any COM calls?
Look up CoInitializeEx.


text:
Q: PHP array cannot use key to get value I have this array:
Array ( ["id"] => 2015020052 ["gs"] => 5 ["ts"] => "THURSDAY 10/15"
["tsc"] => "final" ["bs"] => "FINAL" ["bsc"] => "final"
["atn"] => "Chicago" ["atv"] => "blackhawks" ["ats"] => "1"
["atc"] => "" ["htn"] => "Washington" ["htv"] => "capitals"
["hts"] => "4" ["htc"] => "winner" ["pl"] => true ["rl"] => true
["vl"] => true ["gcl"] => true ["gcll"] => true ["ustv"] => ""
["catv"] => "" )

I am trying to get particular values, like home team and away team and the scores, but I cannot get the values.
I am trying this:
echo "away team is ". $array['atv'];

But i just get
away team is
What am i missing????
var_dump gives me this:
Array vs array(21) { [""id""]=> string(10) "2015020051"
[""gs""]=> string(1) "5" [""ts""]=> string(16) ""THURSDAY 10/15"
[""tsc""]=> string(7) ""final"" [""bs""]=> string(7) ""FINAL""
[""bsc""]=> string(7) ""final"" [""atn""]=> string(8) ""Ottawa""
[""atv""]=> string(10) ""senators"" [""ats""]=> string(3) ""0""
[""atc""]=> string(2) """" [""htn""]=> string(12) ""Pittsburgh""
[""htv""]=> string(10) ""penguins"" [""hts""]=> string(3) ""2""
[""htc""]=> string(8) ""winner"" [""pl""]=> string(4) "true"
[""rl""]=> string(4) "true" [""vl""]=> string(4) "true"
[""gcl""]=> string(4) "true" [""gcll""]=> string(4) "true"
[""ustv""]=> string(2) """" [""catv""]=> string(2) """" }

A: I was also facing the same problem.
Problem:
The array was retrieved in Database [saved as a JSON encoded variable].
I was not getting the array element by key like $arr['key']
Solution:
Tried everything, no success.
Lastly, tried json_decode() and json_encode().
$arr = json_decode(json_encode($arr), TRUE);
Note that second parameter TRUE is very important. Otherwise, you will get object returned.
And it worked like charm.

A: You are not doing a correct associative array, this must be like this:
<?php

$array = [
        'id' => 2015020052,
        'gs' => 5,
        'ts' => "THURSDAY 10/15",
        'tsc' => "final",
        'bs' => "FINAL",
        'bsc' => "final",
        'atn' => "Chicago",
        ...
    ];

Now you can get the value:
echo "away team is ". $array['atv'];

Here is the Demo


text:
Q: Special characters in mod_rewrite url I want this URL:
http://www.mydomainblabla.com/s/can+you+drill+shrinky+dinks?.html

to be rewritten to this one:
http://www.mydomainblabla.com/search.php?q=can+you+drill+shrinky+dinks?

I am using this mod_rewrite rule in my .htaccess to accomplish this
RewriteRule ^s/(.+).html$ search.php?q=$1 [L,QSA]

However, the result is not as I want it, when I go to the first url, I get a page not found message.
The same problem occurs when I visit this url:
http://www.mydomainblabla.com/s/http://www.zakgeldnodig.nl/.html

which should be rewritten into this one:
http://www.mydomainblabla.com/search.php?q=http://www.zakgeldnodig.nl/

What modifications should I make to my .htaccess to make this work?

A: Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+s/(.+?)\.html [NC]
RewriteRule ^ search.php?q=%1 [L,NE]


text:
Q: Control number of states in matlab linear analysis tool I am linearizing a simulink model with 3 inputs and 6 outputs using MATLAB linear analysis tool. It includes an integrator which transfers all my 6 states which are: Roll, Rolldot, Pitch, Pitchdot, Yaw, and Yawdot.
The problem is that the linearized system includes only 3 states which is contrary to what I want to model. This is seemingly done by the BlockReduction option in the linearize command. I'm wondering if there is a way that I can tell the linear analysis tool not to minimally realize my system. I haven't tried using command syntax, but I figure that it can be done that way.

A: I can't remember if there is an option in the linearisation tool (GUI) to turn off the Block Reduction, but there is definitely a way to do this using the command line version, see linearizeOptions:
sys = 'watertank';
load_system(sys);
opspec = operspec(sys);
op = findop(sys,opspec);
sys_io(1)=linio('watertank/PID Controller',1,'input');
sys_io(2)=linio('watertank/Water-Tank System',1,'openoutput');
options = linearizeOptions('BlockReduction','off'); % add other options as required
linsys = linearize(sys,op,sys_io,options);
bdclose(sys);


text:
Q: Mostrar lista de emails com Tkinter Estou a fazer um programa em Tkinter que se baseia numa caixa de e-mail. Pretendo, numa janela de Tkinter mostrar uma lista de emails que tem como base um diretorio com ficheiros .txt ( que são os emails). Estive à procura de um comando para criar uma caixa e mostrar em linhas os nomes dos txt mas não consigo encontrar. Alguém sabe algum?

A: Existe um widget que se chama Treeview, que faz parte do modulo ttk (um sub-modulo de tkinter), que te permite de ter uma espécie de tabela onde claramente podes adicionar linhas (ou até mesmo uma hierarquia de linhas (umas debaixo doutras como se fossem filhas umas das outras).
Aqui tens um exemplo que eu tinha criado a bastante tempo atras onde te mostra como remover linhas duma Treeview, claramente mostra-te também como adicionar (se não como poderia remover algo que não existe?).

https://github.com/dossan/tkinter/blob/master/other/howtos/remove_row_from_tree.py

Também podes adicionar "event handlers" a especificas linhas. Por exemplo, se quisesses chamar uma função quando fazes click numa linha, podes faze-lo aplicando aqueles que se chamam "tags".
Se queres saber mais sobre este widget (e como adicionar "tags"), dá uma olhada a este artigo bastante bem escrito e com outros exemplos:

http://www.tkdocs.com/tutorial/tree.html

Nota bem que esse artigo tem código também para outras linguagens de programação que não sejam Python, mas podes especificamente ler código só em Python se o especificas ao lado direito em cima, num drop down menu que se chama "Show".
Existem também outras livrarias third-party que te permitem criar mesmo tabelas. Por exemplo, esta aqui que tenho como repositório no meu account do Github criada por Guilherme Polo. Mas existem outras, como tkintertable. Se não também poderias criar tu a tua tabela, mas talvez não valha a pena.


text:
Q: Copy command in Snowflake failed to parse \n in data I have a CSV file format data that brings string values and JSON entries. For example -

message_id
status
user_detail
date

a123bxe
Success
{user_name:'jim',full_name:'Jim Mathews'}
2021-07-28

b245apl
Success
{user_name: '\n153674@dewbbe',full_name:'Dev Webbe'}
2021-07-28

The file has | as field delimiter \n as a record delimiter. Because of \n coming in the data value, snowflake considers the rest as a new record and tries to enter the rest of the data under the table which eventually giving an error due to data type mismatch.
Here is the file format, I'm using:-
FILE_FORMAT =  COMPRESSION = 'AUTO'
FIELD_DELIMITER = '|'
RECORD_DELIMITER = '\n'
SKIP_HEADER = 0
ESCAPE_UNENCLOSED_FIELD='\n'
VALIDATE_UTF8 = TRUE
EMPTY_FIELD_AS_NULL = TRUE
TRIM_SPACE = TRUE
ERROR_ON_COLUMN_COUNT_MISMATCH = FALSE
NULL_IF = ('NULL', 'null','None','NONE',"""")
How should I escape the \n coming as a part of data value?

A: Try using the FIELD_OPTIONALLY_ENCLOSED_BY parameter with a single quote


text:
Q: No HTTP2 protocol between ngrok AWS server/client I am trying to connect to my ngrok server on AWS EC2 instance with my ngrok client on windows via HTTP2, but whatever i've tried i always end up with http1.1 protocol.
I have generated a self-assigned SSL certificate both as also from an SSL certificate provider, but it didn't work. Both server and client are using the same certificate. Localhost connections are via HTTP2, but when i am trying to expose the local server with the ngrok server all my connection are with HTTP1.1, as also bad request, not secure connection, etc.
I followed this  [walkthrough]: https://www.svenbit.com/2014/09/run-ngrok-on-your-own-server/


text:
Q: Order of elements become wrong after rendering erb I have a wired problem when developing rails. The order of elements in container is

  <%= yield %>
  <%= render 'layouts/footer' %>
  <%= debug(params) if Rails.env.development? %>

For most of the pages, it works well. But it goes wrong when it renders following page
<% provide(:title, 'All Apps') %>

All Apps

        App Name
        Status
        Delete

        <%= render @apps %>

</talbe>

The order of elements in container becomes

All Apps

    ...

...

...

What confuses me is that only this page goes wrong. I am using Rails 4.0.5.

A: What is most probably happening is your browser HTML parser is trying to fix things, by putting elements "floating" in a table (without being in a tr>td) before the table. You probably have an unclosed tag.
(which is why it's vering important in cases like these to check the generated html and compare it to the browser's DOM panel - it can be very different !)