text:
Q: Retrive total quantity of ordered Items using SQL I am trying to get Quantity of an item that is requested and yet not received.
Process of purchasing and Item is as
Created Purchase Order > Ordered Items saved in ItemsRequested table
Created Purchase Invoice > Received Items are in ReceivedItems table
Using below query to get Items Requested quantity but the result is wrong. What is logically wrong in query ?
select Sum(ItemRequested.Quantity) as OnOrder from ItemRequested
Inner join PurchaseOrders on ItemRequested.PurchaseOrderId = PurchaseOrders.PurchaseOrderId
Inner join PurchaseInvoices on PurchaseInvoices.PurchaseOrderId = PurchaseOrders.PurchaseOrderId
inner join ItemReceived on ItemReceived.PurchaseInvoiceId = PurchaseInvoices.PurchaseInvoiceId
where PurchaseOrders.DateOrdered >'2019-04-15 11:37:26.537' and ItemRequested.ItemId=3439

A: The definition of the items you need is "requested but not yet received". So you have to retrieve the rows that are in ItemRequested but absent from ItemReceived.
Thus your query should be more like this
SELECT  SUM(ItemRequested.Quantity) AS OnOrder
FROM    ItemRequested
        INNER JOIN PurchaseOrders ON ItemRequested.PurchaseOrderId = PurchaseOrders.PurchaseOrderId
WHERE   PurchaseOrders.DateOrdered >'2019-04-15 11:37:26.537'
AND     ItemRequested.ItemId=3439
-- Exclude the PO having received items
AND NOT EXISTS (
    SELECT 1
    FROM PurchaseInvoices
        INNER JOIN ItemReceived ON ItemReceived.PurchaseInvoiceId = PurchaseInvoices.PurchaseInvoiceId
    WHERE PurchaseInvoices.PurchaseOrderId = PurchaseOrders.PurchaseOrderId
)


text:
Q: How to change max listeners from 32 to unlimited i installed shout cast on Ubuntu server .
First: i want to know how to change maximum number of listeners from 32 to unlimited.
Second : there is any app to stream to server from ubuntu.

A: Its impossible to set the amount of listeners to "Unlimited" but you can change it to whatever number you want to.
You can do this by going to your sc_serv.conf or whatever you named your config file and then editing the file and finding MaxUser=32 and change the number to whatever you want to.
If you need help setting up let me know by emailing me (lsmithx2 "@" fragfm.org.uk)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add facet_grid panel means as text and hline I have a dataframe that looks like this.
> head(df)
  DGene JGene cdr3_len Sum
1 IGHD1 IGHJ1        0  22
2 IGHD1 IGHJ1        1  11
3 IGHD1 IGHJ1        2  16
4 IGHD1 IGHJ1        3  40
5 IGHD1 IGHJ1        4  18
6 IGHD1 IGHJ1        5  30
...

It is pretty simple to facet_grid.
ggplot(df,aes(x=cdr3_len,y=Sum)) + geom_line() + xlim(c(1,42)) + facet_grid(JGene~DGene,scales="free_y")

and getting something that looks like.

I was wondering if anyone could help me with adding a hline to the mean of each grid. Or possibly how to print the mean of each grid in the top right corner.
Thanks,
Edit -
Full link to dataframe

A: Here's a way to add both text and a vertical line for the mean of cdr3_len by pre-computing the desired values (per @jwillis0720's comment):
First, calculate the mean of cdr3_len for each panel and then left_join that data frame to a second data frame that calculates the appropriate y-value for placing the text on each panel (because the appropriate y-value varies only by level of JGene).
library(dplyr)

meanData = df %>% group_by(JGene, DGene) %>%
  summarise(meanCDR = sum(Sum*cdr3_len)/sum(Sum)) %>%
  left_join(df %>% group_by(JGene) %>%
              summarise(ypos = 0.9*max(Sum)))

Now for the plot:
ggplot(df,aes(x=cdr3_len, y=Sum)) +
  geom_vline(data=meanData, aes(xintercept=meanCDR), colour="red", lty=3) +
  geom_line() +
  geom_text(data=meanData,
            aes(label=round(meanCDR,1), x=40, y=ypos), colour="red",
            hjust=1) +
  xlim(c(1,42)) +
  facet_grid(JGene~DGene,scales="free_y")


text:
Q: Is there open source or free software to use my touchpad as absolute touch? I'm running OS X Yosemite, and don't want to spend money on a Wacom tablet. Is there free software or code that can disable the acceleration of the touchpad so I can write effectively with a stylus?

A: I just found a app called Inklet.
I did not try it my self, but will consider it for any pen drawing work where the use of mouse or trackpad is difficult.
It does cost $20, but it might be worth, but there is a free demo version to try first.


text:
Q: create and loop through arrays of folders in shell Please feel free to rename the question to something more appropriate.
How would I mimic the below zsh using bash instead?
mkdir folder1
mkdir folder2
mkdir folder3

# zsh

folders=(folder*) | print $folders
#folder1 folder2 folder3

# bash

folders=(folder*/) | echo $folders
#folder1

As you can see, this only outputs the first element.
Any pointers would be appreciated, thanks.

A: Try changing it to:
folders=(folder*); echo "${folders[@]}"

*

*folders[@] gives all the elements in the array

*${} expands the output from above command to bash.

A: If lets say, you  have multiple .txt file  in some Directory and you want to get/display those folders . you can try something like this:
declare -a folder_arr
i=0

for dir in *.txt; do

folder_arr[i]=$dir
i=$((i+1))
done

for j in $(seq 0 $((i-1)))
do
echo ${folder_arr[$j]}
done

I excuted the above file and was able to get the expected reult.
   /temps$ ./dirrr.sh
    z.txt


text:
Q: Couchbase CLI refusing connection I'm trying to use couchbase's command line backup and restore commands (e.g., cbbackup and cbrestore) and when I type the following command:
cbbackup http://127.0.0.1:8891 ~/couch_backup -u [username] -p [password]

I consistently get a [Errno 61] Connection refused error.
I have validated that the username and password I'm using are the same as what I use to log into the web interface successfully. Should these two username/password combinations be the same? Can anyone think of any other reason why this wouldn't work?

A: Couchbase is usually listen on 8091 port, not 8891. So if you didn't change port manually try:
cbbackup http://127.0.0.1:8091 ~/couch_backup -u [username] -p [password]


text:
Q: UIImageView performance issue with generated image I'm having some problems with updating the image of an UIImageView. I use a base image, that I modify by drawing in it before displaying. When displaying without the "overlay", performance is fine. But when I generate the "overlay", it takes close to 10 seconds before the view is updated. The base image is a 640x430 PNG file. I don't see any spikes in CPU and / or memory usage when the image is supposed to display - so I'm not really sure why it's taking so long. If I change the image to some static image bundled in my app, it changes instantaneously. Am I doing anything obviously stupid here?
The code I use to generate the overlay looks like this:
func drawTextOverlay(textData:[String : [CGFloat]], sourceImage:UIImage)->UIImage {
    log.debug("Overlay generation started")

    UIGraphicsBeginImageContext(sourceImage.size);
    sourceImage.drawInRect(CGRectMake(0,0,sourceImage.size.width,sourceImage.size.height));

    for letter in textData {
        let toDraw = letter.0
        let pointX = letter.1[0]
        let pointY = (letter.1[1])

        let rect = CGRectMake(pointX, pointY, sourceImage.size.width, sourceImage.size.height)
        let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
        textStyle.alignment = NSTextAlignment.Left
        let textColor = UIColor.redColor()

        let font = UIFont.boldSystemFontOfSize(12);
        let textFontAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName: textStyle]

        toDraw.drawInRect(rect, withAttributes: textFontAttributes)
    }

    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    log.debug("Overlay generated")
    return newImage;
}

and it gets called like this:
self.imageView.image = self.drawOverlay(UIImage(named:"base_image")!)
self.imageView.setNeedsDisplay()

private func drawOverlay(image:UIImage)->UIImage {
    return graphicsService.drawTextOverlay(getKeys(), sourceImage: image)
}

Thanks!
EDIT:
Making sure to post the notification to the main thread like this did the trick:
dispatch_async(dispatch_get_main_queue(),{
    NSNotificationCenter.defaultCenter().postNotificationName("NotificationName", object: nil)
});

A:
it takes close to 10 seconds before the view is updated

Those words almost always mean that you are attempting to talk to the interface from a background thread. You must never do that.


text:
Q: How to obtain ag-grid changes in JavaScript? I'm trying to use ag-grid in an ASP.NET MVC application and I'm not using any framework in the client side.
The question is how to get the changes made in the grid to save the data in the database? As simple JavaScript array data?
I need something that return me the changed data like this:
added[1],     => {code:"", name: "newName"}
changed[1],   => {code:"01", name: "changedName"}
deleted[1]    => {code:"02", name: "toBeDeleted"}

Then, sending that to the server is easy, but once the server returns OK, how do I clean the changes flags?

A: you can use rowValueChanged or cellValueChanged for that.
https://www.ag-grid.com/javascript-grid-events/#editing
update data and use arrays to store references to updated, deleted or changed rows. On clicking save button anywhere in your app, you can get the rows and update in database.


text:
Q: Calculating the tensor product $\mathbb{Z}/n\mathbb{Z} \otimes_{\mathbb Z} \mathbb{Z}/n\mathbb{Z}$ Consider the $\mathbb{Z}$ module $\mathbb{Z}/n\mathbb{Z}$.
What is $\mathbb{Z}/n\mathbb{Z} \otimes_{\mathbb Z} \mathbb{Z}/n\mathbb{Z}$?

A: There are different solutions; however, I like this. Consider the following exact sequence:
$$\mathbb Z\xrightarrow{f} \mathbb Z\xrightarrow{g}\mathbb Z_n\xrightarrow{}0$$
where $g(a)=\overline{a}$ and $f(a)=na$. By tensor theorems, the sequence $$\mathbb Z\otimes \mathbb Z_n\xrightarrow{f\otimes id} \mathbb Z\otimes \mathbb Z_n \xrightarrow{g\otimes id}\mathbb Z_n\otimes \mathbb Z_n\xrightarrow{}0\otimes \mathbb Z_n$$ is exact too. Hence, $\frac{\mathbb Z\otimes \mathbb Z_n}{\rm{Im( f\otimes id)}}\cong \mathbb Z_n\otimes_{\mathbb Z} \mathbb Z_n$, but the definition of $f$ implies that $\rm{Im}(f\otimes id)=n(\mathbb Z\otimes\mathbb Z _n)$. Thus, we can conclude that $\frac{\mathbb Z\otimes \mathbb Z_n}{\rm{Im( f\otimes id)}}\cong \frac{\mathbb Z_n}{n\mathbb Z_n}\cong \mathbb Z_n$. By similar argument, you can show that $\mathbb Z_n\otimes_{\mathbb Z} \mathbb Z_m\cong\mathbb Z_{(m,n)}$


text:
Q: Caching ASP.NET users related data within WCF service My requirement is to call WCF web service from ASP.NET code behind and pass some data for example:
void Add(int x, int y);

Result of the operation should be somehow stored within WCF web service (member variable).
Later user should be able to call
double Equals();

and get the result of the operation. Of course since it's an open website many non-authenticated users can open the ASP.NET page and call the web service.
Alternatively Add method can return "key" that can be used to get result back, for example :
Guid Add(int x, int y);
double Equals(Guid key);

I don't think I can use WCF sessions since web service will think that there is only 1 client ( WebSite calling the webserivce hosted in IIS ).
Users are not authenticated - they are anonymous users.
I could use : ( please take a look at my EDIT )
InstanceContextMode =InstanceContextMode.Single

as attribute over my web service and store Dictionary<key, result> but the problem is when can I remove entry from Dictionary? Should I use some sort of BackgroundWorker to check dictionary every e.g. 15 minutes and remove old entries? In that case I would have to store DateTime against each entry but that's not a problem if this is the best way to implement this solution...
My example Add/Equals methods are only to illustrate the problem, real requirement need to store much more data per user than simple double result

Thanks in advance for all the help.
EDIT:
After thinking more about the InstanceContextMode =InstanceContextMode.Single I think it's not the best option to use with ASP.NET since if 100 users will call the web service at the same time I will get 100 sequential invocations which will cause performance issues.
In that case do you have any ideas how to implement this without changing InstanceContextMode setting (which by default is PerSession as far as I know) ?

A: I think,Keeping the
InstanceContextMode =InstanceContextMode.Single

as the service behavior, if your architecture permits, you can use the System.Web.Caching.Cache object implemented in a static class(so that it will be instantiated only once) ,where you can specify the cache dependency/expiration time etc and hence you can get the complete set of functionalities offered from the cache service, instead of implementing on your own.
Edit:
If your primary intention is about Caching, then you need not use the Instance Context mode even. You can simply implement your own static Cache provider based on the System.Web.Caching.Cache and pass the cacheKey as shown in the following sample:
 public int Add(int a, int b)
        {
            string cacheKey = a.ToString()+b.ToString();
            if (!CacheProvider.Contains(cacheKey))
            {
                CacheProvider.Add(cacheKey, a + b);
                return a + b;
            }
            else
            {
                return (int)CacheProvider.GetValue(cacheKey);
            }

        }

CacheProvider in the above code is the static implementation of your Cache provider.


text:
Q: Neo4j java unmanaged server extension not running I am trying to run the neo4j java unmanaged server extension example given below
https://github.com/neo4j-contrib/developer-resources/tree/gh-pages/language-guides/java/server-extension
i followed the readme and executed "mvn compile exec:java"..
but it looks like it is for JDBC driver.
my question is: How do i run the example server extension...?
./Zahoor

A: You need to compile the jar file using mvn package and drop the jar into your server's plugins folder. In conf/neo4j-server.conf set the following option:
org.neo4j.server.thirdparty_jaxrs_classes=example.extension.movies=/<mybaseurlpath>


text:
Q: unable to send logrus output /dev/null I'm using Logrus package for logging on my project.
All is fine but for testing purpose I do not need the logrus output to be displayed.
I looking at logrus.SetOuput for answer.
So basically I want the log to be written to /dev/null
But for some reason I still see the logs on STDOUT
   // This code run right at the start
   if env == "test" {
        fmt.Println("Entering test mode ....")
        logrus.SetOutput(ioutil.Discard)
        return
    }

Here how my logger setup looks like
// logger.go

package logger

import(
    "os"
    "io/ioutil"
    "github.com/Sirupsen/logrus"
)

var log *logrus.Logger

const (
    DEBUG   = 0
    INFO    = 1
    WARNING = 2
    ERROR   = 3
)

func init() {
    env := os.GetEnv("ENV")
    if env != "test" {
        return
    }
    logrus.SetOutput(ioutil.Discard)
}

func Init(logLevl int) {
    log = logrus.New()
    log.Formatter = &logrus.TextFormatter{FullTimestamp: true}
    switch logLevl {
    case DEBUG:
        log.Level = logrus.DebugLevel
    case INFO:
        log.Level = logrus.InfoLevel
    case WARNING:
        log.Level = logrus.WarnLevel
    case ERROR:
        log.Level = logrus.ErrorLevel
    }
}

func Get() *logrus.Logger {
    return log
}

func I(args ...interface{}) {
    log.Info(args)
}

func Df(format string, args ...interface{}) {
    log.Debugf(format, args)
}

func D(args ...interface{}) {
    log.Debug(args)
}

func W(args ...interface{}) {
    log.Warn(args)
}

And here how I use the logger package
import "logger"

func init() {
  logger.Init(0)
}

logger.D("Dummy string")

A: You're using two different logrus.Logger variables in your code. The first, which is called in init() is the global default Logger that gets exported from logrus. Later, in your custom initialization function Init(logLevel int), you're creating a new Logger via logrus.New() which is from then on used for logging — but hasn't been configured to use a different output.
I'd suggest to get rid of the init() function and do all the initialization in your Init(logLevel int) (please note the different API for setting the output).
func Init(logLevl int) {
    log = logrus.New()
    log.Formatter = &logrus.TextFormatter{FullTimestamp: true}
    switch logLevl {
    case DEBUG:
        log.Level = logrus.DebugLevel
    case INFO:
        log.Level = logrus.InfoLevel
    case WARNING:
        log.Level = logrus.WarnLevel
    case ERROR:
        log.Level = logrus.ErrorLevel
    }

    env := os.Getenv("ENV")
    if env != "test" {
        return
    }
    log.Out = ioutil.Discard
}


text:
Q: In Scala how can I advise my own methods? I want to do this:
trait Renderable {
    def render: String
}

trait Parens extends Renderable {
    abstract override def render = "(" + super.render + ")"
}

object Foo extends Renderable with Parens {
    def render = "Hello"
}

But this does not work because the linearization order puts Parens after Foo
(Foo always comes, of course) so Parens can't advise Foo.render.
I end up doing this:
trait FooRender {
    def render = "Hello"
}

object Foo extends FooRender with Parens {
}

But sometimes I really don't want to do that because it breaks things up. As
far as I can tell, linearization order is the only thing getting in the way,
but I don't know a way to change that. What might make this cleaner?

A: How about separating the presentation logic (render) and the actual contents (value)?
trait Renderable {
  def value : String
  def render = value // default presentation logic, simple rendering.
}

trait Parens extends Renderable {
  override def render :String = "(" + value + ")" // parens rendering.
}

object Foo extends Parens {
  def value = "Hello"
}

println(Foo.render) // prints '(Hello)'

Edit
Found a way you can do pretty much what you wanted, check it out:
trait Renderable {
  def render: String
}

trait Parens extends Renderable {
  abstract override def render = "(" + super.render + ")"
}

class Foo extends Renderable {
  def render = "Hello"
}

val foo = new Foo with Parens
println(foo.render)

You can't use an object since you need to implement the trait at creation time, but if you can control the instance creation then this might work :).
I'm pretty sure it's not possible to do it otherwise (someone please correct me if I'm wrong)


text:
Q: how to hide or secure the token when passing from javascript to web api 2 I'm using javascript (angularjs) on UI site/project and Web API 2 and other site/project
UI project: localhost/12345
Web API : localhost/98777
UI project is calling the Web API (C#) project passing the token from UI to WebAPI for CRUD requests.

I've generated the token in ServerSide project - WEB API2 (localhost/98777),  1- username / password
  2- then the url localhost:/98777/Token, passing username + password + token
wit this way it returns a token if you call it in fiddler: with content-type:
  application/x-www-form-urlencoded. Like this a token is generated and written to the localDB, later on this generated token can be use  in your UI app to call with javascript (ajax/angular) passing to WebAPI project.

I've implemented the bearer token calling the GET/POST/PUT methods in my client site.
localhost/12345 defined in Client site to get employee records via token:
----------------------------------------------
method: 'GET'
contenttype: 'application/json, charset=utf-8',
authorization: "Bearer 040jdU6ry....."
url: localhost/98777/api/employees/

this returns me the data all employees... it works.
localhost/98777 defined in server site web.config:
---------------------------------
<httpProtocol>
 <customHEaders>
   <remove name="Access-Control-Allow-Origin" />
   <add name="Access-Control-Alllow-Origin" value ="*"/>
 <customHeaders>
</httpProtocol>

PROBLEM?
The problem is people can do and open Developer tools in IE/Chrome/FF and see the sources of javascript and look at the token.
and then execute the code in Fiddler/ composer and add records :(.
so why do I need a token then ????
Can someone advice what part am I missing ? Is it normal that people can see the token?
This app will be used in intranet and used by developers, so I need to secure it maximum...

A:
Is it normal that people can see the token?

Yes, it is normal. As far as I know, the token just holds identity information, as well as some claims the client can not modify. That's the only thing it can be trusted for : Identity.
Server-side you have to check (roles/rights/business rules) that the user corresponding to the token's identity is entitled to perform the requested action.
Never rely on the business rules enforcement of your client-side UI. Always double check server-side and you will be safe.

A: You can think about following steps,

*

*Have a public key

*Encrypt the key using Time stamp

*Send the Encrypted key with the Time stamp in header

*Encrypt the key in the API with the same Time stamp

*Compare both keys.

*Check the Time stamp with the system time.


text:
Q: Is it possible to normalizr string? I am using normalizr. I try to normalize string, but I didn't figure out.
const mails = [
  {
    "id": "mailId1",
    "conversationId": "conversationId1",
    "content": "Hi",
    "sender": {
      "emailAddress": { name: 'Jack', address: 'jack@example.com' }
    }
  },
  {
    "id": "mailId2",
    "conversationId": "conversationId1",
    "content": "Hello",
    "sender": {
      "emailAddress": { name: 'Rose', address: 'rose@example.com' }
    }
  }
]

const userSchema = new schema.Entity('users', {}, {
  idAttribute: value => value.emailAddress.address
});
const conversationIdSchema = new schema.Entity('conversationIds', {}, {
  idAttribute: value => value
});
const mailSchema = new schema.Entity('mails', {
  conversationId: conversationIdSchema,
  sender: userSchema
});

const normalizedData = normalize(mails, [mailSchema]);

Right now the code above will give me the results below:
(note conversationIdSchema is not working because it is wrong)
{
  result: { mails: ['mailId1', 'mailId2'] },
  entities: {
    users: {
      'jack@example.com': { name: 'Jack', address: 'jack@example.com' }
      'rose@example.com': { name: 'Rose', address: 'rose@example.com' }
    },
    mails: {
      // ...
    }
  }
}

I hope to have conversationIds like this:
{
  result: { mails: ['mailId1', 'mailId2'] },
  entities: {
    users: {
      'jack@example.com': { name: 'Jack', address: 'jack@example.com' }
      'rose@example.com': { name: 'Rose', address: 'rose@example.com' }
    },
    mails: {
      // ...
    },
    conversationIds: ['conversationId1']
  }
}

A: No, this is not possible. Normalizr works on objects, not strings.


text:
Q: Compilation error option-unknown - can anyone help me? everyone.
I am trying to compile a file in Miktex but it shows this message:
! keyvalue error: "option-unknown"
!
! Unknown option 'vargreek-shape' for package unicode-math.
!
! See the keyvalue documentation for further information.
!
! For immediate help type H <return>.

Can you explain to me what it is and how to fix it?
Sorry i am completely new to latex and just found this website.

A: Sorry for my slightly misleading comment yesterday I deleted it and reposting a fixed version as an answer.
The error  means that you have
\usepackage[vargreek-shape]{unicode-math}

or
\usepackage[vargreek-shape=xxx]{unicode-math}

when there is no option of that name.
There Is an option listed in the manual (I'll ping the author to get that fixed) but the option was removed at the last release.
The change history available in README.md at at
https://www.ctan.org/pkg/unicode-math
says

*

*v0.8d (2017/01/25)

*

*vargreek-shape=TeX and vargreek-shape=unicode package options
  dropped; for consistency and compatibility, \phi and \epsilon
  should and will now behave the same as in `TeX

`.


text:
Q: Call for translation method on Moses as a service using xml-rpc fails I am facing an exception calling moses (Statistical Machine Translation) as a service with xmlrpc installed. I firstly open a port to the Moses server
--Listening on port 8082

but the main problem is when I send a rest request with an xml as body parameter.
<methodCall>
<methodName>translate</methodName>
<params>
<param>
<value>
<array>
<data>
<value>
<array>
<data>
<value>
<string>struct</string>
</value>
<value>
<string>struct</string>
</value>
</data>
</array>
</value>
</data>
</array>
</value>
</param>
</params>
</methodCall>

When I execute it as a POST request on http://xxx.xxx.xxx.xxx:8082/RPC2
I notice that service on port fails with exception "terminate called after throwing an instance of 'xmlrpc_c::fault'
Aborted
"
I think the main problem is with xml body structure but I cannot find any documentation on the web for translate method. Any suggestions? Thank you.
UPDATE
Note that if I open a port with setting
--threads all

I never get response back.

A: A working approach but may not the most clean and safe, is calling a python client from c# or java since does not exists library on nuget for doing this work.
ProcessStartInfo start = new ProcessStartInfo();

            start.FileName = "C:\\python\\python.exe";

            start.Arguments = $"C:\\python27\\client.py {word}";

            start.UseShellExecute = false; // Do not use OS shell

            start.CreateNoWindow = true; // We don't need new window

            start.RedirectStandardOutput = true; // Any output, generated by application will be redirected back

            start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)

            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script

                    string output = process.StandardOutput.ReadToEnd();

                    string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
                }
            }

and client is something like that client.py


text:
Q: Is it safe to measure 220Vrms@50Hz on DSO directly? I borrowed my friend's DSO to complete my project(Hantek DSO5072), but on scope it says CAT II/400V. So is it safe to measure 220Vrms@50Hz with it?

A: I see several "scary" elements in your question.
This isn't your DSO, you should use it only to measure "safe" (low voltage) things. When in doubt: only things that are battery powered.
CAT II/400V says something about what the oscilloscope can handle at its inputs. It doesn't tell you anything about your safety.
Also: Why would you need to measure mains voltage?
If that really is your goal, measure the output of a power adapter that outputs a low value AC voltage (so not DC) of 15 V AC for example. These are rare nowadays but were more common 20 years ago.
The issue is that the oscilloscope has inputs that are grounded on one side. Grounded meaning connected to Earth, assuming it is connected to the mains properly, so using a cable with Earth and using a proper Earthed socket. If you then would "measure the mains" there's a large chance that you will get a big spark when you connect the scope. And if you're lucky the Ground Fault detection (if that is present in your house and working) will switch off the mains power.
If you're unlucky you can connect the mains to the scope and then your scope could be mains live meaning you will get an electric shock when you touch it.
You should watch EEVBlog Dave Jones' video on this subject: How NOT To Blow Up Your Oscilloscope
After your added comment: you might need a high voltage probe specifically designed for these kinds of measurements. Most of these are quite expensive, often more than the listed price of your friend's scope.

A: Generally, no, especially if you don't have a good ground setup or don't understand about mains wiring (such as the difference between ground and neutral for example) and general knowledge of line voltage safety.
220V AC is actually over 600V peak-to-peak (+/- 311V), pretty close to the limit of your friend's scope. Your line voltage may actually be 230V, and maybe even higher than that, say by 10%, so as high as 253Vrms. That's 358V peak!
At that voltage all it would take is a spike from some other source, like a switch opening to a motor, light ballast, or some other inductive load to fry the scope input.
Then there's the question of grounding. The scope probe ground is the scope frame ground. If you just connect it across the line you have a 50-50 chance of connecting line voltage to ground- popping the breaker if you're lucky, but certainly doing bad things to the scope. How do you know? That business about neutral and ground I mentioned earlier: you need to understand this.
TL; DR version: no, it's not safe.


text:
Q: VBA Macro to print Columns A-J and every 40 rows I am very new to VBA Macros. I am trying to create a Macro that will set the print area for columns A-J and every 40 rows. The number of total rows will change for every worksheet but the columns will remain the same.
So far I've only been able to get the first page to print properly. This is what I have so far.
--
Sub formatSheets()

 For i = 40 To 1350 Step 40
    ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=Cells(i + 1, 1)

Range("A1:J1350").Select

Next
End Sub

--
Thank you so much for your help.
-Mary

A: I would reset all the page-breaks and set the print area for each sheet before adding the new page-breaks.
Sub formatSheets()
    Dim ws As Worksheet
    For Each ws In ActiveWindow.SelectedSheets
        ws.PageSetup.PrintArea = Intersect(.Columns("A:J"), .UsedRange)
        ws.ResetAllPageBreaks
    End With

    With ActiveWindow.SelectedSheets

        For i = 40 To 1350 Step 40
           .HPageBreaks.Add Before:=Cells(i + 1, 1)
        Next
    End With
End Sub


text:
Q: How to sort spring data jpa repository on character varying column Hi we are using postgress database and spring data jpa repository in java to use the data. Now we have one column (version) of type "character varying (255)" and column have data as val1 = 11.0.2000.78 and val2 = 11.0.2000.301
when we fire sort descending query using spring data jpa repository it lists value val1 above the val2. Actually it should list val2 above the val1.
We understand that since column is of type character it is considering 7 greater than 3 so is the issue. Any solution for this ?
We want numeric sort on the column of type character on such values. Is there any way to handle in spring data jpa repository ?

A: CREATE TABLE tableone
(
    test text
) ;

INSERT INTO tableone(test) VALUES('11.0.2000.78');
INSERT INTO tableone(test) VALUES('11.0.2000.301');

select * from tableone order by test desc;

SELECT
   test
FROM
    tableone order by
    ( CAST(
        COALESCE(
            NULLIF(
                replace(test, '.', ''),
                ''),
            '0')
       AS numeric) ) desc;


text:
Q: Should the outcome variable be measured at least twice for a longitudinal study? I am trying to find the association between BMI and onset age of a condition with linear regression model. I have multiple records of BMI measurement. But the outcome variable, onset age of condition, obviously, only once.
It seems  outcome variable should be measured at least twice for a longitudinal study.
Is this correct? If yes, then how do I make use of this multiple BMI observation in my linear regression model?

A: Is the BMI measured before or after the onset of the condition?
If it is measured before the onset you could use survival analysis. These models often allow you to introduce time varying covariates.
If they are measured after the onset, you will have to ask yourself how you think some future event will affect the condition now. In that case I would use the BMI closest to the event onset and consider that an (imperfect) proxy for the BMI at the onset of the condition.

A: The first thing I would do is make some graphs of BMI over time per person and color them as to whether they were pre-onset or post-onset.
Then I'd think about whether the trend in BMI pre-onset is an interesting predictor. If it is, there are some methods that allow time varying covariates that are not regular; or, you could try some sort of cluster analysis (either formal or not) on the trends and then see if those were related to onset.
Survival analysis - time to event - may be more powerful than methods that simply look at onset vs. not (logistic regression). It may also be a more interesting question, substantively


text:
Q: Splitting string causing Value of type 'Any?' has no member 'components' I have a function using webview IOS with swift 4. I am trying to explode result, but I am getting Value of type 'Any?' has no member 'components' and I have no idea how to fix this. I am new to swift.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.webView.evaluateJavaScript("document.getElementById('user_id').innerText") { (result, error) in
        if result != nil {
            let items = result.components(separatedBy: "|")
            self.ref?.child("people").child(result as! String).setValue(["device_token": self.deviceTokenStringfinal])
        }
    }
}

A: Because result can be anything: a string, a number, an array, a JSON object... depending on what your Javascript returns. Swift has no way of knowing that at compile time so it marks result as Any.
You must do a cast at runtime:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.webView.evaluateJavaScript("document.getElementById('user_id').innerText") { (result, error) in
        guard let result = result as? String else { return }

        let items = result.components(separatedBy: "|")
        self.ref?.child("people").child(result).setValue(["device_token": self.deviceTokenStringfinal])
    }
}


text:
Q: Private member of a Static Nested Class in Java Could someone please explain how private members of a static nested class are accessible outside the class?
class Main {
    static class Inner{
        private static int calc= 10;
    }

    public static void main(String args[]){
        System.out.println("calc is "+Main.Inner.calc);
    }
}

A: The inner class is just a way to cleanly separate some functionality that really belongs to the original outer class.
The inner class is (for purposes of access control) considered to be part of the containing class. This means full access to all privates.
The way this is implemented is using synthetic package-protected methods: The inner class will be compiled to a separate class in the same package. The JVM does not support this level of isolation directly, so that at the bytecode-level  will have package-protected methods that the outer class uses to get to the private methods/fields.
If you like to hide the private members of your inner class, you may define an Interface with the public members and create an anonymous inner class that implements this interface.


text:
Q: How to create a new service in MEAN stack framework? I have a service named user.service.js which is used for getting the users data from the users collection. The same way I need a service called courses.service.js which is going to read all the data from the courses collection. Can someone please show me how to do that?

A: Just add your module name and save file , change api url if needed
    (function () {
  'use strict';

  // Users service used for communicating with the plants REST endpoint
  angular
  //.module('coursesServices.admin.services')
  .factory('coursesService', coursesService);

  coursesService.$inject = ['$resource'];

  function coursesService($resource) {

    var courses = $resource('/api/courses/:courseId', {
      plantId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });

    return courses;
  }

}());


text:
Q: I get this error message "A data base error has occured. " Bitbucket i am new to bitbucket and when i try to create a new repository or project or user etc, i get this error.
I use Atlassian Bitbucket v7.3.0
I have found another post that has probably a similar problem.
https://community.atlassian.com/t5/Bitbucket-questions/Cannot-create-a-repository-Getting-Database-Error/qaq-p/1906892#U2067135
After i do some search i have found this with event tracer of the SQL Server.
How can i solve below error which i get from it?
"Could not connect because the maximum number of '1' dedicated administrator connections already exists. Before a new connection can be made, the existing dedicated administrator connection must be dropped, either by logging off or ending the process."
I believe that probably this is the error that i must fix to solve the "database error has occured."
Thanks in advance.


text:
Q: How to find the distance of two lists? I have two lists as the following:
ab = {1, -1, -1, -1, 1, 1};
ac = {1, -1, -1,  1, 1, 1};

How I can find the difference (more precisely, the edit distance) between them? In this case the result should be 1, since there is one item difference between ab and ac.
Note: in my case, the list elements only take the values 1 and -1, and both lists are one-dimensional of the same length, but it is always nice to see more general solutions (elements are of Reals, lists are matrices, etc.).
Thank you.

A: You could do this
ab = {1, -1, -1, -1, 1, 1};
ac = {1, -1, -1, 1, 1, 1};

EditDistance[ab, ac]

which would give a result even if the lists had different lengths (or whatever).
The documentation says:

EditDistance[u, v] gives the number of one-element deletions, insertions, and substitutions required to transform u to v.

A: A very basic approach:
Count[Equal @@@ Thread[{ab, ac}], False]

1

or perhaps:
Count[MapThread[Equal, {ab, ac}], False]

1

Now if there is only 1 and -1 to watch out for, this will also do (thanks to Aky for pointing out a glaring error):
Plus @@ Abs[ab - ac]/2

A: These results are specific to the case where the data are 1|-1, and may be specific to v6.
<<Developer`
n = 10^7
PackedArrayQ[ a = RandomInteger[1,n]*2 - 1 ]
PackedArrayQ[ b = RandomInteger[1,n]*2 - 1 ]
(* 10000000
   True
   True *)

AbsoluteTiming[ (Length@a - a.b)/2  ]
(* {0.435134, 4998582} *)

AbsoluteTiming[ Tr@Unitize@Subtract[a,b] ]
(* {0.792662, 4998582} *)

AbsoluteTiming[ Tr@Unitize@BitXor[a,b] ]
(* {0.883002, 4998582} *)

aa = FromPackedArray@a;
bb = FromPackedArray@b;

AbsoluteTiming[ (Length@aa - aa.bb)/2  ]
(* {1.373384, 4998582} *)

AbsoluteTiming[ Tr@Unitize@Subtract[aa,bb] ]
(* {1.366143, 4998582} *)

AbsoluteTiming[ Tr@Unitize@BitXor[aa,bb] ]
(* {2.590419, 4998582} *)

A: I will abuse the fact that OP hasn't said if it is more general question.
This is my solution fo 1/-1 data case:
Count[ab ac, -1]

A: There is an appropriate metrics:
HammingDistance[ab, ac]

1

one could use also (but in general it yields different results since it counts transpositions, deletions etc.)
DamerauLevenshteinDistance[ab, ac]

1

A: For Integer data we also could write:
 Tr @ Unitize @ BitXor[ab, ac]

1

For Real data we can use the slightly slower but also shorter:
Tr @ Unitize[ab - ac]

Blackbird challenged me to provide a method that works on all input types.  My approach is to select between methods depending on data.
diff[a__?(VectorQ[#, IntegerQ] &)] := Tr @ Unitize @ BitXor @ a
diff[a__?(VectorQ[#, NumericQ] &)] := Tr @ Unitize @ Subtract @ a
diff[a_, b_] := HammingDistance[a, b]

Timings for some of the methods posted so far (search the site for timeAvg):
{ab, ac} = List @@ RandomInteger[2, {2, 250000}];  (* List @@ to prevent unpacking *)

HammingDistance[ab, ac]                  // timeAvg
Count[MapThread[Equal, {ab, ac}], False] // timeAvg
Tr @ Unitize @ BitXor[ab, ac]            // timeAvg
diff[ab, ac]                             // timeAvg

0.009984
0.05428
0.0005488
0.0005744

Now with Real data:
{ab, ac} = N /@ {ab, ac};

HammingDistance[ab, ac]                  // timeAvg
Count[MapThread[Equal, {ab, ac}], False] // timeAvg
Tr @ Unitize[ab - ac]                    // timeAvg
diff[ab, ac]                             // timeAvg

0.01872
0.0748
0.00312
0.0021728

(I learned something from this test: Subtract[a,b] is faster than a-b on packed reals.)
Now something unpackable:
{ab, ac} = RandomChoice[CharacterRange["a", "z"], {2, 250000}];

HammingDistance[ab, ac]                  // timeAvg
Count[MapThread[Equal, {ab, ac}], False] // timeAvg
diff[ab, ac]                             // timeAvg

0.005488
0.0524
0.005496


text:
Q: Why using pdf we get better results than using dvi? In How can I auto adjust a equation to appear in the entire page? (Scale to equations, is this exist?) I asked how I could change the equation sizes.
Nothing seemed to work. But the problem was I was using latex (Kile) and seeing the the results in dvi. When I used pdflatex as @Hooked proposed I got good results in the pdf.
Why? Why I can't use dvi? Or if I can use dvi, how to do this?
The code below generated this (using latex and dvi):

when the correct is this(possible using pdflatex).):

\documentclass[landscape, 12pt]{report}
\usepackage{graphicx}
\pagestyle{empty}

\begin{document}
\noindent Here is some text
\begin{equation}
\resizebox{1.0 \textwidth}{!}
{
   $ a + b $
}
\end{equation}
and here is some more.
\end{document}

A: I think it is a problem of your DVI-viewer. Perhaps the font problem.
I tried your code with LaTeX, and the dvi-file look quiet similar to your pdf-example (the text inside the resizebox looks is a bit grainy).
I converted the dvi with dvipdfmx (dvi can't be imported here), the result is:
2011-11-21 Edit: Uploaded cropped image


text:
Q: Шкала Scale и её параметры Может кто-нибудь объяснить за что отвечает каждая строчка кода шкалы, как её использовать и как написать её минимумом кода.
Вот код найденный на pythonworld.ru, так ничего и не объяснил.
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        scale = Scale(self, from_=0, to=100,
            command=self.onScale)
        scale.pack(side=LEFT, padx=15)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack(side=LEFT)

    def onScale(self, val):
        v = int(float(val))
        self.var.set(v)

def main():
    root = Tk()
    ex = Example(root)
    root.geometry("250x100+300+300")
    root.mainloop()

if __name__ == '__main__':
    main()

A: Действительно минимальный пример (который ничего не делает, только создает ползунок в окне):
import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()

scale = ttk.Scale(root)
scale.pack()

root.mainloop()

Печать значения в консоль при перемещении движка:
import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()

def on_scroll(val):
    print(val)

scale = ttk.Scale(root, from_=0, to=100, command=on_scroll)
scale.pack()

root.mainloop()

Получение значения в произвольный момент (при нажатии кнопки) через привязанную переменную:
import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()

scale_var = tk.IntVar()
scale = ttk.Scale(root, from_=0, to=100, variable=scale_var)
scale.pack()

def on_button_press():
    print(scale_var.get())

button = ttk.Button(text="Press me", command=on_button_press)
button.pack()

root.mainloop()


text:
Q: How to selectively enable or disable SSL for some URLs in Tomcat 7 I am using SSL in Tomcat 7, create a keystore and configure server.xml, and also config in web.xml as below
<security-constraint>
         <!-- SSL enforced -->
        <web-resource-collection>
            <web-resource-name>SSL</web-resource-name>
            <url-pattern>/inspectionGp/*</url-pattern>
            <url-pattern>/inspection/*</url-pattern>
            <url-pattern>/inspGpDt/*</url-pattern>
            <url-pattern>/inspDt/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
</security-constraint>

That works for SSL, these restricted URLs are forced to use only SSL, but other URLs can also use both HTTP and HTTPS, it's strange, I don't want use HTTPS for the URLs which are not configured in <url-pattern>. I use  <transport-guarantee>NONE</transport-guarantee>, that will result in all URLs support both HTTP and HTPPS. So can anybody help explain how I can resolve it?

A: Definitely consider using SSL for everything.  Many of our clients are going this direction and I recommend it fully.
If you mix HTTP/HTTPS and want to maintain session state, you'll have to circumvent some of the mechanisms in Tomcat that try to prevent this (secure-only cookies for JSESSIONID).  Once you successfully do that, then somebody could possibly hijack a session from the HTTP and take actions on the HTTPS side.
All that said, if you want to have this level of fine-grained control, you could consider using a ServletFilter.  The filter could be applied first in the web.xml and be applied to the "REQUEST" dispatcher on the "/*" URL pattern (or just patterns where you need to make this determination).
The filter would then look at the request.  If it is a path that must be HTTPS it would check the request.isSecure().  If not secure it would issue a 301 redirect to the HTTPS side of things, making sure to maintain the full request path and any URL parameters.  Likewise to redirect from HTTPS over to HTTP.
I am passionately in love with servlet filters.  They are the Swiss Army Knife of request handling.  There is nothing you cannot do.  Most importantly, the behavior is part of the app and not a customization to the Tomcat setup.  You can deploy the app anywhere and it'll "just work".


text:
Q: json with array I am trying to create a dict like this:
{
  "Name": "string",
  "Info": [
    {
      "MainID": "00000000-0000-0000-0000-000000000000",
      "Values": [
        {
          "IndvidualID": "00000000-0000-0000-0000-000000000000",
          "Result": "string"
        },
        {
          "IndvidualID": "00000000-0000-0000-0000-000000000000",
          "Result": "string"
        }
    ]
    }
  ]
}

Where the Values section has 100+ things inside of it. I put 2 as an example.
Unsure how to build this dynamically. Code I have attempted so far:
count = 0
with open('myTextFile.txt') as f:
        line = f.readline()
        line = line.rstrip()
        myValues[count]["IndvidualID"] = count
        myValues[count]["Result"] = line
        count = count +1

data = {"Name": "Demo",
       "Info": [{
          "MainID":TEST_SUITE_ID,
          "Values":myValues
       }}

This does not work however. Due to "Key Error 0" it says. Works if I do it like  myValues[count]= count but as soon as I add the extra layer it breaks  myValues[count]["IndvidualID"] = count.   I see some example of setting a list in there, but I need like a List (Values) with multiple things inside (ID and Result). Have tried a few things with no luck. Anyone have a simple way to do this in python?
Full traceback:

Traceback (most recent call last):
  File "testExtractor.py", line 28, in <module>
    myValues[count]["IndvidualID"] = count
KeyError: 0

A: If I add a few bits and pieces I can get this code to run:
count = 0
myValues = []
with open('myTextFile.txt') as f:
    for line in f:
        line = line.rstrip()
        d = {"IndvidualID":count, "Result":line}
        myValues.append(d)
        count = count + 1

TEST_SUITE_ID = 1
data = {"Name": "Demo",
       "Info": [{
          "MainID":TEST_SUITE_ID,
          "Values":myValues
       }]}

Output:
{'Name': 'Demo', 'Info': [{'MainID': 1,
      'Values': [{'IndvidualID': 0, 'Result': 'apples'}, {'IndvidualID': 1, 'Result': 'another apples'}]
}]}

Note:
I have defined myValues as an empty list. I iterate over the file to read all lines and I create a new dict for each line, appending to myValues each time. Finally I create the whole data object with myValues embedded inside.
To get the above output I actually substituted: f = ['apples','another apples'] for the open file, but I'm sure an actual file would work.


text:
Q: Установка Realplexor-а Использую инструкцию из примера:
cd /opt
wget http://github.com/DmitryKoterov/dklab_realplexor/tarball/master
tar zxf *realplexor*.tar.gz
mv *realplexor*/ dklab_realplexor
# Now deal with an init-script.
ln -s /opt/dklab_realplexor/dklab_realplexor.init /etc/init.d/dklab_realplexor
chkconfig --add dklab_realplexor
chkconfig dklab_realplexor on
service dklab_realplexor start

Дохожу до шага chkconfig --add dklab_realplexor и получаю сообщение об ошибке:
[dklab_realplexor]# chkconfig dklab_realplexor on
error reading information on service dklab_realplexor: No such file or directory

Проверка на:
yum install chkconfig

дает результат:
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
Setting up Install Process
Package chkconfig-1.3.49.3-2.el6_4.1.x86_64 already installed and latest version
Nothing to do

Система: CentOS 6.4
Файл /etc/init.d/dklab_realplexor есть - но пустой. Открыл так:
vim /etc/init.d/dklab_realplexor`

A: команда wget http://github.com/DmitryKoterov/dklab_realplexor/tarball/master сохранит в текущем каталоге файл под именем master, соответственно, следующая за ней команда распаковки архива tar ... ничего не распакует — она не найдёт файла, подпадающего под шаблон *realplexor*.tar.gz.
необходимо сделать что-нибудь одно из:

*

*либо после скачивания переименовать файл master в, например, realplexor.tar.gz:
$ mv master realplexor.tar.gz

*либо добавить команде wget ... параметр --content-disposition, и тогда файл сразу получит имя DmitryKoterov-dklab_realplexor-v1.41-7-g01281d4.tar.gz (или что-то в этом роде).

*либо распаковывать файл master не приведённой командой tar ..., а, например, так:
$ cat master | gunzip | tar -x

после чего можно продолжать следовать инструкции.


text:
Q: Split lists by punctuation before writing as columns text file Say I have two lists with two initial elements:
  a = [Mango, Orange]

and
  b = [Max - Trom - Tyre | Men, Peter - Min - Mike | Doug]

I want to have an output of several columns that looks like:
 Mango    Max    Trom  Tyre
 Orange   Peter  Min   Mike

In other words, I want to transpose the lists first into two columns and then do the following:

*

*Split the second list by '-' into several columns

*Remove any text after '|' in the second list
I saw this post Python: Write two lists into two column text file but this only enabled me to transpose the  lists and not to split the list elements into several columns

A: This might help.
Demo:
a = ["Mango", "Orange"]
b = ["Max - Trom - Tyre | Men", "Peter - Min - Mike | Doug"]

for i, v in zip(a, b):            #Iterate Both List
    v = v.split("|")[0]           #Split by "|" and access first element
    print([i] + v.split(" - "))   #Form required output.

Output:
['Mango', 'Max', 'Trom', 'Tyre ']
['Orange', 'Peter', 'Min', 'Mike ']

A: use below code:
a = ['Mango' , 'Orange']
b = ['Max - Trom - Tyre | Men' , 'Peter - Min - Mike | Doug']
c=list()
d=list()
for i in range(len(a)):
    d=[]
    d.append(a[i])
    b1=b[i].split("|")[0]
    for k in b1.split("-"):
        d.append(k)

    c.append(d)
    print(c)

A: a = ["Mango", "Orange"]
b = ["Max - Trom - Tyre | Men", "Peter - Min - Mike | Doug"]

def combine_name(key, value):
   return  [key] + [name.strip() for name in value.split("|")[0].split('-')]

print list(map(combine_name, a, b))

>>>[['Mango', 'Max', 'Trom', 'Tyre'],
    ['Orange', 'Peter', 'Min', 'Mike']]


text:
Q: UK geojson displays blank folium map I'm trying to use the following geojson for UK local authorities, but it displays a blank map.
<https://martinjc.github.io/UK-GeoJSON/json/eng/topo_lad.json -O UK_counties.json>
My table lists most of the local authorities in the same way. Not sure if its the key_on reference that's the only problem or if there's more to it.
My code so far is below:
threshold_scale = np.linspace(df_ctbl['Population'].min(), df_ctbl['Population'].max(), 6, dtype=int)

threshold_scale = threshold_scale.tolist() # change the numpy array to a list
threshold_scale[-1] = threshold_scale[-1] + 1 # make sure that the last value of the list is greater than the maximum immigration

# let Folium determine the scale.
londonf_map = folium.Map(location=[latitudeld, longitudeld], zoom_start=4, tiles='Mapbox Bright')
londonf_map.choropleth(
    geo_data=uk_geo,
    data=df_ctbl,
    columns=['Local Authorityp', 'Population'],
    key_on= 'properties.lad13nm',
    threshold_scale=threshold_scale,
    fill_color='YlOrRd',
    fill_opacity=0.7,
    line_opacity=0.2,
    legend_name='UK Population in 2019',
    reset=True
)
londonf_map

Can anyone help? Thanks

A: You can have a look at this answer : question about Mapbox bright. I think you have a problem with the tiles name "Mapbox Bright".


text:
Q: How to connect to GCP in go using cloud.google.com/go/storage library with aksk? I am writing an application that fetches various metadata from GCP buckets and objects for analytical purposes.
I came across the cloud.google.com/go/storage  library in the post below
https://cloud.google.com/storage/docs/listing-objects#client-libraries
I am currently trying to connect to GCP with cloud.google.com/go/storage using access-key,secret-key (aksk)
endpoint := option.WithEndpoint("https://storage.googleapis.com")
//create client option from aksk
client, err := storage.NewClient(ctx, endpoint)
if err != nil {
   return nil, fmt.Errorf("storage.NewClient: %v", err)
}

I am not able to find any ClientOption which accepts aksk.
PS: I don't want to use any other modes of authentication as it will break the existing architecture


text:
Q: How to select records greater than max timestamp stored in a file from previous load from table in Pandas I have SQL script from which I am extracting data storing into a data frame.
Current Code
cursor.execute("""
    SELECT * FROM ofs.ord_add oa
            WHERE
            oa.is_active = 'Y' AND   oa.or_ad_id = 5820  AND   oa.flag_value = 'Y'
    """)
    data3=cursor.fetchall()
    columns = [column[0] for column in cursor.description]
    order_addition = pd.DataFrame(data3,columns=columns)

** Current Output- Run1**
ID     IS_ACTIVE   OR_AD_ID   FLAG_VALUE   INSERT TIMESTAMP
12300     Y          5820        Y         2020-01-06 08:12:53
14340     Y          5820        Y         2020-01-19 06:11:53

** Current Output-Run2**
ID     IS_ACTIVE   OR_AD_ID   FLAG_VALUE   INSERT TIMESTAMP
12300     Y          5820        Y         2020-01-06 08:12:53
14340     Y          5820        Y         2020-01-19 06:11:53
22368     Y          5820        Y         2020-01-22 08:12:53
34567     Y          5820        Y         2020-01-24 06:11:53

I am want use a condition in my current code such that :
1) max insert timestamp from the last run is stored in a file
2) In the next run of the SQL query, Only records greater than max timestamp stored in the file is
   loaded into the dataframe.
Expected Output after Run2
  ID     IS_ACTIVE   OR_AD_ID   FLAG_VALUE   INSERT TIMESTAMP
  22368     Y          5820        Y         2020-01-22 08:12:53
  34567     Y          5820        Y         2020-01-24 06:11:53

How can this be done in python ?

A: First, create a variable from the very first run:
unique_ids = tuple(dataframe.IDs.unique.tolist())

Then you execute the sql query the next time
cursor.execute("""
     SELECT * FROM ofs.ord_add oa
              WHERE
             oa.is_active = 'Y' AND   oa.or_ad_id = 5820  AND   oa.flag_value = 'Y'
             AND oa.ID NOT IN %(unique_ids)s;
"""
({'unique_ids':unique_ids})
)

do test the variable place holding ... i may have bungled it in this code. But the whole idea is that before u run the query again, get the variable then pass it on to the query. https://www.psycopg.org/docs/usage.html has a guide on how to pass variables in. love to get your feedback if it works or not


text:
Q: In triangle $ABC$, $\angle C = 48^\circ$. $D$ is any point on $BC$, such that $\angle CAD = 18^\circ$ and $AC = BD$. Find $\angle ABD.$ In  triangle $ABC$, $\angle C = 48^\circ$. $D$ is any point on $BC$, such that $\angle CAD = 18^\circ$ and $AC = BD$. Find $\angle ABD.$
I tried to make some constructions: draw a line through $D$ parallel to $AC$; draw a line through $C$ which makes $66$ degrees with $AC$. None of them have been useful. It feels like I am trying to force the formation of congruent triangles, and that doesn't work. Please help.

A: Draw in black the triangle $ABC$ with angle $48^\circ$ at $C$, and $AD$ with angle $18^\circ$ at $A$. This ensures the blue angles $114^\circ$ and $66^\circ$. Choose $D'\in BC$ such that  $|D'C|=|BD|=|AC|$. This gives the red angles $66^\circ$ and $66^\circ-18^\circ=48^\circ$. This implies that $|AD'|=|AD|$. The triangles $AD'C$ and $ADB$ are therefore SAS-congruent with the same angles at $D'$ and $D$. This shows that the green angle $\angle ABD=48^\circ$.

A: Let $E$ be a point such $ED=AD$ and $EB=CD$ and that $A, E$ lie on the same side of line $BC$. Then $\triangle DEB \equiv \triangle ADC$ so $\angle BDE = \angle CAD$ and therefore
$$\angle EDA = \angle BDA - \angle BDE = \angle DCA + \angle CAD - \angle BDE = \angle DCA = 48^\circ.$$
Since $ED=AD$, we have $$\angle AED = 90^\circ - \frac 12 \angle EDA = 90^\circ - \frac 12 \cdot 48^\circ = 66^\circ.$$
But also $\angle DEB = \angle ADC = 180^\circ - 48^\circ - 18^\circ = 114^\circ$. Hence $\angle AED + \angle DEB = 180^\circ$ and therefore $E$ lies on $AB$. It follows that
$$\angle ABD = \angle EBD = \angle DCA = 48^\circ.$$

Special thanks to Calum Gilhooley for providing a picture.

A: One way to solve it would be using sine rule. In ACD, we have
$$\frac{\sin 114}{AC} = \frac{\sin 48}{AD}$$
In triangle ABD, we have
$$\frac{\sin(114-B)}{BD} = \frac{\sin B}{AD}$$
If you solve these equations, using AC=BD, we have
$$\tan B = \frac{\sin 48}{1+\cot 114\cdot\sin48}$$
$$\implies \tan B = 1.1107$$
Hence $B = 48^0$

A: Let $\measuredangle ABC=x$. Then $\measuredangle BAD=114^\circ-x$. By sine theorem we have:
$$
BD\stackrel{\triangle BAD}=AD\frac{\sin(114^\circ-x)}{\sin x}
\stackrel{\triangle CAD}=AC\frac{\sin 48^\circ}{\sin 114^\circ}\frac{\sin(114^\circ-x)}{\sin x}\\
\implies \frac{\sin 48^\circ}{\sin 114^\circ}\frac{\sin(114^\circ-x)}{\sin x}=1
\implies \frac{\sin x}{\sin(114^\circ-x)}=\frac{\sin 48^\circ}{\sin 66^\circ}
\implies x=48^\circ.
$$

A: Ok, here's my method, it's VERY confusing and messy, so there's probably a better method.
Using the sine rule: $$\frac{AC}{\sin114}=\frac{AD}{\sin 48}$$
so $$AC=BD=\frac{AD\sin114}{\sin48}$$
Cosine rule: $$AB^2=AD^2+\frac{AD^2\sin^2 114}{\sin^2 48}-2\frac{AD^2\sin 114\cos 66}{\sin 48}=AD^2 (1+\frac{\sin^2 114}{\sin^2 48}-2\frac{\sin 114\cos 66}{\sin 48})$$
So $$AB=AD \sqrt{1+\frac{\sin^2 114}{\sin^2 48}-2\frac{\sin 114\cos 66}{\sin 48}}$$
Sine rule (again): $$\frac{AB}{\sin66}=\frac{AD}{\sin ABD}$$
so $$\frac{AD \sqrt{1+\frac{\sin^2 114}{\sin^2 48}-2\frac{\sin 114\cos 66}{\sin 48}}}{\sin66}=\frac{AD}{\sin ABD}$$
Cancelling $AD$ from both ides and rearranging to find $ABC$ should get you your answer. I hope that helped! (It'd probably help to draw a sketch.)


text:
Q: POSTMAN. Некорректная работа скрипта при корректном ответе Я написал скрипт который запускает внутри запроса сразу еще 1 запрос:
pm.sendRequest('111', (error, response) => {
  if (error) {
    console.log(error);
  } else {
  console.log(response);
  }
});

const postRequest = {
  url:  pm.environment.get("url"),
      method: 'POST',
      header: {
        'Accept': '*/*',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: {
          mode: 'urlencoded',
          urlencoded: [
            {key: "code", value: "CMS.CHECK_TOKEN", disabled: false},
            {key: "token", value: pm.environment.get('token'), disabled: false},
            {key: 'params', value: "{\"token\": \""+pm.environment.get('token')+"\"}" , disabled: false}

        ]
      }
};
pm.sendRequest(postRequest, (error, response) => {
  console.log(error ? error : response.json());
});

// Example containing a test
pm.sendRequest('111', (error, response) => {
  if (error) {
    console.log(error);
  }
pm.environment.get("shit");
pm.environment.set("s", response);
  pm.test('response okay', () => {
    pm.expect(error).to.equal(null);
    pm.expect(response).to.have.property('code', 200);
    pm.expect(response).to.have.property('status', 'OK');
  });
});

Суть в том что все отрабатывает хорошо, я получаю нужный мне ответ. Я дописал логи, чтобы я мог сохранить ответ. Но постман выдает ошибку "There was an error in evaluating the test script:  Error: Unexpected token 'f' at 1:4 426fa910-4843-46dc-8819-58a6ede02a42 ^", при этом нужный ответ выглядит вот так: 426fa910-4843-46dc-8819-58a6ede02a42
Как мне это исправить?


text:
Q: Search LaTeX documentation with Alfred I'm using Alfred v2 on Mavericks. I would like to use it to quickly locate documentation of LaTeX packages (PDF files). I have TeXLive 2014 installed in /usr/local/texlive/2014. I added /usr/local/texlive/2014/texmf-dist/doc/latex to Alfred's search scope, but I'm not having any success. I tried searching using open and the backtick (file search) to no avail. I tried rebuilding the OSX metadata, but not joy there either. The locate command-line utility quickly finds the files in question, e.g.:
$ locate thmtools.pdf
/usr/local/texlive/2014/texmf-dist/doc/latex/thmtools/thmtools.pdf

I should add that Spotlight can't find the files either. Is it a matter of permissions?
$ ll /usr/local/texlive/
total 0
drwxr-xr-x  20 root  wheel   680B Sep 21 11:51 2014

Thanks for any hint!

A: (1) Ready Alfred to accept a terminal command. Per this support document, the standard method is to type > and then the terminal command. Similarly, in LaunchBar the action is built into the basic index, too, and one can initiate it with term or similar.
(2) Type texdoc PackageName where PackageName is the LaTeX package you're looking for the documentation for. For example: texdoc enumitem or texdoc thmtools.
It'll open the documentation PDF. That's it!
Note that of course you can also do this from the command line directly if you open a terminal window.

A: If you're a Powerpack user, I'd suggest creating a file filter. Follow the steps in the tutorial below, but drag in a LaTeX file instead to tell your filter which file types to include. You can include as many file types as you need.
http://blog.alfredapp.com/2014/04/24/tutorial-creating-an-alfred-workflow-without-a-single-line-of-code/
If you're not a Powerpack user, you can add the LaTeX file types to Alfred's Default Results. Go to the Preferences > Features > Default Results, click on "Advanced" and drag in your file types. However, be aware that this could clutter up your results quite a bit if you have a lot of files of this type, making it harder to locate your apps or essential files. :)


text:
Q: Why won't my bookmarklet work? I have a commenting tool that can be included on a page simply by adding a script tag to the <head>. This works fine, and I've made a Greasemonky script and Firefox plugin that do just that, and putting it manually on a site works fine too. However I'm trying to make a bookmarklet:
javascript:(function(){var%20ormeo=document.createElement('script');
ormeo.src='http://www.ormeo.net/js/ormeoStart.js';
ormeo.type='text/javascript';
document.getElementsByTagName('body')[0].appendChild(ormeo);})();

...and this doensn't work (on Firefox 3.5). Any ideas why? Other bookmarklets that do the same thing, add a <script> tag to the <head> work fine, why not mine?

A: javascript:(function(){var ormeo=document.createElement('script');
ormeo.src='http://www.ormeo.net/js/ormeoStart.js';
ormeo.type='text/javascript';
document.getElementsByTagName('head').item(0).appendChild(ormeo);})();

Please try this code. It will help you.

A: Try adding the script tag to the head instead of the body:
document.getElementsByTagName('head')[0].appendChild(ormeo);})();


text:
Q: spark programming: best way to organize context imports and others with multiple functions It's easy and simple in the toy examples for showing how to program in spark. You just import, create, use and discard, all in one little function.
import org.apache.spark._
import org.apache.spark.sql._
import org.apache.spark.sql.hive.HiveContext

def main(args: String) {
  val conf = new SparkConf().setAppName("example")
  val sc = new SparkContext(conf)
  val sqlContext = new SQLContext(sc)

  val hiveContext = new HiveContext(sc)
  import hiveContext.implicits._
  import hiveContext.sql

  // load data from hdfs
  val df1 = sqlContext.textFile("hdfs://.../myfile.csv").map(...)
  val df1B = sc.broadcast(df1)

  // load data from hive
  val df2 = sql("select * from mytable")
  // transform df2 with df1B
  val cleanCol = udf(cleanMyCol(df1B)).apply("myCol")
  val df2_new = df2.withColumn("myCol", cleanCol)

  ...

  sc.stop()
}

In the real world, I find myself writing quite a few functions to modularize the tasks. For example, I would have a few functions just to load the different data tables. And in these load functions I would call other functions to do necessary data cleaning/transformation as I load the data. Then I would pass the contexts like so:
 def loadHdfsFileAndBroadcast(sc: SparkContext) = {
   // use sc here
   val df = sc.textFile("hdfs://.../myfile.csv").map(...)
   val dfB = sc.broadcast(df)
   dfB
 }

 def loadHiveTable(hiveContext: HiveContext, df1B: Broadcast[Map[String, String]]) = {
   import hiveContext.implicits._
   val data = hiveContext.sql("select * from myHiveTable")
   // data cleaning
   val cleanCol = udf(cleanMyCol(df1B)).apply(col("myCol"))
   df_cleaned = data.withColumn("myCol", cleanCol)
   df_cleaned
 }

As you can see, the load function signatures get heavy quite easily.
I've tried to put these context imports outside the main function inside the class. But that causes problems (see this issue), which leaves me no option but to pass them around.
Is this the way to go or is there a better way to do this?

A: First, let me say I'm glad that someone is exploring writing clean code in Spark. That is something I always find critical, but it always seems like people are so focused on the analytics themselves they lose sight of maintainability.
I do also agree Spark produces interesting challenges in that regard. The best way I've found, and of course you might feel this isn't an improvement, is to use traits with abstract method definitions and mix those into the object that orchestrates everything.
For example:
trait UsingSparkContextTrait {
   def sc: SparkContext

   def loadHdfsFileAndBroadcast = {
      val df = sc.textFile("hdfs://.../myfile.csv").map(...)
      sc.broadcast(df)
 }
}

trait UsingHiveContextTrait {
   def hiveContext: HiveContext
   def df1B: Broadcast[Map[String, String]]
   def loadHiveTable = {
      val data = hiveContext.sql("select * from myHiveTable")
      val cleanCol = udf(cleanMyCol(df1B)).apply(col("myCol"))
      data.withColumn("myCol", cleanCol)
 }
}

And then finally:
import org.apache.spark._
import org.apache.spark.sql._
import org.apache.spark.sql.hive.HiveContext

class ClassDoingWork extends UsingSparkContextTrait with UsingHiveContextTrait {
   val conf = new SparkConf().setAppName("example")
   val sc = new SparkContext(conf) //Satisfies UsingSparkContextTrait
   val sqlContext = new SQLContext(sc)

   val hiveContext = new HiveContext(sc) //Satisfies UsingHiveContextTrait
   val dfb = loadHdfsFileAndBroadcast    //Satisfies UsingHiveContextTrait
   import hiveContext.implicits._
   import hiveContext.sql

   def doAnalytics = {
      val dfCleaned = loadHiveTable
      ...
   }
}

The cool thing about this dependency injection-ish approach is that you will know at compile-time if you are missing any of the components you need for your code to execute.
Finally, on a much simpler note, you can also access the SparkContext from an RDD instance with rdd.context. That could prove useful too.

A: If all of your methods are defined in a single object/class, you could make the contexts belong to the object/class and always reference the global instance. If you provide it in the constructor you can even safely import only once and have access to the methods everywhere in your class/object.
For instance, if contexts are defined implicitly in calling object
object testObject {
  def main(args: Array[String]): Unit = {
    val sconf = new SparkConf().setMaster("local[2]").setAppName("testObj")
    val rootLogger = Logger.getRootLogger
    rootLogger.setLevel(Level.ERROR)
    implicit val sc = new SparkContext(sconf)
    implicit val sqlContext = new SQLContext(sc)
    new foo().run()
  }
}

you can use them below in the class that actually holds your logic
case class OneVal(value: String)
class foo(implicit val sc: SparkContext, implicit val sqlC: SQLContext){
  import sqlC.implicits._
  def run(): Unit ={
    doStuff().show(1)
    doOtherStuff().show(1)
  }
  def doStuff(): DataFrame ={
    sc.parallelize(List(OneVal("test"))).toDF()
  }
  def doOtherStuff(): DataFrame ={
    sc.parallelize(List(OneVal("differentTest"))).toDF()
  }
}

In this example SQLContext.toDF is the implicit method in this case.
If run, this gives below output as expected
+-----+
|value|
+-----+
| test|
+-----+

+-------------+
|        value|
+-------------+
|differentTest|
+-------------+


text:
Q: How to uninstall packages and revert to the original provided by the distribution? I'm running Debian oldstable (Jessie 8) and I'm interested in installing some .deb packages for testing purposes from testing (Buster 10). I'll be downloading the .deb files directly from packages.debian.org, and installing them using dpkg -i.
If I needed to, how would I uninstall those testing/buster packages and revert back to what originally came with oldstable?
Thanks

A: As others have suggested, you'd be better off upgrading to Debian 9 and using backports, rather than trying to use Debian 10 packages directly on Debian 8.
However, if you get all the dependencies right you should be able to run Debian 10 packages on Debian 8, as always at the risk of breaking your setup. Reverting is easy enough in your case, since you'll be installing packages using dpkg -i:

*

*for packages which weren't installed previously, remove them with dpkg -P (which will purge them);

*for packages which were installed previously, downgrade them with apt install ${package}/jessie.

Do note however that package downgrades aren't supported; in most cases they will work, but if they break it's not a bug and you'll get to keep both pieces.

A: I seriously recommend that you create a virtualized machine and run your tests on it.
apt is amazing but even it might not be able to fix the potential problems that could arise if you so something wrong.
For reverting to older versions, see Stephen Kitt's answer.


text:
Q: GNU Screen: Combining split-regions and full-screen sessions Let's say I have three sessions: 0, 1 and 2
I'm on session 0 and I press CTRL-A S to split the screen. Then I select session 1 for the bottom split region, while 0 is in the upper.
Can I switch to session 2 and have it display in full-screen while 0 and 1 remain split? If I CTRL-A n to other sessions in a split screen it only changes the split-region. I want some sessions to be full-screen though.
Is that possible?

A: The terminal is split into pains and windows (not sessions) are shown in each pane.  With screen you are not able to change quickly between unsplit and split.  You could probably set up some macros to push the necessary operations.
tmux might be able to do this for you, but I've never spent much time with it.

A: GNU Screen does the splitting "above" the organisation of individual screens. So, no.
However, you can nest screen sessions. This is one reason for the -m and -e options. You can nest in either direction (or even both), but the hotkey usage can get tricky.

A: On Ubuntu 20.04 using GNU Screen version 4.08.00 (GNU) 05-Feb-20, I am able to get the OP's desired behavior using the following. You can add it to your ~/.screenrc (may require some tweaking; I don't use it this way) or save it somewhere and then use it by invoking screen as follows:
screen -c /path/to/file -S session_name
# -----------------------------------------------------------------------------
# Loads a multi-pane layout with easy access to terminal + vim editor w/bottom terminal
#
# 0 - Bash prompt
# 1 - Vim (focused)
# 2 - Bash prompt
# -----------------------------------------------------------------------------

# Create new layout with bash prompt
layout new shell
layout title shells
layout select shell
screen -t shell bash

# Create new layout with vim + bottom terminal
layout new editor
layout title editor
layout select editor
# Open vim in
screen -t vim bash -c 'vim; bash'

focus

# Horizontal split
split

# Move to bottom split
focus down

# Create bash shell in bottom split
select 1
screen -t term bash

# Give vim bash shell a little less vertical space
resize -v -15

# Move focus back up to vim
focus up

The key is using layouts. You can read more about them here, but the gist of it is you use layouts to contain collections of windows and then you switch between layouts vs. windows for the type of behavior that you'd like. That being the case, I've added the following to my .screenrc to simplify layout switching:
# Creates a default layout of 0, which makes the user's sessions start
# numbering at 1, which makes for easier switching
# (it also saves your layout to 'default' by default)
layout save default

# Create new layout with shell prompt when creating a new window
bind c eval 'layout new' screen

# Switch between layouts with Alt+Number
bindkey "^[0" layout select 0
bindkey "^[1" layout select 1
bindkey "^[2" layout select 2
bindkey "^[3" layout select 3
bindkey "^[4" layout select 4
bindkey "^[5" layout select 5
bindkey "^[6" layout select 6
bindkey "^[7" layout select 7
bindkey "^[8" layout select 8
bindkey "^[9" layout select 9

# Switch to previous layout
bind , layout prev

# Switch to next layout
bind . layout next

# Show all layouts
bind s layout show

Note: All of the above are cobbled together from hours of researching, reviewing blog posts, etc., so I don't claim credit for anything other than managing to compile together a solution that works for me :)


text:
Q: JPA Criteria API and two joins on the same path expression My problem is very similar to this old question: Hibernate Criteria with self join but I'd need a non-Hibernate specific, clean JPA solution for identical problem. I use Hibernate 4.3 at the moment as a JPA provider, but I can update it if necessary. I have following entities:

*

*Game, which can have many Result entries, one per each player that played it

*GameResult owned by a Game and referencing a player who took a part. It has no back reference to the owning Game

*Player who played a game.

Now I want to create a query that finds all games that I played against a particular opponent and retrieve our scores. I got following JPA query:
String strQuery = "SELECT g, my_result, their_result FROM Game g JOIN g.results my_result JOIN  g.results their_result WHERE my_result.player=:p1 AND their_result.player=:p2";

It seems to work, but I'd like to transform it to Criteria API, and I am a complete noob when it comes to Criteria API. I got following for a start:
Root<Game> game = query.from(Game.class);
Join<Game, GameResult> result_mine = game.join("results");

So far, so easy. But now I have no idea how to get result_theirs joined with this part. I tried following:
Join<Game, GameResult> result_theirs = game.join("results");
result_mine.join( *what should I put here* , result_theirs);

//or:
Selection<Game> alias_game = game.alias("g");
Join result_theirs = result_mine.join(alias_game, "results"); //does not compile

//or:
Join result_theirs = result_mine.join(game.get("results")); //does not compile

//or:
Join<Game, GameResult> result_theirs = game.join("results");
result_mine.join(result_theirs); //does not compile

I am missing something, but I have no idea what, or maybe I am going in a wrong direction.
So, what am I doing wrong and how can I translate above JPA query into Criteria API code?

A: Your 3rd or is correct except you are joining it twice
Your line result_mine.join(result_theirs); tries to join the GameResult to GameResult which cannot be done as your Entity mapping only specified how to join Game to GameResult(but not GameResult to GameResult) the former is already done by Join<Game, GameResult> result_theirs = game.join("results");
So do Something like below
CriteriaQuery<Tuple> query = cb.createTupleQuery();
Root<Game> game = query.from(Game.class);
Join<Game, GameResult> result_mine = game.join("results");
Join<Game, GameResult> result_theirs = game.join("results");
query
        .multiselect(game, result_mine, result_theirs)
        .where(
                cb.equal(result_mine.get("player"),p1),
                cb.equal(result_theirs.get("player"),p2)
        );
List<Tuple> results = em.createQuery(query).getResultList();


text:
Q: google cloud storage - difference between Storage.BlobWriteOption and Bucket.BlobWriteOption I don't understand difference between class Storage.BlobWriteOption and Bucket.BlobWriteOption . I have attached SDK signature . Some method is taking an argument in bucket level but not in storage level.
Bucket.BlobWriteOption
Storage.BlobWriteoption


text:
Q: c++ pure virtual function(abstract) used as callback for C library function I am creating a C++ library from a C library.
C library have functions that contain callback,and callback have also arg(number of arguments).
I want to expose callback class override functions to the user so that the user can access callback function data.
As shown in this example user use callback class
To simplify, I created the smallest version of my issue.
Here I am trying to use a standard C function with a callback and assign a pure virtual function as the callback.
/// library.h part of  code //////
#include <iostream>
extern "C" {
    #include<stdio.h>
}

extern "C" {
    void qsort(void *base, size_t nmemb, size_t size, int (*)(const void *, const void *));
}

struct callback{
    virtual int compare(const void *a, const void *b)=0;
};

struct myclass{
    myclass()=default;
    callback *callback_;
    void mycallback(callback& cb){
        callback_ = &cb;
    }

    void sortdata(int *array,int size){
        qsort((void*)array,size,sizeof(int),callback::compare);
        //qsort((void*)array,size,sizeof(int),&callback_->compare);
    };
};

and
////Application.cpp part code ///////////////////
//#include "library.h"
class usercallback : public callback{
public:
    //currenty only one callback but in my case many
    virtual int compare(const void *a, const void *b) override{
        std::cout<<__PRETTY_FUNCTION__<<std::endl;
        return *((int*)a) < *((int*)b);
    }
};

int main(){
    int array[] = {1,2,4,5,7,8,93,2,4,6,7,89,43,2,4,5};
    int size = sizeof(array)/sizeof(array[0]);
    myclass myobj;
    usercallback cb;
    myobj.mycallback(cb);
    myobj.sortdata(array,size);
}

this program gives error and i gauss because of C++ internally pass this object as arg.
error: invalid use of non-static member function 'virtual int callback::compare(const void*, const void*)'
   23 |         qsort((void*)array,size,sizeof(int),callback::compare);

I have also read this article.but it not solve my problem.
i also know that it can be solved by using static, but i want to expose a class to the users, as in this example.
code building on Ubuntu.

A: The ideal solution is to not paint yourself in that corner in the first place. If you have any leeway at all towards addressing this differently from a design standpoint, that should be your goto.
That being said, if you are stuck, and HAVE to make that interoperability work, you'll have to marhsall the this available from a free-floating function, which means a global variable. A private static member variable is the best approach for this here, and ideally, it should be thread_local for safety.
For example:
// library.h
struct myclass{
    myclass()=default;

    void mycallback(callback& cb){
        callback_ = &cb;
    }

    void sortdata(int *array,int size){
        active_instance_ = this;
        qsort((void*)array,size,sizeof(int),compare_entry);
        active_instance_ = nullptr;
    };

private:

    callback *callback_;
    static thread_local myclass* active_instance_;

    static int compare_entry(const void *a, const void *b) {
        assert(active_instance_);
        active_instance_->callback_->compare(a, b);
    }

};

// library.cpp
thread_local myclass* myclass::active_instance_ = nullptr;

Obviously, this is only fine for callbacks that only live until the stack unwinds. It is inappropriate for anything involving long-lived callbacks.
For those, hopefully, the API in question provides a void* user_data pointer in which you can store this. If so, then you would be able to do:
//assuming
void register_callback(void* user_data, void (*cb)(void*, int));

// library.h
struct myclass{
    myclass()=default;

    void mycallback(callback& cb){
        callback_ = &cb;
        register_callback(this, callback_entry);
    }

private:
    callback *callback_;
    static int callback_entry(void* user_data, int p) {
        auto self = reinterpret_cast<myclass*>(user_data);
        self->callback_->some_method(p);
    }
};


text:
Q: When the Omegawolf attacks a target that is guarded by the Huntsman, which of the three (Omegawolf, target, Huntsman) die? The Omegawolf usually can't be killed at night; does that apply to this situation, and what happens to the target and the Huntsman?

A: That is correct. The Omegawolf won't be killed in this situation as they are immune to the kill.
The Huntsman will still sacrifice themselves though, and the target will remain alive - so in this situation only the Huntsman will die.

A:
What if both a protector and a huntsman are visiting when the Alphawolf visits; which of those visitors (protector and/or huntsman) dies then?

I assume you mean Omegawolf here? If so, both the Protector and the Huntsman die. If a Protector and a Huntsman guard the same target, the Huntsman's protection triggers first. The Protector dies for visiting the target that the Omegawolf attacked (Unless that target is the Protector, in which case the Protector survives).


text:
Q: Mixing Authentication Policies in Pyramid I am writing an application that will have some HTML content (display tables etc.) and also have a JSON API.
For normal HTML I use AuthTktAuthenticationPolicy for authentication and ACLAuthorizationPolicy for authorization. So the user is presented with a login form and on successful login auth_tkt cookie is set. The system works fine.
Now I want to replicate a similar system for JSON API. The problem is that for API requests user will not necessarily be logged in. So each request requires an api_key parameter. Based on the key, if I find a valid user, I send back the JSON. Otherwsie I display a 403 page.
One way is to do this in each view
api_key = request.GET.get('api_key',None)
user = FrontEndUsers.User_by_api_key(api_key)
if user:
    #Process view
else:
    return HTTPForbidden

However, it seems too much of a boiler-plate to use for each view to do exaclty what an authentication policy would do. Can I specify a separate authentication policy for JSON routes? Or is there any other way of doing this?
EDIT
On second thoughts it seems that even with AuthTktAuthenticationPolicy, I have to do
security.authenticated_userid() in every view (If I need authentication info). This I have already factored into a separate function
def get_auth_info():
    user_id = security.authenticated_userid()
    login_info = {}
    if user_id is not None:
        login_info['login'] = True
        login_info['logged_in_user'] = FrontendUsers.get_user_by_id(user_id).name
    else:
        login_info['login'] = False
    return login_info

I can include the API_key check function call in this function so that none of my views change (I still only call get_auth_info()) and yet I can check if correct API key has been presented.
I'd still like to see if there are any other ways to do this or if there's a problem with my current scheme

A: You didn't mention anywhere in here how you're using permissions? Proper usage of permissions and ACLs on your views should prevent you from needing to run that boilerplate at the start of your function. For the simple paste you showed, you simply need a permission='logged_in' and an ACE mapping (Allow, Authenticated, 'logged_in'), but of course you can get more complex if necessary.
It is not possible to specify different authentication policies for different views in a simple way because authentication policies in pyramid are intended to be global. You can do it globally via the pyramid_multiauth. Or you may write your own policy that wraps multiple policies and dispatches to one or another depending on request properties.


text:
Q: Attempt to invoke virtual method 'int android.graphics.Bitmap.getHeight()' on a null object reference I'm working on image selection from "Gallery" or "Take photo". My problem is, while back pressed when taking the photo by using camera. I'm getting the error.
My code is
if (items[position].equals("Take photo")) {
                        Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        File file= getOutputMediaFile();
                        Uri picUri = Uri.fromFile(file);
                        filepath = picUri.getPath();
                        i.putExtra(MediaStore.EXTRA_OUTPUT,picUri);
                        _a.startActivityForResult(i, 1);
                    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    Log.e("Action", action);
    if (action.equals("add_car")) {
        if(_addLayout.filepath != null){
            filePath = _addLayout.filepath;
            _addLayout.filepath = null;
        }
        if(data != null)
        filePath = CommonUtilities.getPath(data.getData(), "Image");
        _addLayout.filepath = filePath;
        setImage(UI_AddCar.ivTakenPicture);
    }
  }

void setImage(ImageView im){
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;

     Bitmap bitmap = BitmapFactory.decodeFile(filePath);

     if(filePath != null){
         int height = bitmap.getHeight(), width = bitmap.getWidth();
            if (height > 1280 && width > 960){
                Bitmap imgbitmap = BitmapFactory.decodeFile(filePath, options);
                im.setImageBitmap(imgbitmap);
                im.setVisibility(View.VISIBLE);
         } else {
                im.setImageBitmap(bitmap);
                im.setVisibility(View.VISIBLE);
            }
     }

In this UI_AddCar.ivTakenPicture is the ImageView

A: Thanks to Piyush Gupta. I updated if condition like
if(filePath != null && bitmap != null){
         int height = bitmap.getHeight(), width = bitmap.getWidth();

            if (height > 1280 && width > 960){

                    Bitmap imgbitmap = BitmapFactory.decodeFile(filePath, options);
                    im.setImageBitmap(imgbitmap);
                    im.setVisibility(View.VISIBLE);

            }else {

                    im.setImageBitmap(bitmap);
                    im.setVisibility(View.VISIBLE);
            }
     }


text:
Q: How can I maintain child objects with LinqToSql over WCF? I am currently stuck in the design of this solution.
The data layer design consists of the following:

*

*Recipe (parent high level object)

*

*Language Detail (name, description by language) (many)

*

*Headers (many)

*Steps (many)

*

*Ingredients (many)

*Quantities (many)

*Procedures (many)

*Notes (many)

The challenge that I am having is how to create a data access design that will add/remove the child objects in the database when the object is populated from a WCF SaveRecipe(recipe) method?
This all stems from the management asking us to add a communications layer in our application, right now our UI is coupled to our business layer, and the BL is directly coupled to the DAL, we basically need the injection of WCF between the BL and DAL.
I have read in this thread that using L2S isn't a good idea over WCF, but since the design isn't new, we have to use this type of methodology, and then move away from it once we can refactor the heavy amounts of UI work.

A: If you are trying to send stuff down the line with WCF I suggest you create a model of the data you want to move around your domain. As far as I've found you can't serialize IQueryable objects, but you can create a set of classes that Linq populates and then serialize that. For example:
[DataContract]
public class Recipe {

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Description { get; set; }

    [DataMember]
    public List<Ingredient> Ingredients { get; set; }

}

Then fill that up with
List<Recipe> recipes = (from r in dc.recipe
                           select new Recpie {
                               Name = r.name,
                               Description = r.description,
                               Ingredients = (Linq code to make list of ingredients)
                           }).ToList();

And then sending the list down the line with WCF becomes a piece of cake.

A: I like this answer from Karl on the thread you referenced:

It is better to create your own
  classes for the transfer of data
  object. Those classes, of course,
  would be implemented as DataContracts.
  In your service layer, you'd convert
  between the linq-to-sql objects and
  instances of the data carrier objects.
  It is tedious but it decouples the
  clients of the service from the
  database schema. It also has the
  advantage of giving you better control
  of the data that is passed around in
  your system.

It looks like you're going to have to refactor anyways - just as well start by refactoring out the dependency to linq2sql in your UI layer.
I don't think you have a quick and easy solution.

A: I don't recommend exposing L2S classes over WCF. Create a hierarchy of DataContract objects, and pass those over WCF. The downside of this is that you have to "deep copy" your L2S objects into your DataContract hierarchy, but the upside is that you can only include fields that are necessary and proper for transport over a network. For example, in a project I'm working on now, I pass an EmployeeData object over the network that includes most of my L2S Employee fields but excludes things like the employee's salted hash & password salt.

A: It could also be an idea to create classes both including and excluding child entries. I have sometimes created classes like this:
class Recipe {
    [DataMember] public string Name;
    [DataMember] public string Description;
}

class RecipeWithIngredients : Recipe {
    [DataMember] public IList<Ingredient> Ingredients;
}

Edit: inadvertedly posted before the post was finished.


text:
Q: How do I install Tesseract OCR onto WAMP server, to be run by PHP? I am attempting to install the OCR software Tesseract onto my WAMP server so that I can then automate the OCR process for some images. When I search for how to install software onto a WAMP server, all I get back is how to install a WAMP server so that route turned up no answers. I have successfully installed Tesseract on my computer and know that the files I am using work properly, my issue is that I am unable to run Tesseract from a PHP script. I used the Windows installer that is provided and installed it to my www directory in WAMP. I then attempted to use the PHP exec() to perform some OCR and got no output. This is my simple script:
<?php
    $path = getenv('PATH');
    putenv("PATH=$path:/usr/local/bin");
    $src = 'a.jpg';
    $srcImg = imagecreatefromjpeg($src);

    $img = imagecreatetruecolor($newClanWidth, $newHeight);
    imagecopyresampled($img, $srcImg, 0, 0, $positions["aPlayer"], $positions[0], $newClanWidth, $newHeight, $clanWidth, $height);
    imagejpeg($img, 'temp.jpg', 100);
    echo '<pre>';
    exec('tesseract temp.jpg out');
    //echo file_get_contents('out.txt');
    echo '</pre>';
    imagedestroy($img);
?>

The image is being saved correctly. I can change the positions in the imagecopyresampled() and the image is changed accordingly. I suspect my problem is with the installation since everywhere I look everyone says to use exec() just like I would from a command line. I have also tried specifying the command like Tesseract-OCR/tesseract.exe temp.jpg out. The Tesseract-OCR folder is in the same directory as my PHP script. I admit to being new to this, so please bear with me if there is something simple I've overlooked. Thanks in advance.

A: what do you mean by "successfully installed Tesseract" ?
how did you verify that?
can you run tesseract.exe -v and get proper in command line (or however you call CMD on windows these days)?
if this works, than make sure that you get the same results by doing this via php:
make sure that you have errors turned on: error_reporting(-1) and check if you are getting any errors.
than try if you actually can execute tesseract via php by:
$return = shell_exec('tesseract.exe -v'); // in your example you miss .exe it would be without extension on linux
var_dump($return);

(shell_exec returns the all output, compare to exec what returns just the last line)
if that works, than try setting absolute path while extracting:
imagejpeg($img, 'c:/temp.jpg', 100);
$return = exec('tesseract.exe temp.jpg c:/out');
var_dump($report); // in case it gives you some errors
$content = file_get_contents('c:/out.txt');
if ($content === false) die('something is still wrong');
// otherwise process $content

if nothing helps, than share your results/errors.
last hint: try to install linux


text:
Q: Wall-in: benefit or vulnerability? In one of the Day[9] TV videos (5:40-6:00 minutes) Day[9] (what is actually his name?) says something like this:

Wall-in is almost always a vulnearability as much as asset. In the early game wall-in off prevents rushes, but in later stages of the game it is just a ... free depo there?

Could you clarify what he said (I couldn't here the end of phrase well)?
And why it is vulnerability?
Thanks.

A: It also creates a choke in your own base, so for example if your army is in the main base while your natural expo gets attacked, it will be more difficult for you to engage the opponent, because your wall-in forces your army into a small choke.
[update]
Note: In team games (2v2 / 3v3 / 4v4), it's far more compelling to wall in because you risk facing much stronger rush attacks. The bigger the rush, the more important it is to keep them at bay while you prepare a defense. As Terran, I sometimes place unfinished buildings at the front as an emergency, or as Protoss, you sometimes need multiple zealots ready to do the hold-position gate.
[update]
A wall-in can often provide void rays an easy full-charge.

A: He's referring to the fact that you've placed a few supply depots and a rax right at your main base entrance. It's a vulnerability because it's 16 supply and a production building that is much easier to snipe than the rest of your supply and production buildings. In essence, you've given your opponent what Day[9] considers to be some free buildings to destroy.
As to whether or not its a liability, it depends on whether or not you extend your defensive perimeter to include your expansion bases.
Edit: Example of this weakness in action (playing the video will jump you to the relevant moment in the game):


text:
Q: MeshFunctions::invmeshf that resists other solutions I'm trying to base mesh on the slope of the function. That's why there is a Cross of two partial derivatives.
With[{R = Function[If[Abs[#1] < \[Pi]/4, 1, Sec[Abs[#1] - \[Pi]/4]]]},
  With[{F =
    Function @@ {{\[CurlyPhi],
       h}, {Sin[\[CurlyPhi]] R[\[CurlyPhi], h],
       Cos[\[CurlyPhi]] R[\[CurlyPhi], h], h}}},
  ParametricPlot3D[
     F[\[CurlyPhi], h], {\[CurlyPhi], -(\[Pi]/2), \[Pi]/2}, {h, -1,
      1}, MeshFunctions -> #1,
     Mesh -> {{0}}] &@{Function @@ {{\[CurlyPhi], h},
      Norm[{#1, #2, #3}] & @@ Cross[\!\(
\*SubscriptBox[\(\[PartialD]\), \(h\)]\(F[\[CurlyPhi], h]\)\), \!\(
\*SubscriptBox[\(\[PartialD]\), \(\[CurlyPhi]\)]\(F[\[CurlyPhi],
          h]\)\)]}}]]

The graph is plotted, but the mesh is not, and there is an error message:
MeshFunctions::invmeshf: "MeshFunctions->Function[{φ,h},Sqrt[Abs[Cos[<<1>>] If[<<3>>]+If[<<3>>] Sin[<<1>>]]^2+Abs[-Cos[<<1>>] If[<<3>>]+If[<<3>>] Sin[<<1>>]]^2]] must be a pure function or a list of pure functions."

Quite suddenly, when R is replaced by Function[1], the error disappears. But I don't need 1.
I tried renaming the arguments to the mesh function (to no avail), I turned the option into an argument to ParametricPlot3D& (to no avail), I turned Function[] into Function@@{} (to no avail). Now I'm at a loss.

A: Sorry for my careless.
Maybe Abs can't be differential in Mathematica,so we have to use RealAbs instead.
And it seems that we need to set  Mesh -> {{1}}.
With[{R = If[RealAbs[#1] < Pi/4, 1, Sec[RealAbs[#1] - Pi/4]] & },
 With[{F =
    Function @@ {{φ,
       h}, {Sin[φ]*R[φ, h],
       Cos[φ]*R[φ, h], h}}},
     (ParametricPlot3D[
      F[φ, h], {φ, -(Pi/2), Pi/2}, {h, -1, 1},
      MeshFunctions -> #1, MeshStyle -> {Thick, Red},
      Mesh -> {{1}}] & )[
       {Function @@ {{φ, h}, (Norm[{#1, #2, #3}] & ) @@
       Cross[D[F[φ, h], h],
        D[F[φ, h], φ]]}}]]]