text:
Q: Can I change metric units on CloudWatch? I am sending metric data to CloudWatch, and they were sent to AWS with StandardUnit.Count unit, but I later changed them to StandardUnit.Milliseconds. On my dashboard in AWS I still see the data in Count unit.
Is it possible to force AWS to show it in Millisecs, or will it change later? Or should I rename my metrics (I would not like that option)

A: You do not have to rename your metric. CloudWatch doesn't really care about your unit all that much. From CloudWatch Concepts doc:

Units help provide conceptual meaning to your data. Though CloudWatch attaches no significance to a unit internally, other applications can derive semantic information based on the unit.

Units are not tied to a metric, they are tied to each specific datapoint. In your case datapoints will have unit Count up to one point and Milliseconds from that point on. This is not a problem as long as you don't use GetMetricStatistics API with a specified unit. If you don't specify a unit, GetMetricStatistics will return data for both units, but if you set a unit, you'll only get the data for the specified unit (see the API docs for more detail).
CloudWatch Dashboards will display the last unit they see. In the example below, I was publishing the metric with unit Milliseconds up until the gap and with unit Count after the gap (opposite of your situation) and the dashboards are displaying the Count as unit:

If I change the range of the graph to exclude the datapoints with Count unit, graph displays Milliseconds as unit:

A: May be someone searching for cloudformation templates for the same.
      MetricName: "Duration"
  Namespace: "AWS/Lambda"
  Statistic: "Average"
  TreatMissingData: "notBreaching"
  Period: 120
  EvaluationPeriods: 1
  Threshold: 5000
  Unit: "Milliseconds"
  ComparisonOperator: "GreaterThanThreshold"
  Dimensions:
  - Name: "FunctionName"
    Value: !Ref LambdaAuthorizerFnName

A: Perhaps, you can go to Edit > Options, then:

*

*Uncheck the "Show units" option.

*Add custom label into the "Label" field.

Here, for example, I changed the label to "Seconds":

Result:


text:
Q: angular template to iterate over array or show single element Some custom components are part of an angular 7 app. Following pattern is common in the components where child components expect either a single value or an array. Depending on a flag, the component renders the required layout. Following is an example:
<ng-container *ngIf="!arrayFlag">
    <app-some-component ... >
        ...
    </app-some-component>
</ng-container>
<ng-container *ngIf="arrayFlag">
  <app-some-component ...
    *ngFor="let field of fields; let i = index; trackBy:trackByFn">
        ...
  </app-some-component>
</ng-container>

Can we simplify this pattern in such a way that the content of component need not be written twice, once for array and once for single value. e.g.
<ng-container ... >
  <app-some-component ... >
        ...
  </app-some-component>
</ng-container>

Regards

A: If your components are "dumb" like this (they don't hold any logic, you can maybe use templates :
<ng-template #child let-arr>
  <child-component *ngFor="let i of arr"></child-component>
</ng-template>

<ng-container *ngTemplateOutlet="child; context: { arr: flag ? [0] : myArray }"></ng-container>

EDIT Done way simpler :
<app-some-component
  *ngFor="let field of (flag ? fields : [0]); let i = index; trackBy:trackByFn">
</app-some-component>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically setting width of after selector I am creating a simple tab like functionality using CSS.
When a tab is active, I set CSS of the selected tab using the tab-slider--tabs:after selector. However one of Tab header text is longer than the other, hence the image looks like this:

How do I dynamically set the width so that it looks like this:

 .tab-slider--tabs {
  display: block;
  float: left;
  margin: 0;
  padding: 0;
  list-style: none;
  position: relative;
  border-radius: 35px;
  overflow: hidden;
  background: #fff;
  height: 35px;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}
.tab-slider--tabs:after {
  content: "";
  width: 50%;
  background: #345F90;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  transition: all 250ms ease-in-out;
  border-radius: 35px;
}
.tab-slider--tabs.slide:after {
  left: 50%;
}

Here's the: Demo Code
Update: I was able to solve this temporarily using .tab-slider--trigger{ width:30%; display: table-cell; ...}  but I am still looking for the right way to do this.

A: try this:
.tab-slider--trigger {
  width:150px;
  font-size: 12px;
  line-height: 1;
  font-weight: bold;
  color: #345F90;
  text-transform: uppercase;
  text-align: center;
  padding: 11px 20px;
  position: relative;
  z-index: 2;
  cursor: pointer;
  display: inline-block;
  transition: color 250ms ease-in-out;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}


text:
Q: Android reduce image when present in drawable folder I'm drawing in a Canvas a background.png image of my game (the image is wider than high because is a scolling background). The images have this sizes:

*

*drawable-xhdpi: 1817x443 px

*drawable-hdpi: 1363x332 px

*drawable-mdpi: 909x222 px

*drawable-ldpi: 682x166 px

I did some testing:

*

*On my Oneplus X the image looks pretty good, but on my Samsung
Galaxy Nexus and Wiko Iggy the image lose quality.

*Now, if I remove the background.png from xhdpi folder, the image
looks good on Oneplus X and Galaxy, but it is still bad on Wiko.

*At the end, if I remove the background.png from both xhdpi and hdpi folder, the
image looks good in all mobiles (Ok, the xhdpi version in Oneplus X
was a little better, but the mdpi version is still good too).

The drawing code of the 2 scrolling background:
backgroundArea.offsetTo(xBackground, backgroundArea.top);
canvas.drawBitmap(background, null, backgroundArea, mPaint);
backgroundArea.offset(backgroundArea.width(), 0);
canvas.drawBitmap(background, null, backgroundArea, mPaint);

Why are this happening? Why does It not taking the right image for the right mobile and instead it shrinks the bigger available image? How I can solve this?
(PS: I'm still using Eclipse ADT).

A: My problem was that Oneplus X has xxhdpi resolution, the Samsung Galaxy xhdpi and Wiko Iggy hdpi (You can use this app to discover the resolution).
So I created a new folder drawable-xxhdpi and moved all background.png "one floor upstair" (I put my 1817x443 image from xhdpi to xxhdpi and so on). You can use this scale:
LDPI - 0.75x
MDPI - Original size // means 1.0x here
HDPI - 1.5x
XHDPI - 2.0x
XXHDPI - 3x
XXXHDPI - 4.0x


text:
Q: OnClick not firing in UserControl when button is clicked I have a master page.  In the master page I have a UserControl for the footer.  In the footer I have a button that is not firing OnClick.  During debugging I see the function being called by OnClick, btnSignup_Click,  is not getting hit.  I can't seem to figure out where the mistake in my code is.
Also I wanted to note that the validation functionality is working correctly.
master.master
<%@ Master Language="C#" AutoEventWireup="true" Inherits="master" Codebehind="master.master.cs" %>
<%@ Register TagPrefix="xyz" TagName="Footer" Src="~/controls/footer.ascx" %>

<xyz:Footer ID="Footer" runat="server" />

footer.ascx
<%@ Control Language="C#" AutoEventWireup="true" Inherits="footer" Codebehind="footer.ascx.cs"  %>

     <asp:TextBox ID="fName" runat="server"></asp:TextBox>
     <asp:RequiredFieldValidator ID="RequiredFieldValidatorfName"  ValidationGroup="validationSignup" Display="Static" ControlToValidate="fName" ErrorMessage="First Name required" runat="server"></asp:RequiredFieldValidator>

    <asp:Button ID="btnSignup"  CommandName="Button" runat="server" ValidationGroup="validationSignup" Text="Signup"  HeaderText="Please fill in all required fields before continuing." OnClick="btnSignup_Click"/>

    <asp:ValidationSummary ID="ValidationSummary"   ValidationGroup="validationSignup" runat="server"></asp:ValidationSummary>

footer.ascx.cs
public partial class templates_site_footer : BaseUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSignup.Click += new EventHandler(btnSignup_Click);
    }
    protected void btnSignup_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        // code to execute after button is clicked
    }
}

A: Remove btnSignup.Click += new EventHandler(btnSignup_Click); code from Page_Load event, You had already assigned OnClick event to button in .ASCX markup and no need to check validate of your page again in btnSignup_Click, you can directly write button click event code which you want to execute.
Your Footer User Control Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
    //btnSignup.Click += new EventHandler(btnSignup_Click);
}

protected void btnSignup_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
         // code to execute after button is clicked
    }
    else
    {
         // Your page does not validated.
    }
}


text:
Q: PyQt Error: qt.qpa.plugin: Could not find the Qt platform plugin "windows" in При попытке компилировать созданное по туториалу простейшее оконное приложение на Python, в консоли выводит следующее сообщение:
qt.qpa.plugin: Could not find the Qt platform plugin "windows" in "E:\Python35\Lib\site-packages\PyQt5\plugins\platforms"
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: minimal (from E:\Python35\Lib\site-packages\PyQt5\plugins\platforms), offscreen (from E:\Python35\Lib\site-
packages\PyQt5\plugins\platforms), windows (from E:\Python35\Lib\site-packages\PyQt5\plugins\platforms).

Папку /platforms перенес в папку проекта. Не помогло.
Переменную окружения указывал на эту самую папку /platforms. Тоже не помогло.
С каким бубном еще поплясать, чтобы все заработало? :с


text:
Q: How to fit basic custom built model in tensorflow I am used to working in PyTorch but now have to learn Tensorflow for my job. I am trying to get up to speed by creating a simple dense network and training it on the MNIST dataset, but I cannot get it to train. My super simple code:
import tensorflow as tf
from tensorflow.keras import Input
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical

# Load mnist data from keras
(train_data, train_label), (test_data, test_label) = tf.keras.datasets.mnist.load_data(path="mnist.npz")
train_label, test_label = to_categorical(train_label), to_categorical(test_label)
train_data, train_label, test_data, test_label = Flatten()(train_data), Flatten()(train_label), Flatten()(test_data), Flatten()(test_label)

# Create generic SGD optimizer (no learning schedule)
optimizer = SGD(learning_rate = 0.01)

# Define function to build and compile model
def build_mnist_model(input_shape, batch_size = 30):
    input_img = Input(shape = input_shape, batch_size = batch_size)

    # Pass through dense layer
    x = Dense(200, activation = 'relu', use_bias = True)(input_img)
    x = Dense(400, activation = 'relu', use_bias = True)(x)
    scores = Dense(10, activation = 'softmax', use_bias = True)(x)

    # Create and compile tf model
    mnist_model = Model(input_img, scores)
    mnist_model.compile(optimizer = optimizer, loss = 'categorical_crossentropy')

    return mnist_model

# Build the model
mnist_model = build_mnist_model(train_data[0].shape)

# Train the model
mnist_model.fit(
    x = train_data,
    y = train_label,
    batch_size = 30,
    epochs = 20,
    verbose = 2,
    shuffle = True,
    # steps_per_epoch = 200
)

When I run this I get
ValueError: When using data tensors as input to a model, you should specify the `steps_per_epoch` argument.

This does not really make sense to me because my train_data and train_label are just regular tensors and per the Tensorflow documentation in this case it should default to the number of samples in the dataset divided by the batch size (which would be 200 in my case).
At any rate, I tried specifying steps_per_epoch = 200 when I call mnist_model.fit() but then I get a different error:
InvalidArgumentError: Incompatible shapes: [60000,10] vs. [30,1]
     [[{{node training_4/SGD/gradients/gradients/loss_5/dense_17_loss/softmax_cross_entropy_with_logits_grad/mul}}]]

I can't seem to discern where a size mismatch would come from. In PyTorch, I am used to manually creating batches (by subindexing my data and label tensors) but in Tensorflow this seems to happen automatically. As such, this leaves me quite confused about what batch has the wrong size, how it got the wrong size, etc. I hope this simple model is way easier than I am making it and I just do not know the Tensorflow tricks yet.
Thanks for the help.


text:
Q: Why am I getting Cannot convert value of type Bool to expected argument type String Getting several "Cannot convert value of type Bool to expected argument type String" errors. The method for encoding expects a string but it is getting a Bool?
Here is the code. See the attached image for errors.
import Foundation

class Restaurant {
    var name = ""
    var item = ""
    var location = ""
    var image = ""
    var isVisited = false
    var phone = ""
    var rating = ""

    init(name: String, item: String, location: String, phone: String, image: String, isVisited: Bool) {
        self.name = name
        self.item = item
        self.location = location
        self.phone = phone
        self.image = image
        self.isVisited = isVisited
    }

    class func makeNewsItem(_ notificationDictionary: [String: AnyObject]) -> Restaurant? {
        if let name = notificationDictionary["name"] as? String,
            let phone = notificationDictionary["phone"] as? String,
            let location = notificationDictionary["location"] as? String {
            let date = Date()
            let image = ""
            let visited = false
            let item = ""

            let newsItem = Restaurant(name: name, item: item, location: location, phone: phone, image: image, isVisited: visited)

            NotificationCenter.default.post(name: Notification.Name(rawValue: RestaurantTableViewController.RefreshNewsFeedNotification), object: self)
            return newsItem
        }
        return nil
    }
}

extension Restaurant: NSCoding {
    struct CodingKeys {
        static var Name = "name"
        static var Item = "item"
        static var Location = "location"
        static var Image = "image"
        static var IsVisited:Bool = false
        static var Phone = "phone"
        static var Rating = "rating"
    }

    convenience init?(coder aDecoder: NSCoder) {
        if let name = aDecoder.decodeObject(forKey: CodingKeys.Name) as? String,
            let location = aDecoder.decodeObject(forKey: CodingKeys.Location) as? Date,
            let phone = aDecoder.decodeObject(forKey: CodingKeys.Phone) as? String {

            let date = Date()
            let image = aDecoder.decodeObject(forKey: CodingKeys.Image) as? String
            let visited:Bool = aDecoder.decodeBool(forKey: CodingKeys.IsVisited) as? String
            let item = aDecoder.decodeObject(forKey: CodingKeys.Item) as? String

            self.init(name: name, item: item, location: location, phone: phone, image: image, isVisited: visited)
        } else {
            return nil
        }
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: CodingKeys.Name)
        aCoder.encode(location, forKey: CodingKeys.Location)
        aCoder.encode(phone, forKey: CodingKeys.Phone)
        aCoder.encode(item, forKey: CodingKeys.Item)
        aCoder.encode(image, forKey: CodingKeys.Image)
        aCoder.encode(isVisited, forKey: CodingKeys.IsVisited)
        aCoder.encode(rating, forKey: CodingKeys.Rating)
    }
}

A: You can´t add a bool value to the forKey. This has to be a string value, so change it from:
aCoder.encode(isVisited, forKey: CodingKeys.IsVisited)

To:
aCoder.encode(isVisited, forKey: "IsVisited")

Same for:
let visited:Bool = aDecoder.decodeBool(forKey: CodingKeys.IsVisited) as? String

To:
let visited:Bool = aDecoder.decodeBool(forKey: "IsVisited") // note, no need for as? String here


text:
Q: ASP.Net MVC dynamic script bundle does not load and gives 404 error first few times I am working on an existing ASP.Net MVC web application on .Net 4.5.2 and MVC 5.2. This has dynamic script bundles on 250 odd views which are added to the BundleTable only when the particular view is first accessed. This leads to an issue where the first time any view is hit, the script bundle returns a 404 error. But refreshing the page few times resolves the issue - at which point the bundle loads up fine and then gets cached on the browser.
The code for this looks like:
//View:
@model XYZ
@{ ViewBag.Title = "Title"; }
@section JavaScript {
    @Html.RenderScripts("~/Scripts/a.js", "~/Scripts/b.js")
}
// HtmlHelper RenderScripts extension
public static IHtmlString RenderScripts(this HtmlHelper helper, bool isMinified, params string[] filePaths)
{
    var path = (helper.ViewDataContainer as WebPageBase).VirtualPath.Replace("~/", "~/Scripts/").Replace(".cshtml", "").Replace("../", "");
    var bundle = new ScriptBundle(path).Include(filePaths);
    bundle.Orderer = _orderer;
    if (!isMinified) bundle.Transforms.Clear();
    BundleTable.Bundles.Add(bundle);
    return Scripts.Render(path);
}

It appears that the 1st request might be adding the bundle, but there's a lag in generating and serving up the bundle itself which is resulting in the 404 error. So how soon can a bundle be used once it's added - does it need a warm up?
Is this a wrong pattern of using Script bundles? Is there a way to address this so I can continue to declare the view-specific script bundles on the view without moving them to the bundle config?


text:
Q: Referencing PowerPoint Object in Excel VBA Long story short - I am trying to pass a string to PowerPoint from PowerShell to update a textbox on a master slide. I can do this from within PowerPoint vba, but it is completely static. As soon as I try to pass data through PowerShell to PowerPoint, I get an error that I have been unable to solve. (see here)
So instead I am attempting to do it through an Excel proxy! I already use Excel VBA to update content on PowerPoint slides, so thought this would be suitable. I currently have shapes set up in Excel, data is updated, and then this is pasted in to a PowerPoint deck, saved and closed.
I need to now extend this Excel macro with functionality that updates the textbox on the master slide. I need to translate "PowerPoint VBA" to "Excel VBA for PowerPoint", what a horrible sentence... I digress:
PowerPoint VBA
Function UpdateMasterF(message As Variant)
    Dim sourceLabel As Shape
    Dim curSLD As Long
    curSLD = ActiveWindow.View.Slide.SlideIndex

    'switch to SlideMaster
    Application.Windows(1).ViewType = ppViewSlideMaster

    Set sourceLabel = ActivePresentation.SlideMaster.CustomLayouts(1).Shapes("sourcelabel")
    sourceLabel.TextFrame.TextRange.Text = message

    'return to default
    Application.Windows(1).ViewType = ppViewNormal

    'set slide
    ActiveWindow.Presentation.Slides(curSLD).Select

Excel VBA
Function TestPowerPoint(message As Variant, presPath As Variant)
    Dim oPPTApp As Object
    Dim oPPTFile As Object

    Set oPPTApp = CreateObject("PowerPoint.Application")
    oPPTApp.Visible = msoTrue
    Set oPPTFile = oPPTApp.Presentations.Open(presPath)

    ' translate e.g. ApplicationWindow, ActivePresentation etc

    oPPTFile.Save
    oPPTFile.Close
    Set oPPTFile = Nothing
    oPPTApp.Quit
    Set oPPTApp = Nothing

I need to be able to complete the same steps as in the PowerPoint VBA but in the Excel macro. I'm having issues finding the right names for it though. So where it says
Application.Windows(1).ViewType = ppViewSlideMaster

Can this be replaced with oPPTApp or oPPTFile? I've read through MSDN Docs and it seems to match but doesn't work.
Hopefully that's conveyed my ask! I expect most people to read and shudder at such a situation...

A: The hierarchy's like this:
To access a presentation open in PPT, you'd use e.g.
Set oPPTPres = oPPTApp.Presentations(1) or
Set oPPTPres = oPPTApp.ActivePresentation

Each presentation object has a Designs collection representing the different masters in the presentation, so to access SlideMaster of the first design,
With oPPTPres.Designs(1).SlideMaster
   ' for example:
   With .Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 500, 50)
      .TextFrame.TextRange.Text = "Well, look at that, will ya!"
   End With

End with

Each Design has a collection of custom layouts (the thumbnails you see indented beneath the main master when in Slide Master view).  They can be similarly accessed.

A: So extending Steve's answer, I decided to just replace the existing box with a new one, to save the pain of trying to edit the existing shape.
I'm fortunate that the automation I am doing is for the creation of new PowerPoint decks, so I'm able to just place these new shapes on them as I create multiple decks from one blank canvas.
The code I ended up with to get the same formatting is:
Function TestPowerPoint(message1 As String, message2 As String, presPath As Variant)

set up variables to be used
Dim oPPTApp As PowerPoint.Application
Dim oPPTFile As Object
Dim oPPTPres As PowerPoint.Presentation

Set oPPTApp = CreateObject("PowerPoint.Application")
oPPTApp.Visible = msoTrue
Set oPPTFile = oPPTApp.Presentations.Open(presPath)
Set oPPTPres = oPPTApp.ActivePresentation

With oPPTPres.Designs(1).SlideMaster.CustomLayouts(1)
    With .Shapes.AddTextbox(msoTextOrientationHorizontal, 28, 60, 500, 25)
        .ZOrder msoBringToFront
        With .TextFrame.TextRange
            .Text = message1
            With .Font
                .Size = 10
                .Name = "Calibri"
                .Color = RGB(255, 0, 0)
                .Bold = msoTrue
            End With
        End With
    End With
End With

With oPPTPres.Designs(1).SlideMaster.CustomLayouts(2)
    With .Shapes.AddTextbox(msoTextOrientationHorizontal, 28, 200, 736, 50)
        .ZOrder msoBringToFront
        With .TextFrame.TextRange
            .Text = message2
            .ParagraphFormat.Alignment = ppAlignCenter
            With .Font
                .Size = 32
                .Name = "Calibri"
                .Color = RGB(255, 255, 255)
                .Bold = msoFalse
            End With
        End With
    End With
End With

oPPTFile.Save
oPPTFile.Close
Set oPPTFile = Nothing
oPPTApp.Quit
Set oPPTApp = Nothing

End Function

Fantastic! Thank you to everyone who contributed.


text:
Q: Cloud Firestore unable to retrieve document or field I've used the sample code provided by the Firebase Documentation and it prints out the error message. I have no clue if the issue is within the code or within the structure of the database, as there are also sub-collections. In this case, I am trying to retrieve the "Home Title" field, however I heard that that's not possible (I may be wrong), so I'm trying to retrieve the "Sample Wedding" document, to no avail. This is my very first time programming a project in Swift and also using Firestore.
Here's my code:
    let db = Firestore.firestore()
    let docRef = db.collection("Weddings").document("Sample Wedding")

    docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Document data: \(dataDescription)")
    } else {
        print("Document does not exist")
    }

Here's my database structure:
]

A: You can try it like this
  let db = Firestore.firestore()
  db.collection("Weddings").document("Sample Wedding").getDocument {
  (documentSnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            print("Document data: \(documentSnapshot)")
            if let title = documentSnapshot.get("Home Title") as? String {
            print(title)
           }
        }
    }


text:
Q: CUDA Cores and Streaming Multiprocessors Count for Inference Speed As far as I understand, the number of CUDA cores of an NVIDIA GPU determines how fast it can run a single deep learning model.
So, if I'm running inference on a model in 0.5 seconds with an NVIDIA TITAN RTX GPU, which has 72 streaming multiprocessors and 4608 cores, and it utilizes the GPU with a max utilization of ~10%, can I assume that 10% of the streaming multiprocessors (so roughly 7) are being used? So, therefore, roughly ~900 CUDA cores are being used? (I'm basing this off of this answer: https://superuser.com/questions/1109695/how-to-determine-number-of-gpu-cores-being-utilized-for-a-process)
As a result, if I downgrade to a lower GPU with 3000 CUDA cores, it should theoretically still be able to perform inference at the same 0.5 seconds speed right?

A: That is not a correct interpretation of utilization.  10% utilization means, roughly speaking, 10% of the time, a GPU kernel is running.  90% of the time, no GPU kernel is running.  It does not tell you anything about what that GPU kernel is doing, or how many resources it is using.  The answer given on superuser is wrong.  The correct description is here.  It is possible, as indicated there, to demonstrate 100% utilization for a GPU kernel that only uses one "core" (ie. a kernel that is only using one thread).
Regarding your question, you should not assume that there will be no change in performance whatsoever if you switch from a GPU with 4608 cores to a GPU that has 3000 cores.  First of all that is not enough information to judge performance (things like clock speed and other things matter), and secondly, if you for example assumed they were GPUs of the same generation, a GPU with 3000 cores is likely to be somewhat slower than a GPU of 4608 cores.  This is because for a given GPU architectural generation, other things like clock speed, memory bandwidth, etc. are all likely to be lower on the GPU with 3000 cores.
In short, I wouldn't assume the inference performance would be the same.  It depends on other things besides what you have indicated here.  I think it could be faster, and could also be slower, depending on the actual GPUs comparison.
With respect to CUDA GPUs that are currently available, almost anything is likely to be somewhat slower at inference performance than a Titan RTX.  The difference may be small, perhaps negligible, or larger, depending on the specific GPU.


text:
Q: Authentication fail with okhttp + ssl + basic auth I'm using okhttp3 to request some web service through SSL + basic auth using the following client builder:
client = new OkHttpClient.Builder()
    .sslSocketFactory(sslContext.getSocketFactory())
    .hostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    })
    .authenticator(new Authenticator() {
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            String credential = Credentials.basic("myuser", "mypassword");
            return response.request().newBuilder()
                    .header("Authorization", credential)
                    .build();
        }
    })
    .build()

then I run the request with
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url);
Request request = requestBuilder.build();

Call call = client.newCall(request);
Response response = call.execute();

and I get a 403 (access denied).
I tried using cURL and I get authenticated correctly.
I set a breakpoint in the authenticate  function, and it seems that it is not even called.
If I set the header directly in requestBuilder, i.e.
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url);
String credential = Credentials.basic("myuser", "mypassword");
requestBuilder.header("Authorization", credential).build();
Request request = requestBuilder.build();

Call call = client.newCall(request);
Response response = call.execute();

it works.
Any suggestion?


text:
Q: Svelteki api fetch pages In short, I want to fetch data from diferents pages from one API I've made.
The API is https://joao-back-ecommerce-prod.herokuapp.com/store/ and as you can see I've multiples endpoints.
With svelte i'm trying to go from page to page in one click with increment function.
exemple:

    {#each products as product}

            {product.title} - {product.description}
            hlmlll

    {/each}
    <button on:click={next}>Next</button>

I want to go to next page when click on button next. I thought that with increment id + 1 it will be work, but, it doesn't.
In the browser when I change the page number it works.
Any help?

A: You are just changing a local variable, it does not affect the url.
What you would do is navigate to the next page by changing the url.
There are two ways to do this:
import { goto } from '$app/navigation';
const next = () => goto(`/product/${id+1}`); // change to get correct path for you

or, a better way is to actually just link to the next page instead:
Next

The second option is preferred because you are in fact navigating for which you should use a link (buttons are for actions), it will also work if the user has javascript disabled.
SvelteKit will not actually go to the server and load a new page, it will just fetch the data from the load function and update accordingly, the user will not notice they are on a different page, only the url changes.


text:
Q: logout of keycloak gatekeeper using python requests sessions using browser
everything works find if i login and logout using the browser
eg. i login using the keycloak form
and i logout by pasting the following in the browser
{}/oauth/logout?redirect={}/auth/realms/{}/protocol/openid-connect/logout

when i check the keycloak admin page, the session is removed as expected
using python requests sessions
i login using the following
r = self.session.post(
    "{}/oauth/login".format(self.host),
    data={"username": username, "password": password},
    verify=False
)

this works and when i try to access any endpoints i am able to after login
i logout using the following
url = "{}/oauth/logout?redirect={}/auth/realms/{}/protocol/openid-connect/logout".format(
    self.host,
    self.host,
    self.realm_name
)
r = self.session.get(
    url,
    allow_redirects=True,
    verify=False,
)

this logs me out of gatekeeper and clears the cookies (i cant acccess and endpoints which is correct), however in the keycloak admin page, i still see my session active.
the cookies should have been kept in the session, anyone knows why? thanks
Edit:
i think its because when i login through gatekeeper using the endpoint
/oauth/login

it does not return these 3 cookies which i get when i use the browser
AUTH_SESSION
KEYCLOAK_IDENTITY
KEYCLOAK_SESSION

these 3 cookies come from the endpoint
https://{}/auth/realms/{}/protocol/openid-connect/token

however, since i dont login through the form, i dont have these tokens


text:
Q: Pandas ValueError: Shape of passed values In the following code I iterate through a list of images and count the frequencies of a given number, in this case zeros and ones. I then write this out to a csv. This works fine when I write out the list of frequencies only, but when I try to add the filename then I get the error:
ValueError: Shape of passed values is (1, 2), indices imply (2, 2)

When I try to write out one list of frequencies (number of ones) and the filenames it works fine.
My code is as follows:
import os
from osgeo import gdal
import pandas as pd
import numpy as np

# Input directory to the .kea files
InDir = "inDirectory"

# Make a list of the files
files = [file for file in os.listdir(InDir) if file.endswith('.kea')]

# Create empty list to store the counts
ZeroValues = []
OneValues = []

# Iterate through each kea file and open it
for file in files:
    print('opening ' + file)
    # Open file
    ds = gdal.Open(os.path.join(InDir, file))
    # Specify the image band
    band = ds.GetRasterBand(1)
    # Read the pixel values as an array
    arr = band.ReadAsArray()
    # remove values that are not equal (!=) to 0 (no data)
    ZeroPixels = arr[arr==0]
    OnePixels = arr[arr==1]
    print('Number of 0 pixels = ' + str(len(ZeroPixels)))
    print('Number of 1 pixels = ' + str(len(OnePixels)))
    # Count the number of values in the array (length) and add to the list
    ZeroValues.append(len(ZeroPixels))
    OneValues.append(len(OnePixels))
    # Close file
    ds = Non

# Pandas datagram and out to csv
out = pd.DataFrame(ZeroValues, OneValues, files)
# Write the pandas dataframe to a csv
out.to_csv("out.csv", header=False, index=files)

A: Pandas thinks you're trying to pass OneValues and files as positional index and columns arguments.  See docs.
Try wrapping your fields in a dict:
import pandas as pd

ZeroValues = [2,3,4]
OneValues = [5,6,7]
files = ["A.kea","B.kea","C.kea"]

df = pd.DataFrame(dict(zero_vals=ZeroValues, one_vals=OneValues, fname=files))

Output:
   fname  one_vals  zero_vals
0  A.kea         5          2
1  B.kea         6          3
2  C.kea         7          4


text:
Q: How to call controller within another conroller in cakephp I am using cakephp v2.6 to develop a web app.
Is it possible to call a controller within another controller in CAKEPHP.
Is it correct way for doing the same
In SecondController.php
App::uses('FirstController','Controller');

class SecondController extends AppController
{
$firstcontrollerobject=$this->FirstController;
}

Thanqs

A: Put PHP code in the Component, if you want to share between several controllers

Components are packages of logic that are shared between controllers. CakePHP comes with a fantastic set of core components you can use to aid in various common tasks. You can also create your own components. If you find yourself wanting to copy and paste things between controllers, you should consider creating your own component to contain the functionality. Creating components keeps controller code clean and allows you to reuse code between projects.

http://book.cakephp.org/2.0/en/controllers/components.html

A: Short answer is Yes, but you shouldn't.
You should use either a component or a model. Or put your action in AppController if you want it to be used by other controllers.
App::uses('FirstController','Controller');

class SecondController extends AppController
{
    public function test() {
        $FirstController = new FirstController();
        $Firstcontroller->action();
    }

}


text:
Q: Bluemix: MQA : how to make phone shake harder in android to report bug and feedback I am trying to integrate Bluemix MQA with my mobile app. I am using the MQA-Android-2.7.4.arr file in my project. I have one query related to phone-shake as below.
How do I make the phone shake harder in Android to report a bug as slight shaking is also popping up the screen multiple times?

A: Android devices have different accelerometers and the same algorithm appears to have different effects on each. I'm creating a request for enhancement to add a shake threshold slider for the shake gesture.


text:
Q: Matplotlib axis custom intervals For a plot, I need the y-axis to be between -800 and +20 with evenly spaced intervals intervals for approximately the following ranges:
-1000 to -100, -100 to -50, -50 to -20, -20 to 0, 0 to +20
How can I do this? plt.yscale only allows using predefined scales like linear, log etc. as far as I know. I couldn't find how to create a custom scale.
I'm fine with some flexibility in the division of the y-axis but need it to roughly respect that. I'm even okay with using purely the log base 10 scale with plt.yscale('log',basey=10), but this doesn't allow me to get negative numbers on the axis.
EDIT: using plt.yscale('symlog',basey=10) solves the problem of plotting negative log intervals. But if I did want to do it, how would I have a custom scale?


text:
Q: Excel - Finding all values in one column for unique values in another column I have an Excel table that looks like this:
Code | Description
-------------------------
A    | Desc1
A    | Desc2
B    | Desc3
C    | Desc4
C    | Desc5
C    | Desc6
...

I need to find all the Descriptions for each unique Code.  For example I want a table that looks like this:
Code | Description1 | Description2 | Description3
-----------------------------------------------------
A    | Desc1        | Desc2        |
B    | Desc3        |              |
C    | Desc4        | Desc5        | Desc6

Is there a way to do this in Excel?  I tried Pivot Tables, but had no luck.

A: If your data is in A1:B7 including headers as you show, enter whatever headers you want in C1:F1, but make sure the Code column values you are looking for is in C2 and going down. Like C3 = B and C4 = D. If you don't know all the Code column values there is a simple unique extract formula that can get them from the Code column for you.
In C2 enter this formula with Ctrl+Shift+Enter keys
=INDEX($A$2:$A$7, MATCH(0, COUNTIF($C$1:$C1, $A$2:$A$7), 0))

In D2 enter this formula with Ctrl+Shift+Enter keys and then you can drag it to the right and down to populate your new table.
=IFERROR(INDEX($B$2:$B$7, MATCH(0, COUNTIF($C2:C2,$B$2:$B$7)+IF($A$2:$A$7<>$C2, 1, 0), 0)), 0)

Currently this will display a 0 in cells that do not have any new description to display.
This also will only work if your original data is sorted by the Code column.Edit- Nevermind, it does work with unsorted values.
I hope this helps.
EDIT* Added a Photo
Read more about this formula combo here ► How to extract a unique distinct list from a column in excel


text:
Q: passing array as argument in java i wants to pass array as arguments to sub class from main . but looks like its not initialized.Please have a look on below and advice where i am wrong.
Thanks in Advance
    class arraymain{
    public static void main(String[] arg){

        Array obj=new Array();
        obj.passArray(new int[]{1,2,3,4,5},4);
    }
    }
 class Array{
 void passArray(int[] values,int size){

   values=new int[size];
        for (int num=0;num<values.length;num++){
            System.out.println(values[num]);

        }
    }

}
OUPTPUT:
0
0
0
0

A: values=new int[size];

You are initializing a new array, overwriting the passed parameter.
When creating a new array this way, all values are initialized with their default values, for int this happens to be 0.
Simply remove this line, and the code should work as intended.
And, as a comment points out, this makes the parameter size unused. The length of the array is derived directly from the array, as you already do in your code.

A: You need to remove values=new int[size]; from your Array class.
You are getting values as parameter, and then you are doing this values=new int[size];, which creates a new array, and this new array has no values (default values 0).

A: The problem is the line
values=new int[size]

You are creating a new array, and thereby you are hiding the one with non-0 values.


text:
Q: Converting date.toString() to date I'm trying to convert a string to a date. I've got an example here with the input string as hardcoded string.
try {
    String currentDate = "Tue Jan 05 21:19:57 CET 2016";
    Date d = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse(currentDate);
} catch (ParseException e) {
    e.printStackTrace();
}

For some reason, this throws the following exception:
ParseException: Unparseable date: "Tue Jan 05 21:19:57 CET 2016" (at offset 20)

Could someone help me with this problem? Thanks!

A: Your problem is described her java.text.ParseException: Unparseable date
Your machine Local can effect the local that used in SimpleDateFormat


text:
Q: Wiring power banks in series for 25V output to power e-bike So I have an old electric bike sitting around, no battery. Replacement 24V 10Ah batteries are $200+. However, I have/can get 10Ah power banks (to charge phones) for under $10. They all have standard 5V 2A outputs. Same brand and model. Bike is an ancient Ezip eco ride; 250W motor.
Can I wire 5 power packs in series to get a ~24-25V output? I can't do it via the USB ports, because I can't pass voltage back through the USB port - it overloads and shuts down.
I'm afraid of opening the power packs and wiring the batteries directly, because the PCBs are still connected and might get damaged.
Assume I disconnect the PCBs from the batteries before wiring them in series. Also assume I time the battery usage so they don't over-discharge. What's the chance this will go up in flames, Note 7 style?
If you're gonna call me an idiot for even suggesting this, please do so kindly. Thanks! ^_^

A: Your power banks provide 5V 2A output or 10W, and cost about $10. To power a 250W motor, you'll need 25 power banks which will cost you $250. Why not just buy a $200 battery then?
Also, think how bulky those 25 power banks will be on your bike, and what a pain they will be to charge.
Hopefully these simple arguments are enough to persuade you, before I'll have to explain all the balancing issues you'll face once you connect Li-ion cells in series, or consider custom charging circuits you'll need to design if you remove the original PCBs.


text: Q: Does macOS have a switch for not charging battery when power adapter plugged in? macOS has battery health management and it may stop charging when battery is 80%, then it uses power adapter only for operation of my macOS. I wonder is there a switch for flip this on whatever the battery power percentage is? If not, are there related APIs for coding a new Application for this switch?


text:
Q: Chronicle Bytes from InputStream I'm trying to use saxophone for parsing json to protobuf message on the fly, and want to avoid creating string instances for each response.
For that i need to create Bytes instance from InputStream (that is provided from apache http entity).
I'm digging sources for a while but cant find way to do that... any suggestions?

A: There is two ways you can do this.
// reuse a string builder if the String cannot be pooled easily
stringBuilder.setLength(0);
bytes.parseUTF(stringBuilder, StopCharTesters.ALL);

or you can use the built in String pool
String s = bytes.parseUTF(StopCharTesters.ALL);

This will work well if there is a relative small number of possible Strings (at least most of the time)


text:
Q: Add non-friend tester by Facebook ID to Facebook app I am developing a Facebook app for a client. I want to add the client as a tester to the Facebook app so he can play around with it and give me feedback. The client and I are not friends on Facebook, so I am trying to add him by his Facebook ID, as instructed in the Add Tester modal.
Add Testers Dialog
When I enter his ID, I get a red x with the error message: "XXXXXXXXXXXX could not be resolved to a valid user ID or name." I have checked that the Facebook ID he gave me is correct via the Facebook Graph API Explorer.
How do I add him using his Facebook ID and get around this problem?

A: It seems that one must use the username of a person who is not their friend to register that person as a tester for your app. (Thanks @CBroe for asking me to try that.)
Unfortunately, the username field is deprecated in the Facebook Graph API for versions 2.0 and higher:
{
    {
  "error": {
    "message": "(#12) username field is deprecated for versions v2.0 and higher",
    "type": "OAuthException",
    "code": 12,
    "fbtrace_id": "GnJd8sMSb7l"
  }
}

As far as I can tell, the best way to get the username from Facebook ID is to browse to https://www.facebook.com/{id} and grab the username from the redirected url, which will be https://www.facebook.com/{username}.


text:
Q: Customizing Sharepoint Online Login Branding Our SharePoint online/Office 365 cloud instance has received Microsoft's final push to remove the "old experience" to logging in. Our users can no longer select "keep me signed in" as a result.
We tried adding company branding to the sign-in page and selecting Yes for the "Show option to remain signed in", but it doesn't seem to work. Here's the link for you to try changing it on your own instance. We've waited well past the hour implementation timeline and have tried across multiple browsers after clearing cache, etc etc.

I'm wondering if this custom company branding was intended for the "old experience" and not the new. Anybody out there had success adding that remain signed in checkbox in the new experience?

A: Microsoft Office 365 is replacing the "keep me signed in" checkbox with a prompt that displays after the user successfully signs in. This prompt asks the user if they'd like to remain signed in. If a user responds "Yes" to this prompt, the service gives them a persistent refresh token. This is the same behavior that currently occurs when a user checks the "Keep me signed in" checkbox. For federated tenants, this prompt will show after the user successfully authenticates with the federated identity service.

Admins can choose to hide this new prompt for users by using the "Show option to remain signed in" setting in company branding.
Refer to: The new "Keep me signed in" experience for Azure AD is in preview


text:
Q: How do I control the axis labels on a ggvis plot where the variables to be plotted are selected interactively? I am trying to create an interactive visualization with the ggvis package.
Specifically, the user should be able to select which of the variables should be plotted on which axes. One way to do this was already presented in answer 2 of this question. However in this solution the axes are not labeled correctly:
E.g. in this example
library("ggvis")
library("magrittr")
sel <- input_select(names(mtcars),map=as.name)
mtcars %>% ggvis(sel,~mpg) %>% layer_points()

The y-axis has a label of "reactive_x" (x being a random number).
I would now like to label the y-axis according to the currently selected variable. Adding
%>% add_axis("y",title=sel)

does not work because sel is a closure, not a character vector. Wrapping sel in as.character does not work either.
Does anybody have a solution to this problem?
Note: This would possibly easier to solve by wrapping the ggvis plot in a shiny app. However, I am not interested in such solutions as this visualization will be part of a package that I am developing.


text:
Q: Show Bootstrap Responsively I'm new to Laravel and I have a project, I would like the "Nav" to be shown on the phone just as it does on a computer or notebook.
My Notebook:
1º 2º 3º

My Phone:
1º
2º
3º

My Ex Code:

    1º
    2º
    3º

ex:1º

ex:2º

ex:3º

A: This is a matter of adding the correct amount of columns inside of a row.
You should check out the Grid System
https://getbootstrap.com/docs/4.0/layout/grid/

            1º

            2º

            3º

A:

    1º
    2º
    3º

By the above code it has column size of 33.33%(col-4) on all screen sizes and the data 1º, 2º, 3º will be aligned on the same row.
You can learn about the row and column (Grid-system) in Bootstrap.
Or if you want to continue only with HTML and CSS then learn about float{} in css to make it align in that way.
One more way is just to set set width to each element and float it but it looks awkward when you give more content in to a element.
So the best way is to learn with bootstrap and continue on your project.


text:
Q: Composer: Laravel/passport requires illuminate/auth ~5.3.* but locked to v5.2.45 I am trying to add lumen-passport to my Lumen project via the following command composer require dusterio/lumen-passport but is being halted due to my illuminate/auth version.
Problem 1
- Installation request for dusterio/lumen-passport ^0.1.9 -> satisfiable by dusterio/lumen-passport[0.1.9].
- Conclusion: remove illuminate/auth v5.2.45
- Conclusion: don't install illuminate/auth v5.2.45
- dusterio/lumen-passport 0.1.9 requires laravel/passport >=0.2.2 -> satisfiable by laravel/passport[v0.2.2, v0.2.3, v0.2.4, v1.0.0, v1.0.1, v1.0.10, v1.0.11, v1.0.12, v1.0.13, v1.0.14, v1.0.15, v1.0.16, v1.0.17, v1.0.2, v1.0.3, v1.0.4, v1.0.5, v1.0.6, v1.0.7, v1.0.8, v1.0.9, v2.0.0, v2.0.1, v2.0.2, v2.0.3, v2.0.4].
- laravel/passport v0.2.2 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v0.2.3 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v0.2.4 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.0 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.1 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.10 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.11 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.12 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.13 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.14 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.15 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.16 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.17 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.2 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.3 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.4 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.5 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.6 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.7 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.8 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v1.0.9 requires illuminate/auth ~5.3 -> satisfiable by illuminate/auth[v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.9].
- laravel/passport v2.0.0 requires illuminate/auth ~5.4 -> satisfiable by illuminate/auth[v5.4.0, v5.4.9].
- laravel/passport v2.0.1 requires illuminate/auth ~5.4 -> satisfiable by illuminate/auth[v5.4.0, v5.4.9].
- laravel/passport v2.0.2 requires illuminate/auth ~5.4 -> satisfiable by illuminate/auth[v5.4.0, v5.4.9].
- laravel/passport v2.0.3 requires illuminate/auth ~5.4 -> satisfiable by illuminate/auth[v5.4.0, v5.4.9].
- laravel/passport v2.0.4 requires illuminate/auth ~5.4 -> satisfiable by illuminate/auth[v5.4.0, v5.4.9].
- Can only install one of: illuminate/auth[v5.3.0, v5.2.45].
- Can only install one of: illuminate/auth[v5.3.16, v5.2.45].
- Can only install one of: illuminate/auth[v5.3.23, v5.2.45].
- Can only install one of: illuminate/auth[v5.3.4, v5.2.45].
- Can only install one of: illuminate/auth[v5.4.0, v5.2.45].
- Can only install one of: illuminate/auth[v5.4.9, v5.2.45].
- Installation request for illuminate/auth (locked at v5.2.45) -> satisfiable by illuminate/auth[v5.2.45].

And here is what is shown when I execute composer show
doctrine/inflector                v1.1.0  Common String Manipulations with regard to casing and singular/plural ru...
doctrine/instantiator             1.0.5   A small, lightweight utility to instantiate objects in PHP without invok...
fzaninotto/faker                  v1.6.0  Faker is a PHP library that generates fake data for you.
illuminate/auth                   v5.2.45 The Illuminate Auth package.
illuminate/broadcasting           v5.2.45 The Illuminate Broadcasting package.
illuminate/bus                    v5.2.45 The Illuminate Bus package.
illuminate/cache                  v5.2.45 The Illuminate Cache package.
illuminate/config                 v5.2.45 The Illuminate Config package.
illuminate/console                v5.2.45 The Illuminate Console package.
illuminate/container              v5.2.45 The Illuminate Container package.
illuminate/contracts              v5.2.45 The Illuminate Contracts package.
illuminate/database               v5.2.45 The Illuminate Database package.
illuminate/encryption             v5.2.45 The Illuminate Encryption package.
illuminate/events                 v5.2.45 The Illuminate Events package.
illuminate/filesystem             v5.2.45 The Illuminate Filesystem package.
illuminate/hashing                v5.2.45 The Illuminate Hashing package.
illuminate/http                   v5.2.45 The Illuminate Http package.
illuminate/pagination             v5.2.45 The Illuminate Pagination package.
illuminate/pipeline               v5.2.45 The Illuminate Pipeline package.
illuminate/queue                  v5.2.45 The Illuminate Queue package.
illuminate/session                v5.2.45 The Illuminate Session package.
illuminate/support                v5.2.45 The Illuminate Support package.
illuminate/translation            v5.2.45 The Illuminate Translation package.
illuminate/validation             v5.2.45 The Illuminate Validation package.
illuminate/view                   v5.2.45 The Illuminate View package.
laravel/lumen-framework           v5.2.9  The Laravel Lumen Framework.
monolog/monolog                   1.22.0  Sends your logs to files, sockets, inboxes, databases and various web se...
mtdowling/cron-expression         v1.2.0  CRON for PHP: Calculate the next or previous run date and determine if a...
nesbot/carbon                     1.22.1  A simple API extension for DateTime.
nikic/fast-route                  v0.7.0  Fast request router for PHP
paragonie/random_compat           v1.4.1  PHP 5.x polyfill for random_bytes() and random_int() from PHP 7
phpdocumentor/reflection-common   1.0     Common reflection classes used by             phpdocumentor to reflect the code stru...
phpdocumentor/reflection-docblock 3.1.1   With this component, a library can provide support for annotations via D...
phpdocumentor/type-resolver       0.2.1
phpspec/prophecy                  v1.6.2  Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage         2.2.4   Library that provides collection,     processing, and rendering functionalit...
phpunit/php-file-iterator         1.4.2   FilterIterator implementation that filters files based on a list of suff...
phpunit/php-text-template         1.2.1   Simple template engine.
phpunit/php-timer                 1.0.8   Utility class for timing
phpunit/php-token-stream          1.4.9   Wrapper around PHP's tokenizer extension.
phpunit/phpunit                   4.8.35  The PHP Unit Testing framework.
phpunit/phpunit-mock-objects      2.3.8   Mock Object library for PHPUnit
psr/log                           1.0.2   Common interface for logging libraries
sebastian/comparator              1.2.4   Provides the functionality to compare PHP values for equality
sebastian/diff                    1.4.1   Diff implementation
sebastian/environment             1.3.8   Provides functionality to handle HHVM/PHP environments
sebastian/exporter                1.2.2   Provides the functionality to export PHP variables for visualization
sebastian/global-state            1.1.1   Snapshotting of global state
sebastian/recursion-context       1.0.2   Provides functionality to recursively process PHP variables
sebastian/version                 1.0.6   Library that helps with managing the version number of Git-hosted PHP pr...
symfony/console                   v3.0.9  Symfony Console Component
symfony/debug                     v3.0.9  Symfony Debug Component
symfony/event-dispatcher          v3.2.4  Symfony EventDispatcher Component
symfony/finder                    v3.0.9  Symfony Finder Component
symfony/http-foundation           v3.0.9  Symfony HttpFoundation Component
symfony/http-kernel               v3.0.9  Symfony HttpKernel Component
symfony/polyfill-mbstring         v1.3.0  Symfony polyfill for the Mbstring extension
symfony/polyfill-php56            v1.3.0  Symfony polyfill backporting some PHP 5.6+ features to lower PHP versions
symfony/polyfill-util             v1.3.0  Symfony utilities for portability of PHP codes
symfony/process                   v3.0.9  Symfony Process Component
symfony/translation               v3.0.9  Symfony Translation Component
symfony/yaml                      v3.2.4  Symfony Yaml Component
vlucas/phpdotenv                  v2.4.0  Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SE...
webmozart/assert                  1.2.0   Assertions to validate method input/output with nice error messages.

And finally the composer.json
{
    "name": "laravel/lumen",
    "description": "The Laravel Lumen Framework.",
    "keywords": ["framework", "laravel", "lumen"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/lumen-framework": "5.2.*",
        "vlucas/phpdotenv": "~2.2"
    },
        "require-dev": {
        "fzaninotto/faker": "~1.4",
        "phpunit/phpunit": "~4.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/",
            "database/"
        ]
    }
}

I have the most recent version of Lumen installed v5.4.4. It seems like a laravel/passport dependency problem and not so much lumen-passport however the instructions on packagist mention that lumen-passport will be grabbed along the way.
It just seems like my version of illuminate/auth needs to be updated however the composer.lock file has it limited to v5.2.45 and for that reason I am hesitant to make any changes to the file and not overly sure how to proceed with resolving this dependency issue so I can install lumen-passport. Appreciate any help with this.

A: Are you sure that your dependencies are up to date? Check the versions you have installed with composer show.
lumen-passport 0.1.9 requires laravel/passport >=0.2.2 and this requires at least illuminate/auth ~5.3 or higher. But your illuminate/auth is locked to 5.2.45. I suggest to update at least laravel/passport or do a composer update. Make sure you have a backup before update.


text:
Q: introduce line break at the same position based on another file I have 3 input files all having the same number of lines. I have come up with a movie example to make the question look interesting.
file1.txt -- Essentially contains the actor names.
1234|jacknicholson|actor
5678|jacknicholson|director
4321|christianbale|actor

file2.txt -- Contains the movies of the actors.
1234|oneflewovercuckoosnest^asgoodasitgets
5678|theshining
4321|batmanbegins^darkknight

file3.txt -- Residence of the actors.
1234|california
5678|hollywoodstudios
4321|losangeles

I am splitting the first input file based on the condition that if names are equal, I need to apply some algorithm. The command is as below.
awk -F '|' 'NR>1 && $2 != prev {print ""} {prev=$2; print}' file1.txt

The above command will make my first file (file1.txt) as,
1234|jacknicholson|actor
5678|jacknicholson|director

4321|christianbale|actor

I need to introduce the space at the same position in the remaining 2 files too so that I can apply my algorithm.
One approach that comes to my mind is, store the position of spaces in the file1.txt in an array and then when I encounter that position in the remaining 2 files, introduce the spaces.

A: To introduce a blank line in a file at the same position as changes in actors in file1.txt, try:
$ awk -F '|' '{save=$0; getline<"file1.txt"} NR>1 && $2!=prev {print ""} {prev=$2; print save}' file2.txt
1234|oneflewovercuckoosnest^asgoodasitgets
5678|theshining

4321|batmanbegins^darkknight

The above works quite a bit like your code except that it is extended to read two files at the same time.  It reads from file2.txt and saves the line in the variable save.  If then reads from file.txt, and using the same logic as your code, determines if the actor changes and, if so, prints a line break.  It then prints the line it received from file2.txt.

A: Another awk solution:
$ awk 'FNR==NR{if(!NF){a[FNR]=1}next}a[FNR]{print"\n"$0;next}{print}' file1.txt file2.txt
1234|oneflewovercuckoosnest^asgoodasitgets
5678|theshining

4321|batmanbegins^darkknight

*

*When reading file1.txt, we mark the line number in array a if line
is blank.

*When reading file2.txt, we get line number which is blank in array
a and print a blank line before it. For other lines, we print it normally.


text:
Q: SpriteKit: White Background As SKScene I have a Swift project including the SpriteKit framework. When I run the program without anything on it, the screen is black and the node counter at 1. The Main.storyboard is entirely white and the class in it is set to SKView. Is the node counter wrong? Shouldn't it be 0 and why is the background black instead of white?
Maybe some necessary code where the mistake is:
class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let scene = GameScene() // class GameScene is a subclass of SKScene

    let skView = self.view as! SKView
    skView.showsFPS = true
    skView.showsNodeCount = true

    /* Sprite Kit applies additional optimizations to improve rendering performance */
    skView.ignoresSiblingOrder = false

    /* Set the scale mode to scale to fit the window */
    scene.scaleMode = .AspectFill
    scene.size = skView.bounds.size
    scene.anchorPoint = CGPointMake(0,0);
    skView.presentScene(scene)
}

A: Node counter is right. First of all you set the node couter for skView object with this line of code:
skView.showsNodeCount = true

Then you add object to this skView with this line:
skView.presentScene(scene)

This action set node counter to 1. Your scene is this single node on skView
About black screen: this is default background color for scene, you can change it with this code for example:
scene.backgroundColor = UIColor.redColor()

And your scene will be red


text:
Q: GLu.gluUnProject Returning NullPointerException I have gluUnProject set up to find world coordinates on touch like so:
public synchronized void randomMethod(MotionEvent event){
        if (event.getAction() == MotionEvent.ACTION_DOWN){
        setx = event.getX();
        sety = event.getY();
        vector3(null);
        }
    }

    public void vector3 (GL11 gl){

        int[] viewport = new int[4];
        float[] modelview = new float[16];
        float[] projection = new float[16];
        float winx, winy, winz;
        float[] newcoords = new float[3];

        gl.glGetIntegerv(GL11.GL_VIEWPORT, viewport, 0);
        gl.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelview, 0);
        gl.glGetFloatv(GL11.GL_PROJECTION_MATRIX, projection, 0);

        winx = (float)setx;
        winy = (float)viewport[3] - sety;
        winz = 0;

        GLU.gluUnProject(winx, winy, winz, modelview, 0, projection, 0, viewport, 0, newcoords, 0);
        posx = (int)newcoords[1];
        posy = (int)newcoords[2];
        posz = (int)newcoords[3];

    }

newcoords is then used in the draw method to draw a square at touch point.
This code returns a NullPointerException however.
07-31 20:17:40.008: ERROR/AndroidRuntime(448): Uncaught handler: thread main exiting due to uncaught exception
07-31 20:17:40.098: ERROR/AndroidRuntime(448): java.lang.NullPointerException
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at android.app.ui.GLSurfaceRenderer.vector3(GLSurfaceRenderer.java:65)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at android.app.ui.GLSurfaceRenderer.randomMethod(GLSurfaceRenderer.java:54)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at android.app.ui.Practice.onTouchEvent(Practice.java:37)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at android.app.Activity.dispatchTouchEvent(Activity.java:2064)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1690)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at android.os.Looper.loop(Looper.java:123)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at android.app.ActivityThread.main(ActivityThread.java:4310)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at java.lang.reflect.Method.invokeNative(Native Method)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at java.lang.reflect.Method.invoke(Method.java:521)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
07-31 20:17:40.098: ERROR/AndroidRuntime(448):     at dalvik.system.NativeStart.main(Native Method)

Line 54 is
vector3(null);

Line 65 is
gl.glGetIntegerv(GL11.GL_VIEWPORT, viewport, 0);

and line 37 from Practice class is
glSurfaceRenderer.randomMethod(event);

which is called inside the touchEvent that randomMethod is synchronised to.
Does anybody have any idea what is causing the null pointer exception
Thank You

A: GLU.gluUnProject seems to be unrelated to the NullPointerException you get.
You are calling:
vector3(null);

so in function vector3(GL11 gl):
gl.glGetIntegerv(GL11.GL_VIEWPORT, viewport, 0);

throws the NPE because gl is null.
You need to initialize the GL11 implementation, ie:
OpenGLContext glContext = new OpenGLContext(OpenGLContext.DEPTH_BUFFER);
GL11 gl = (GL11)glContext.getGL();


text:
Q: openssl smime: aes vs rsa - which one encrypts? When I want to encrypt large files, I have found the following command:
openssl smime -encrypt -binary -aes-256-cbc \
-in large_file.img -out large_file.img.dat \
-outform DER \
public-rsa2048.pem

The private/public keys have been created like this:
openssl req -x509 -nodes -newkey rsa:2048 \
-keyout private-rsa2048.pem -out public-rsa2048.pem

So I am using aes-256-cbs as well as an rsa-key.

*

*Which one is now responsible for the encrpytion?

*Which one does impact the performance and how?

If I increase/lower the public key (rsa512 vs rsa4096), does this impact the performance?
If I choose a different aes algorithm, does this impact the performance as well?
Could someone bring some light into this matter please?

*Are there any other methods to encrypt large files?

A: Using the openssl smime command to encrypt data encrypts it in such a way that it can be received and decrypted by a recipient using email. This means that it uses certificates representing various entities (sender, recipient) and containing keys uniquely associated with those entities to both sign, encrypt, decrypt, and verify signatures on the contained data.
As Artjom pointed out in their comment, a hybrid cryptosystem is used. This means a combination of symmetric and asymmetric encryption algorithms are used, as each has benefits and drawbacks. Symmetric encryption (such as AES) is extremely fast in comparison to asymmetric encryption (such as RSA). However, AES/CBC provides only confidentiality, not integrity, authentication, or non-repudiation. Asymmetric encryption can provide integrity, authentication, and non-repudiation. Asymmetric encryption also has fairly low limits for the amount of data it can encrypt (for example, an RSA-4096 bit key can encrypt at most 446 bytes at once). By combining both methods, we can exercise each for their strengths and mitigate the weaknesses of the other.
In this case, let our message be M. An AES/CBC key Kaes of length 256 bits is generated and used to encrypt the raw data such that the cipher text C is C = E(Kaes, M). The recipient's public key Krpub is then used to encrypt Kaes as C' = E(Krpub, Kaes). The cost of encrypting this small amount of data is relatively low, even though we are using an expensive operation.
Note prior to encrypting the ephemeral session key, it is likely signed using the sender's private key Kspriv unless digital signing is disabled. I am not 100% certain with S/MIME, but this is how PGP works, as when sending to multiple recipients, it would be much more expensive to encrypt the session key with n recipient's public keys and then sign each encrypted key with the sender's private key O(2n) vs. O(n+1) (not really Big-O notation, but effective for communicating the point). The signature of the session key is the same regardless of recipient because it depends only on the sender's private key.
Now all that is left is to concatenate the encrypted session key C' and the cipher text C and transmit them to the recipient. In a real S/MIME message, the identifying information about the sender's public key is transmitted as well in order to facilitate signature verification. The recipient parses the complete encrypted message, decrypts the session key using the recipient's private key Krpriv and then uses the session key Kaes to decrypt the cipher text C.
However, it seems like all of this may be overkill for your situation. If you do not need to integrate with an email communication system and are simply trying to encrypt large files for storage, openssl also offers a simple enc command. You can use it as follows:
Password-based encryption:
$ openssl enc -aes-256-cbc -in large_plain_file.dmg -out large_encrypted_file.enc -k thisIsABadPassword
-k allows you to enter a password on the command line from which the key will be derived. OpenSSL uses a deterministic key derivation function (KDF) (effectively key, iv = MD5(password||salt)). You can run this command with -p on the end to get the key, salt, and IV printed to the console. The IV is deterministically derived from the password and salt. A KDF like PBKDF2 is recommended but the library function in OpenSSL does not expose it to the command-line tool for some reason.
Warning you can run this and specify -nosalt to skip the salt generation, but this is not recommended as it makes an already extremely weak KDF even weaker.
Keyed encryption:
$ openssl enc -aes-256-cbc -in large_plain_file.dmg -out large_encrypted_file.enc K 0123456789ABCDEFFEDCBA98765432100123456789ABCDEFFEDCBA9876543210 -IV 0123456789ABCDEFFEDCBA9876543210
Running with the actual key and IV provided. The key is 32 bytes (256 bits) and the IV is 16 bytes (the size of one AES block).
To decrypt the data, run the command with the -d flag:
$openssl enc -aes-256-cbc -d -in large_encrypted_file.dmg -out large_decrypted_file.enc
This is going to be simpler for you (no certificates/key pairs needed) and faster (no RSA encryption).
Something to keep in mind for all of this is that the password/key will be kept in terminal history if you provide it in the command invocation. Running without -k or -K will prompt the password to be entered in a secure prompt. Or use -pass to read from an environment variable, file, or file descriptor.

Update to address original questions explicitly:

*

*The AES key is responsible for encrypting the data. The RSA key is used to encrypt the AES key.

*Both impact the performance. The AES key is encrypting much more data, but is much faster than RSA encryption.

*

*Yes, changing the size of the RSA key impacts performance, (higher key sizes are slower), but for a large file this is unlikely to be the limiting factor on performance.

*Yes, changing the AES mode of operation may have a substantial impact on performance. AES/CBC, AES/OFB, and AES/CFB are similar in that they are serial operations (depending on the result of one block operation to proceed to the next), but AES/CTR operates as a stream cipher and can be parallelized to provide both encryption and decryption.

*See answer above.


text:
Q: permalink_url property, short url I get JSON from soundcloud and use permalink_url property for initializing my player. Sometimes in permalink_url used short url and I can't get data for this track by https. How and why in permalink_url was short url?
Thanks

A: Do you mean a short url something like this: http://snd.sc/abc123? If so, could you include the request which gives you that short_url? Otherwise if it's a 'normal' url like http://soundcloud.com/username/track, you can use the resolve endpoint to get the track (or user, or set, etc) data.


text:
Q: Domain Locking – Multiple Domains Noob needed some help here.
I am trying to use this code code snippets to lock a swf to couples of domain names.
var allowedDomains:String = "ghostwire.com|somewhere.net|elsewhere.org";

var allowedPattern:String = "^http(|s)://("+allowedDomains+")/";
var domainCheck:RegExp = new RegExp(allowedPattern,"i");
if (!domainCheck.test(url))
{
    // domain check failed, abort application
    stop();
    // abort();
}
else
{
    // domain okay, proceed
}

problem is even when I add my sites like:
var allowedDomains:String = "mysite.nl|mysite.de|mysite.co.uk";
The swf use the abort() function.
This one works grab the domain URL alright. But There isn't a way to add Multiple Domains
var url:String = stage.loaderInfo.url;
            var goodPattern:RegExp = /^(http:\/\/)(www\.)?mysite\.nl/;
            if (goodPattern.test(url) == true)
            {
                trace("This flash is hosted on mysite");
            }
            else
            {
                trace("This flash is not hosted on mysite");
                this.alpha = 0;
            };

The above snippets works.
But then given me two other issues.
1: I cant add more then one domain name.
2: after code obfuscated, the stage get nulled, soo when try to play the swf i get a debugger error.
TypeError: Error #1009: null object
can somebody please tell me what I am doing wrong here!!!
original link here:
PS: I am a newbie, and not banned from here.
I just couldn't find my older details, and when trying to get the script to sent me a new details via e-mail, I got a message that used email which was good, wasn't into this database.
soo I a message was promp to use my google account which I did, sorry If this was wrong.
Hope to get some help consern my thread.
Thanks in advance

A: In your second code, to check the domain you use slightly different regex, which looks for 'www', maybe try this:
var allowedDomains:String = "mysite\\.nl|mysite\\.de|mysite\\.co\\.uk";
var allowedPattern:String = "^http(|s)://(www\\.)?("+allowedDomains+")/";


text:
Q: Expo android build fails I'm trying to build an android app with expo build:android and it keeps failing every time even though i've tried everything on SO and google.
As I can see it says that app icon is not png but i've checked it multiple times and i'm pretty sure it is.
Any idea how to fix this?
Thanks in advance


text:
Q: Writing from pandas dataframe to DataBricks database table I have a database table in Azure DataBricks that already has data in it - I need to append data to that table.
I have my pandas dataframe (df_allfeatures) that I want to append to my database
The function that I use to write to my database table:
def write_to_delta(df_name, db_name, table_name, write_mode, num_part=10):
    df_name \
        .repartition(num_part) \
        .write \
        .mode(write_mode) \
        .insertInto("{}.{}".format(db_name, table_name), overwrite=True)

When using this function to write into by database:
df_allfeatures = spark.createDataFrame(df_allfeatures)
write_to_delta(df_allfeatures, 'production', 'feed_to_output_all_features', 'append', num_part=10)

However I keep getting the error "
AnalysisException: Cannot write incompatible data to table 'production.feed_to_output_all_features': "
The columns that are singled out are the following:
"AnalysisException: Cannot write incompatible data to table 'production.feed_to_output_all_features':

*

*Cannot safely cast 'LEAD_CONCENTRATE_GRADES_PB': string to double

*Cannot safely cast 'TAILINGS_RECOVERIES_PB': timestamp to double

*Cannot safely cast 'DATE': double to timestamp"

I have already changed the datatypes to rectify this error:
df_allfeatures = df_allfeatures.astype({"LEAD_CONCENTRATE_GRADES_PB": 'float32'})
df_allfeatures = df_allfeatures.astype({"TAILINGS_RECOVERIES_PB": 'float32'})
df_allfeatures['DATE'] = pd.to_datetime(df_allfeatures['DATE'])

But I keep getting the same error

A: Follow below ways to convert string datatype to double.
Following are some PySpark examples that convert String Type to Double Type
#Using withColumn() examples
df.withColumn("salary",df.salary.cast('double'))
df.withColumn("salary",df.salary.cast(DoubleType()))
df.withColumn("salary",col("salary").cast('double'))

# Rounds it to 2 digits
df.withColumn("salary",round(df.salary.cast(DoubleType()),2))

# Using select
df.select("firstname",col("salary").cast('double').alias("salary"))

# Using select expression
df.selectExpr("firstname","cast(salary as double) salary")

# using SQL to Cast
spark.sql("SELECT firstname,DOUBLE(salary) as salary from CastExample")

For more such examples follow this link - PySpark Convert String Type to Double Type


text:
Q: How to move background with keys in pygame I am trying to make a game with pygame where the player is fixed in the center of the map. When you press a key, the background moves instead of the player, but I've only managed to do that on the x-axis. When implementing it on the y-axis, the background goes crazy.
for event in pygame.event.get():

            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        pulsar = pygame.key.get_pressed()
        if pulsar[pygame.K_a] or pulsar[pygame.K_LEFT]:

            x += 2
        if pulsar[pygame.K_d] or pulsar[pygame.K_RIGHT]:

            x -= 2

        x_relativa = x % bg.get_rect().width
        screen.blit(bg, (x_relativa - bg.get_rect().width, y))

        if x_relativa < width:
            screen.blit(bg, (x_relativa, 0))

This code shows how I make the background scroll on the x-axis with the A and D keys. Changing these values to the y-axis also works independently but not at the same time

A: I don't exactly understand how your code works, but I do know that the following works:
for event in pygame.event.get():
    if event.type==QUIT:
        running=False
presseds=pygame.key.get_pressed()
if presseds[K_UP] or presseds[K_w]:
    bgrect.y+=5
if presseds[K_DOWN] or presseds[K_s]:
    bgrect.y-=5
if presseds[K_RIGHT] or presseds[K_d]:
    bgrect.x-=5
if presseds[K_LEFT] or presseds[K_a]:
    bgrect.x+=5
screen.fill((0,0,0))
screen.blit(bg,bgrect)

In this code, bgrect is the rect of your background's surface.


text:
Q: How to loop program so it continues execution I currently have this code
#include <iostream>
#include <curl.h>
#include <windows.h>
#include "boost\timer.hpp"

int main(void)
{
    CURL *curl;
    CURLcode res;
    boost::timer t;

    int number = 1;

    while (number == 1)
    {
         if(t.elapsed() > 10)
         {
            curl = curl_easy_init();
            if(curl)
            {
                curl_easy_setopt(curl, CURLOPT_URL, "http://google.com");
                res = curl_easy_perform(curl);

                /* always cleanup */
                curl_easy_cleanup(curl);
            }
            t.restart();
         }
      }
}

What i'd like it to do is continue execution of this program and never end until someone closes the window.
I tried the aforementioned code, however CPU usage spiked to 25% on my quad core CPU.
So how do i continue the execution of the program and loop the code within the while without using so much CPU?
P.S
25% on a quad core means 100% cpu usage on a single core CPU.

A: You can use Sleep(10000) to pause program execution for approx. 10 seconds. You can drop the boost::timer - just sleep 10 seconds in each loop iteration (Sleep is not as accurate, but for 10 seconds the inaccuracy should be negligible).
Your code is what is called a 'busy loop' - for the CPU it makes no difference whether you hang around in a tight loop without much work or do heavy computations. Both will use 100% of a CPU core because there's an neverending stream of instructions coming in. To use less, you need to relinquish execution for a while to let the OS execute other processes.

A: What you're currently doing is busy waiting. That is, even though your program doesn't need to do anything, it's still keeping that loop spinning, waiting for the timer. What you need to do is to execute a true sleep, which tells your operating system that the process doesn't need to do anything for the next 10 seconds.
One way to do a true sleep in boost is the boost::this_thread::sleep function.

A: If need to slow it down with some sleep().  Basically you need to put your thread to sleep to allow other processes to execute.

A: What you've implemented is called a busy wait and is considered very bad style. Use sleep to suspend program execution for a short time, and write an eternal loop as:
for (;;)

or
while (true)

A: Looks like you want to do a sleep after each  operations.

A: You can boost::threads to run it in it's own thread and then do a thread.join in the main thread to wait for it.  If the other thread never ends, because of a while(true) then you program will run until you close the window.

A: Call SwitchToThread() inside of your while loop. (Sleep is less than ideal, as it forfeits the current time slice even if no other thread needs it.)

A: Consider using a timer instead of doing such a tight loop.
Alternatively you can put a System.Threading.Thread.Sleep(300) in between.
Someone would have to kill your process to close it, I cannot discern any window in your code.
If you are polling a website (it looks like you are doing something with Google there) then I would advise you to make a much larger interval! Not many a web-master would be happy to see such activity. It's more likely to be seen as a DOS-attack!
Any way, if there's a window, rather put this code in a timer delegate, otherwise start a timer and allow the user to exit your program somehow (maybe with Console.ReadKey() or so).


text:
Q: What is the best way to append a vector of ones? int n = get_n();
std::vector<int64_t> v{4};
// append n 1s to v here?

I usually just create a vector of ones and move:
std::vector<int64_t> ones(n, 1);
std::move(ones.begin(), ones.end(), std::back_inserter(v));

Is there a better approach than what I have done here?

A: std::vector::resize has the second optional argument for a default value of newly inserted elements, so you can do
v.resize(v.size() + n, 1);

to add n ones.
This is likely to be more efficient than any code that uses std::back_inserter(v) because no capacity checks will be made at each insertion and at most one reallocation will happen.

A: Another approach, that doesn't depend on std::back_inserter(v), uses one of the overloads of std::vector::insert, which accepts a count parameter:
v.insert(v.end(), n, 1);

Its complexity, in this case, should be linear in n (plus the possible reallocation), like std::vector::resize.

A: I would use std::fill_n.
#include <algorithm>
#include <iterator>
std::fill_n(std::back_inserter(v), n, 1);


text:
Q: HTML Table Isn't Using Bootstrap Formatting As Per kableExtra I would like to create a striped html table.  As you can see in this picture, it is not formatting as desired.  Any tips on how to fix this?
EDIT: I think it has something to do with the doc setup - as at one point it was coming out with the stripes.  I'm not sure what change I made that caused the problem
---
title: "Creating a Draft Pick Value Chart"
author: "Tirdod Behbehani"
date: July 5, 2021
output:
  html_document:
    keep_md: true
always_allow_html: true
tables: true
---

```r
library(knitr)
library(kableExtra)

knitr::kable(list(round1, round2),
             caption = "NBA Draft Pick Value Table",
             col.names = c("Pick Number", "Pick Value"),
             format = 'html') %>%
  kable_styling(bootstrap_options = "striped", full_width = FALSE, position="left")
```

A: When I use output: rmarkdown::github_document and always_allow_html: true the stripes from kable_styling() show up.  Thank you!


text:
Q: A precise formula for the summation of an inner product We have $2$ strings $|v\rangle$ and $\langle u|$,
String $-1$ :
$$|v\rangle=|e_{1}\rangle^{np}|e_{2}\rangle^{n(1-p)}$$

where :
$e_{1}$ occurs $np$ times
$e_{2}$ occurs $n(1-p)$ times

String $-2$ :
$$\langle u|=\langle f_{1}|^{nq}\langle f_{2}|^{n(1-q)}$$

where :
$f_{1}$ occurs $nq$ times
$f_{2}$ occurs $n(1-q)$ times

Note that here  $e_{1}, e_{2}$ form an orthonormal basis and so do $f_{1}$ and $f_{2}$.
$p$ and $q$ are probabilities therefore $np,nq$ etc can be a decimal, in this case they would be rounded off to the nearest whole number. Let $|v_{s}\rangle$ be a permuted version of of $|v \rangle$ and let $\langle u_{s'}|$ be a permuted form of $\langle u|$
Now an inner product is formed $\langle u_{s'}|v_{s}\rangle$. Basically every permutation of $|v\rangle$ is combined with every other permutation of $\langle u|$ to form the inner product.
I want to be able to find a formula for $\Sigma_{s,s^{'}}\langle u_{s'}|v_{s}\rangle$ where the summation is on the number of permutations of $|v\rangle$ and $\langle u|$.
How can we find this in general? The summation should be a function of $p$ , $q$ and $n$. Basically in $\Sigma_{s,s^{'}}\langle u_{s'}|v_{s}\rangle$ how many $\langle e_{1}|f_{1}\rangle$, $\langle e_{2}|f_{1}\rangle$, $\langle e_{2}|f_{2}\rangle$, $\langle e_{1}|f_{2}\rangle$ are there? Their numbers should be a function of $n$ , $p$ , $q$
I could find this in code for a given $n$ , $p$ and $q$. But I need a general formula for this mathematically for any $n$ , $p$ and $q$. What would be the formula in case of $n$ going to infinity?


text:
Q: Unable to copy actual files on remote using git-annex I currently want to deploy my existing git-annex repository on a new computer.
My configuration is the following one:

*

*on serverA: I have a git bare (with git-annex) repository and no actual files

*on serverB: I have an classical git-annex local folder which contains the actual (heavy) files (synced with serverA's repository)

*on serverC: I want to create a new git-annex repository and copy the files from serverB on it

Notice that I am not able to clone directly from serverBon serverC.
I follow the process:

*

*on serverC: git clone ssh://serverA/<path> after I run  git annex init origin and git annex sync

*on serverB: git remote add NEW ssh://serverC/<path>, git annex sync NEW and it works. But when I want to copy the actual (heavy) files using git annex sync NEW --content, no file are copied and I have for each file the following error: copy <file> (unable to check NEW) failed.

Any idea of the raeson of these errors (notice that debug mode provide no additional information)?
Notice that all servers use version 8.xx of git-annex


text:
Q: Angular2 Redirect after login segment dont exist Im currently trying to make it navigate to /minions component to get access to the regular outlet, means the outlet to be used while logged in.
How can i make this redirection work?
in ngOnInit in loginhandler class ( aka /login) i do have the following:
 ngOnInit() {
    this.CoreService.isLoggedin().subscribe(data => {
     if (data) {
       console.log("redirect... from login");
       this.Router.navigate(["/minions"]);
     }

    });

  }

but that results in:
Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'minions'

app.module.ts routing:
RouterModule.forRoot([

          {
            path : 'minions',
            component: MinionsComponent,
            outlet: 'regular'

          },
          {
            path: '',
            redirectTo : 'login' ,
            pathMatch: 'full'
          },
          {
            path: 'login',
            component: LoginhandlerComponent,
          },

        ]

    )

Body:
 {{ user  }}

        minions

        <router-outlet name="regular"></router-outlet>

{{ user.username }}

  Login

    <router-outlet></router-outlet>

A: In your routing code you are using outlet as regular so you should pass the value like below
this.router.navigate(['/', {outlets: {'regular': "minions"}}]);


text:
Q: How can I not have the initial HTML template rendered when using a PhoneJS dx-gallery widget and a template? I am experimenting with the AngularJS approach for PhoneJS. So far I am really enjoying both frameworks.
Current issues:

*

*Using a dx-gallery or dx-list with a datasource and a template will cause the initial un-bound template to be rendered when the view is navigated.

I found this out once I started using the dx-gallery widget and specifying a template.   The console will show a network request for the initial template (not bound) being requested.
Code

Question:
How can I not have the initial HTML template rendered when using a PhoneJS dx-gallery widget and a template?

A: Use ns-src binding instead of specifing src directly:

Check out link https://docs.angularjs.org/api/ng/directive/ngSrc


text:
Q: $AB-I$ is a projection means $BA-I$ is so? $(AB-I) \text{ is a projection}
\Rightarrow (AB-I)^2=AB-I \Rightarrow AB.AB-AB-AB+I=AB-I\\
AB^2A-3AB-3I=0\\
(BA-I)^2= BA^2B-2BA+I$
they are complex matrices. please help

A: I suppose that both $A$ and $B$ are square matrices. Let $P=AB-I$. Since $Px=-x$ on $\ker B$ but the only possible eigenvalues of a projection are zeroes and ones, we must have $\ker B=0$, i.e. $B$ is invertible. Hence $BA-I=B(AB-I)B^{-1}$ is also a projection.
We have used $-1\ne1$ in the above. The proof actually works over any field of characteristic $\ne2$. When the characteristic is $2$, the statement in question no longer holds. E.g. over $GF(2)$,
$$
\pmatrix{1&0\\ 0&0}\pmatrix{0&0\\ 1&0}-I=I
$$
is a projection, but
$$
\pmatrix{0&0\\ 1&0}\pmatrix{1&0\\ 0&0}-I=\pmatrix{1&0\\ 1&1}
$$
is not.

A: This is true assuming $A,B$ are square matrices.
We have $(AB-I)^2=AB-I$, so $ABAB-3AB=-2I,A(BAB-3B)=-2I$, so $-\frac{1}{2}(BAB-3B)$ is the inverse of $A$. Hence $(BAB-3B)A=-2I,BABA-3BA=-2I$ and $(BA-I)^2=BA-I$.
If we allow non-square matrices, then we can find a counterexample by using $A = (0\, 1)$ and $B=A^T$. Then $AB-I=(0)$ clearly is a projection, but $BA-I$ isn't.


text:
Q: Maven "Skipping javadoc generation" WHY? I'm working on a maven project and want to generate the most basic of javadocs.
This is the plugin I add to my pom.xml
<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.8.1</version>
        <executions>
            <execution>
                <id>attach-javadocs</id>
                <phase>package</phase>
                <goals>
                    <goal>jar</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>
</build>

I then run the goal mvn clean package and after successfully cleaning and packaging my project it says
[INFO] --- maven-javadoc-plugin:2.8.1:jar (attach-javadocs) @ project-name ---
[INFO] Skipping javadoc generation.

I've tried adding the property:
<properties>
    <maven.javadoc.skip>false</maven.javadoc.skip>
</properties>

And have also tried this in cmd prompt:
mvn clean package -Dmaven.javadoc.skip=false

No different...
Anything I am blatantly missing?

A: see the effective pom of your project either on the command line by typing mvn help:effective-pom or through eclipse effective-pom view of your pom. That will give you the true configuration.
If the flag is set to true, then:

*

*are you adding the configuration in an inactive profile? check mvn help:active-profiles

*do you have pom inheritance and inheriting the configuration from the parents? check parent poms

I don't think that changing the version will help you much as the "skip" parameter was available from version 2.5

A: You must use
-Dmaven.javadoc.skip=true <--  to skip javadoc
-Dmaven.javadoc.skip=false <<-- do not skip


text:
Q: Multiple shapes created dynamically with ActionScript 3 I am trying to create animation in AS dynamically. I want to create multiple shapes which will animate one by one. So, first, one shape is created and animated from dot1. After that second shape should be made and animate to dot2. Number array hold positions of the dots. I use drawLine function to draw line. Before that I set 10 dots. In string fullDate I hold list of dots. Result of this code is only the first animation. I think that code does not generate well new shape, so animation finishes after first animation. Has anyone idea how to fix this issue? Thanks in advance!
  import flash.display.Shape;

var startPoint:Point = new Point();
var endPoint:Point = new Point();

var prog:Number = 0;
var bonus:Number = 1;
var frames:int = 150;

var numbers:Array = new Array();

numbers[0] = new Array();
numbers[0][0] = 460;
numbers[0][1] = 100;

numbers[1] = new Array();
numbers[1][0] = 10;
numbers[1][1] = 20;

numbers[2] = new Array();
numbers[2][0] = 10;
numbers[2][1] = 100;

numbers[3] = new Array();
numbers[3][0] = 10;
numbers[3][1] = 180;

numbers[4] = new Array();
numbers[4][0] = 160;
numbers[4][1] = 20;

numbers[5] = new Array();
numbers[5][0] = 160;
numbers[5][1] = 100;

numbers[6] = new Array();
numbers[6][0] = 160;
numbers[6][1] = 180;

numbers[7] = new Array();
numbers[7][0] = 310;
numbers[7][1] = 20;

numbers[8] = new Array();
numbers[8][0] = 310;
numbers[8][1] = 100;

numbers[9] = new Array();
numbers[9][0] = 310;
numbers[9][1] = 180;

var fullDate:String = "271524";

var i:Number;
var pom:Number;
var shapes:Vector.<Shape> = new Vector.<Shape>();
for (i=0; i < fullDate.length; i++){

    pom = int(fullDate.charAt(i));
    shapes[i] = new Shape();
    addChild(shapes[i]);

    trace(numbers[pom+1][0]);
    drawLine(numbers[pom][0], numbers[pom][1], numbers[pom+1][0], numbers[pom+1][1], 120);
}

function drawLine(startX:Number, startY:Number, endX:Number, endY:Number, time:Number = 120):void {
    startPoint.x = startX;
    startPoint.y = startY;
    endPoint.x = endX;
    endPoint.y = endY;

    frames = time;
    prog = 0;
    this.addEventListener(Event.ENTER_FRAME, tick);
}

function drawLineTick(progress:Number):void{
    for each(var shape:Shape in shapes)
    {
        shape.graphics.clear();
        shape.graphics.lineStyle(14,0x2dfdfd);

        shape.graphics.moveTo(startPoint.x,startPoint.y);
        shape.graphics.lineTo(startPoint.x + ((endPoint.x - startPoint.x) * progress), startPoint.y + ((endPoint.y - startPoint.y) * progress));

    }

}

function tick(e:Event):void {
    if(prog >= frames){
        this.removeEventListener(Event.ENTER_FRAME, tick);
    }

    drawLineTick(prog / frames);
    prog += bonus;
}

A: Because of the asynchronous nature of ActionScript, the drawLine method is invoked on each of your shapes before the first tick is executed. The drawTickLine method then draws the (same) line with the points related to the last part of the date in each of the shapes you created.
The following might not be perfect because it's not 100% clear from your question what the results should be, but hopefully it should give you a push in the right direction. I've tried to include comments to explain my thinking.
import flash.display.Shape;
import flash.geom.Point;
import flash.events.Event;

var startPoint:Point = new Point();
var endPoint:Point = new Point();

var count:int = 0;
var prog:Number = 0;
var bonus:Number = 1;
var frames:int = 150;

// Pushing a bunch of point objects onto the array is a neater
// method than using a multi-dimensional array. If you want the clarity of the
// index to help with debugging you could also do this:
// numbers[0] = new Point(460, 100);
var numbers:Array = [];
numbers.push(new Point(460, 100));
numbers.push(new Point(10, 20));
numbers.push(new Point(10, 100));
numbers.push(new Point(10, 180));
numbers.push(new Point(160, 20));
numbers.push(new Point(160, 100));
numbers.push(new Point(160, 180));
numbers.push(new Point(310, 20));
numbers.push(new Point(310, 100));
numbers.push(new Point(310, 180));

var fullDate:String = "271524";

// Vector for shapes seems overkill unless you need to loop over
// your shapes again later. For now, we store a reference to the
// current shape only
var shape:Shape;

// Set up the first line
drawLine();

// Probably easier to run a single enter frame for the duration of the whole animation
this.addEventListener(Event.ENTER_FRAME, tick);

function drawLine(time:Number = 120):void {

    // Get the appropriate index for start and end points in the numbers array
    var startIndex:int = int(fullDate.charAt(count));
    var endIndex:int = int(fullDate.charAt(count + 1));

    startPoint = Point(numbers[startIndex]);
    endPoint = Point(numbers[endIndex]);

    // create a new shape and add it to stage
    shape = new Shape();
    this.addChild(shape);

    frames = time;
    prog = 0;
}

function drawLineTick(progress:Number):void{
    shape.graphics.clear();
    shape.graphics.lineStyle(14,0x2dfdfd);

    shape.graphics.moveTo(startPoint.x,startPoint.y);
    shape.graphics.lineTo(startPoint.x + ((endPoint.x - startPoint.x) * progress), startPoint.y + ((endPoint.y - startPoint.y) * progress));
}

function tick(e:Event):void {
    drawLineTick(prog / frames);
    prog += bonus;

    // Finished drawing a shape
    if(prog >= frames){
        // Increment count, reset progress and set up the next line
        count ++;
        prog = 0;
        drawLine();
    }

    // Finished drawing all shapes
    if (count == fullDate.length + 1) {
        // Good practice to remove the eventlistener when finished
        this.removeEventListener(Event.ENTER_FRAME, tick);
    }
}