text:
Q: Scrollbar in Tkinter Notebook frames I cant get my scrollbar to show up correctly in my tkinter notebook. I need a scroll for each page
root = tk.Tk()
root.title('Client Intake Form')

n = ttk.Notebook(root)
f1 = ttk.Frame(n)
f2 = ttk.Frame(n)
f3 = ttk.Frame(n)
n.add(f1, text='Page 1', compound=tk.TOP)
n.add(f2, text='Page 2', compound=tk.TOP)
n.add(f3, text='Page 3', compound=tk.TOP)
n.pack()

canvas = tk.Canvas(f1, width=1000, height=1000, relief='raised')
canvas.pack()

scroll = tk.Scrollbar(canvas, command=canvas.yview, orient=tk.VERTICAL)
canvas.config(yscrollcommand=scroll.set, scrollregion=(1000,0,1000,1000))
scroll.pack(side=tk.RIGHT, fill=tk.Y, expand=True)

#######PAGE 2#######
page2 = tk.Canvas(f2, width=1000, height=1000, relief='raised')
page2.pack()

######PAGE 3######
page3 = tk.Canvas(f3, width=1000, height=1000, relief='raised')
page3.pack()

root.mainloop()

I want the scrollbar on the right side of each page.

A:
Question: I cant get my scrollbar to show up correctly in my tkinter notebook.

*

*I want the scrollbar on the right side of each page.
Using the .pack manager is possible, but if you use the .grid manager instead, you get simpler laid out what you want.

*I need a scroll for each page
Instead of repeating yourself, define your own widget and reuse it on all your Notebook tabs.

*

*Define a class YScrolledFrame by inheriting form (tk.Frame).
This Frame grows as large as the parent widget allows.
To behave the Scrollbar dynamic, you have to use .bind('<Configure>', ...
class YScrolledFrame(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.canvas = canvas = tk.Canvas(self, bg='white', relief='raised')
        canvas.grid(row=0, column=0, sticky='nsew')

        scroll = tk.Scrollbar(self, command=canvas.yview, orient=tk.VERTICAL)
        canvas.config(yscrollcommand=scroll.set)
        scroll.grid(row=0, column=1, sticky='nsew')

        self.content = tk.Frame(canvas)
        self.canvas.create_window(0, 0, window=self.content, anchor="nw")

        self.bind('<Configure>', self.on_configure)

    def on_configure(self, event):
        bbox = self.content.bbox('ALL')
        self.canvas.config(scrollregion=bbox)

*Define a class Notebook by inheriting form (ttk.Notebook).
This allows to access a Notebook tab by it's label text.
class Notebook(ttk.Notebook):
    def __init__(self, parent, tab_labels):
        super().__init__(parent)

        self._tab = {}
        for text in tab_labels:
            self._tab[text] = YScrolledFrame(self)
            # layout by .add defaults to fill=tk.BOTH, expand=True
            self.add(self._tab[text], text=text, compound=tk.TOP)

    def tab(self, key):
        return self._tab[key].content

Usage:

import tkinter as tk
import tkinter.ttk as ttk

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        notebook = Notebook(self, ['Page 1', 'Page 2', 'Page 3'])
        notebook.grid(row=0, column=0, sticky='nsew')

        # Fill content, to see scroll action
        tab = notebook.tab('Page 1')
        for n in range(20):
            label = tk.Label(tab, text='Page 1 - Label {}'.format(n))
            label.grid()

if __name__ == '__main__':
    App().mainloop()

Tested with Python: 3.5


text:
Q: Custom system font for a UIBarButtonItem in a toolbar for LaunchScreen.xib I am using the Avenir Next font (which is provided by iOS) in my app that I set up with the appearance API. I would like my LaunchScreen.xib to use it too so that the transition from launch screen to initial view controller is smooth.
I was able to use Avenir Next for the navigation bar in Interface Builder but I can't find a way to set a font for a UIBarButtonItem inside a UIToolbar. The Avenir Next font is properly displaying in the navigation bar during launch screen time.
Since I need it for the launch screen I obviously can't solve this problem by setting the font programmatically, it must be done in Interface Builder.
Is there a way to accomplish this, maybe by manually editing the LaunchScreen.xib file?

A: You can use UIBarButtonItem with a custom view. You can do that in a storyboard/xib just by dragging and dropping a view/button to your toolbar and it will create a UIBarButtonItem with the nested view.
The code will look like this:
<barButtonItem style="plain" id="AwC-sg-sT1">
    <view key="customView" contentMode="scaleToFill" id="4Z4-cp-rPM">
        <rect key="frame" x="0.0" y="0.0" width="320" height="33"/>
        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
        <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
    </view>
</barButtonItem>

A: Initial thoughts would be to subclass UIBarButton Item. Override the font property, with IBInspectable and set it to the Avenir Next font as default. But I cannot test this currently, so I do not know if this will work properly.

A: Straight from one of my projects:
[[UIBarButtonItem appearanceWhenContainedIn: [UINavigationBar class], nil]
     setTitleTextAttributes:@{
                              NSFontAttributeName: [UIFont fontWithName:@"YOUR FONT" size:21.f],
                              NSForegroundColorAttributeName: [UIColor whiteColor]
                              } forState:UIControlStateNormal];

redpajama_set_name: RedPajamaStackExchange


text:
Q: duplicate div inside the one class then remove the duplicate one i have one div

Upload Complete

which could contain the

test test

i want if

test test

test test

"comlete_status" have div inside it "test" more then one.then remove the other div which have name "test"
a minor update here :
 i have 20 div with class name ".complete_status" i want this according to multiple divs
every div should have only one class"test"

A: Target the .test elements inside .complete_status, and remove any with an index greater than 0
$('.complete_status .test:gt(0)').remove();

FIDDLE
or to remove all children but the first child in multiple parents
$('.complete_status .test:not(:first-child)').remove();

FIDDLE

A: $('.complete_status .test').slice(1).remove();

http://jsfiddle.net/KL727/1/

For multiple instances of div.complete_status:
$('.complete_status').each(function() {
  $('.test', this).slice(1).remove();
});

A:
if($('.test').after())
   $('.test').after().remove()

A: You can empty() the status DIV before appending new status value.
$('.complete_status').empty().append('
Test
');

A: if ($(".test").length > 1)
{
   $("div.test:not(:first)").remove();
}

This checks if there are more than one elements with class test and removes all except the first one.

A: $('.complete_status').html($('.complete_status .test').first().html());

and if you have others nodes that you want to keep inside your parent node :
    var p = $('.complete_status .test');
    var f = p.first();
    p.remove();
    $('.complete_status').html(f.html());

A: Try this:
var ele = $('.complete_status > .test').slice(1);
$('.complete_status').text('').append(ele);


text:
Q: VSTS BuildClient.GetArtifactContentZipAsync throws Microsoft.VisualStudio.Services.WebApi exception I'm trying to automate build artifact download. The objective is to download a specific build artifact. When I call BuildClient.GetArtifactContentZipAsync, it throws the following error

I am using the following code
        private static void DownloadBuildResults(Build StartedBuild, string ArtifactName)
        {
            //BuildArtifact drop = BuildClient.GetArtifactAsync(StartedBuild.Id, ArtifactName).Result; //get detiled info

            //Console.WriteLine("Build location: " + drop.Resource.DownloadUrl);

            //string dropFileName = String.Format("{0}_{1}.zip", StartedBuild.Definition.Name, StartedBuild.BuildNumber);

            Stream zipStream = BuildClient.GetArtifactContentZipAsync(79414, "abc").Result; //get content

            using (FileStream zipFile = new FileStream("abc.zip", FileMode.Create))
                zipStream.CopyTo(zipFile);

Please note that I buildID and artifact name is correct. I have double-checked these values. The above code example is taken from https://github.com/ashamrai/TFRestApi/blob/master/19.TFRestApiAppQueueBuild/TFRestApiApp/Program.cs
Is this a bug in the API/SDK? or Am I doing something wrong?
Here is the sample code if someone wants to give a try
GIST: https://gist.github.com/abhishekgoenka/9759256f995e7f7c9cbcb7872c8591c0
I get following error in code

Stack trace
   at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<HandleResponseAsync>d__53.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.TeamFoundation.Build.WebApi.BuildHttpClientBase.<GetArtifactContentZipAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Utils.Dashboard.FrmAzureDashboard.<BtnDownloadKHP_Click>d__13.MoveNext() in C:\code\MetaFXTools\ui\Utils\Dashboard\FrmAzureDashboard.cs:line 118

A: I have hit the same issue as well.
What I have determined so far is that the call to GetArtifactContentZipAsync results in a 302 response from the server.
(The Location header in the response is along the lines of: https://artproduks1.artifacts.visualstudio.com/.../_apis/artifact/.../content?format=zip)
Inside of GetArtifactContentZipAsync is a call to httpResponseMessage.EnsureSuccessStatusCode() and this causes the error to be thrown as the library is not expecting a redirect to be returned.
It is possible to create the connection using: new VssConnection(uri, creds, new VssClientHttpRequestSettings{AllowAutoRedirect = true}), so that the redirect is followed, however this then errors with a different message indicating that an incorrect version has been sent to the server.

A: I got to know the reason of the exception being thrown when calling this API.
In the pipeline if you are using the "Publish build artifacts" to publish the artifacts, the API will work fine. Whereas if you use "Publish pipeline artifact" task, the API will return 302 ("Found").
Microsoft currently has no workaround for this issue and I would suggest you to use either HttpClient or WebClient to download the artifacts.

A:
Is this a bug in the API/SDK? or Am I doing something wrong?

I can confirm the code from ashamrai is correct.(I tested it with my VS2019 16.6 and it works well.) And there's could be something with the values of your variables. I suggest you use try-catch to call the DownloadBuildResults function so that you can share detailed error message here. I just changed a bit from your code above:
class Program
{

    static readonly string TFUrl = "https://dev.azure.com/YourOrganizationName/";
    static readonly string UserPAT = "YourPAT";

    static void Main(string[] args)
    {
        try
        {
            int buildId = 832; // update to an existing build definition id
            string artifactName = "drop"; //default artifact name
            ConnectWithPAT(TFUrl, UserPAT);
            Stream zipStream = BuildClient.GetArtifactContentZipAsync(buildId, artifactName).Result; //get content
            using (FileStream zipFile = new FileStream(@"C:\MySite\test.zip", FileMode.Create))
                zipStream.CopyTo(zipFile);
            Console.WriteLine("Done");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
            if (ex.InnerException != null) Console.WriteLine("Detailed Info: " + ex.InnerException.Message);
            Console.WriteLine("Stack:\n" + ex.StackTrace);
        }
    }
}

So you need to make sure:
1.You have a valid PAT which hasn't expired yet, and this PAT has the access to build artifact. Then directly enter the pat in  static readonly string UserPAT = "xxxxxxxxxxxxx";. It should be "PAT" instead of "<PAT>".
2.The URL(TFUrl) only needs OrganizationName as part of it.
3.Make sure you choose the correct artifact name.
4.Distinguish the difference between BuildID and BuildDefinitionID.

*

*You can see buildDefinitionID when editing the pipeline:

*

*You can see BuildID when checking the pipeline run results in web portal:

You should use the BuildID as input.
5.Also, the build you run(BuildID) should have the artifact published:

Your pipeline should have Publish build artifacts task. Check the log and make sure something is published, the folder to be published can't be empty.
6.Since you're only testing the code by Download artifact function, make sure you queue/run the build successfully before your run the code. (Wait for the end of the pipeline run.)


text:
Q: Sinon mock returns once (never called) I made an attendance tracker that uses slack and google sheets, and now I am trying to write the tests for it. I am currently struggling with mocking the timesheets.get() method. Keep getting the

ExpectationError: Unexpected call: get(tester, Thu Jun 01 2017
  00:00:00 GMT+0900)
Expected get(tester, Thu Jun 01 2017 00:00:00 GMT+0900[, ...]) once
  (never called)

error message
code:
execute(username, body) {
  let user = get username from body;

  let year = get year from body;

  let month = get month from body;

  let calculateMonthTotal = this._getMonthTotal(user, month, year, this.timesheets);
  this.slack.send(calculateMonthTotal);
}

static _getMonthTotal(username, month, year, timesheets) {
  const date = moment({year: year, month: month, day: 1});
  let totalWorkedHours = 0;
  while (date.month() == month) {
    const row = timesheets.get(username, date);
    totalWorkedHours += parseFloat(row.getWorkedHours());
    date.add('1','days');
  }
  return "month total is "+totalWorkedHours;
}

and the timesheets.get() is as follows:
get(username, date) {
  var sheet = this._getSheet(username);
  var rowNo = this._getRowNo(username, date);

  if (rowNo <= 4) {
    return null;
  }

  var row = sheet.getRange("A"+rowNo+":"+String.fromCharCode(65 + this.scheme.columns.length - 1)+rowNo).getValues()[0].map(function(v) {
    return v === '' ? undefined : v;
  });

  if (row) {
    return new TimesheetRow(username, date, row);
  }
}

And here is my test
describe('CommandMonthTotalSpec', ()=> {

  it('should call slack send method with expectMessage', () => {
    const username = "tester";
    const expectMessage = 'month total is 8';
    const body = "getMonthTotal "+username+" 2017/6";
    const date = moment({year: 2017, month: 5, day: 1});

    const row = new TimesheetRow(username, date, ["2017/06/01 00:00:00","2017/06/01 10:00:00","2017/06/01 19:00:00","","1","8","",""]);
    const slack = new Slack();
    const timesheets = new Timesheets();
    let mockTimesheets = sinon.mock(timesheets).expects('get').once().withArgs(username, date).onCall(0).returns(row);

    const command = new CommandMonthTotal(slack, null, timesheets);
    const mockSlack = sinon.mock(slack).expects('send').once().withArgs(expectMessage);

    command.execute(username, body);

    mockSlack.verify();
    mockTimesheets.verify();
  });
});

In the test I am passing two arguments, do not know why it is showing that error message. Could anyone point out what I am doing wrong?

A: changing the mockTimesheets to the following solved the issue
let mockTimesheets = sinon.mock(timesheets).expects('get').atLeast(28).atMost(31)
  .onCall(0).returns(row)
  .onCall(1).returns(null)
  .onCall(2).returns(null)
  .onCall(3).returns(null)
  .onCall(4).returns(null)
  .onCall(5).returns(null)
  .onCall(6).returns(null)
  .onCall(7).returns(null)
  .onCall(8).returns(null)
  .onCall(9).returns(null)
  .onCall(10).returns(null)
  .onCall(11).returns(null)
  .onCall(12).returns(null)
  .onCall(13).returns(null)
  .onCall(14).returns(null)
  .onCall(15).returns(null)
  .onCall(16).returns(null)
  .onCall(17).returns(null)
  .onCall(18).returns(null)
  .onCall(19).returns(null)
  .onCall(20).returns(null)
  .onCall(21).returns(null)
  .onCall(22).returns(null)
  .onCall(23).returns(null)
  .onCall(24).returns(null)
  .onCall(25).returns(null)
  .onCall(26).returns(null)
  .onCall(27).returns(null)
  .onCall(28).returns(null)
  .onCall(29).returns(null)

;


text:
Q: Difference between two dates in Pascal This program is supposed to find the difference between two dates but it has a bug and I can't find it.
It keeps returning a big number - please help
Program tp4;
Type
  dt = Record
    jour : Integer;
    mois : Integer;
    annee : Integer;
  End;
Var
  date : dt ;
  y,x,i,s : Integer;
Begin
  x := 0;
  s := 0;
  For y:=1 To 2 Do
    //2 dates
    Begin
      Writeln('Entrez un date : jour mois année ');
      Readln( date.jour, date.mois, date.annee);
      While ((date.jour<=0) Or (date.jour>31) Or (date.mois>12) Or (date.annee<=0) ) Do
        //verfication loop
        Begin
          Writeln('Entrez une  date valide : jour mois année ');
          Readln(date.jour ,date.mois ,date.annee);
        End;
      s := s+date.jour  ;
      For i:= 1 To date.mois-1 Do
        Case i Of
          3,5,7,8,10,12,1 : s := s+31;
          4,6,9,11 : s := s +30;
          2 : If ((date.annee Mod 100)=0) And ((date.annee Mod 400) = 0 ) Then //convert months to days
                s := s+29
              Else If date.annee Mod 4 = 0 Then
                     s := s+29
              Else s := s+28;
        End;                                                                                //Convert years to days
      For i:= 1 To date.annee  Do

            If (i Mod 100 = 0) And (i Mod 400 = 0) Then s := s+366
            Else If (i Mod 4 =0) Then s := s+366
            Else s := s+365;
                    x:=s-x ;

    End;

  If (x)<=0 Then
    Writeln('la difference est :',-x)
  Else Writeln('la difference est :',x);
  Readln;
End.

**input**
12 03 2019

13 03 2019
**output**

737510

A: I think the error was somewhere in s and x (x:=s-x; etc.), I did refactoring:
Program tp4;

Type dt = Record
  jour : Integer;
  mois : Integer;
  annee : Integer;
End;

Type
  arrayDate = array[1..2] of dt;

Var
  y,i,f,s : Integer;
  arrDate: arrayDate;

function Leap (Y : Word): Boolean;
Begin
  If (Y Mod 4) <> 0 Then Leap := FALSE
  Else If (Y Mod 100) <> 0 Then Leap := TRUE
  Else Leap := (Y Mod 400) = 0;
End;

function Lenght (date: dt) : Integer;
Begin
  Lenght := 0;
  Lenght := Lenght + date.jour;
  For i := 1 To date.mois Do
    Case i Of
      3, 5, 7, 8, 10, 12, 1 : Lenght := Lenght + 31;
      4, 6, 9, 11 : Lenght := Lenght + 30;
      2 : If Leap (date.annee) Then Lenght := Lenght + 29 Else Lenght:= Lenght + 28;
    End;
  For i := 1 To date.annee Do  //Convert years to days
    If Leap (i) Then Lenght := Lenght + 366 Else Lenght := Lenght + 365;
End;

Begin
  For y := 1 To 2 Do  //2 dates
  Begin Writeln ('Entrez un date : jour mois année ');
    Readln (arrDate[y].jour, arrDate[y].mois, arrDate[y].annee);
    While ((arrDate[y].jour <= 0)
      Or (arrDate[y].jour > 31)
      Or (arrDate[y].mois > 12)
      Or (arrDate[y].annee <= 0)) Do //verfication loop
    Begin
      Writeln ('Entrez une  date valide : jour mois année ');
      Readln (arrDate[y].jour, arrDate[y].mois, arrDate[y].annee);
    End;
  End;

  f := Lenght(arrDate[1]);
  s := Lenght(arrDate[2]);

  Writeln ('la difference est :', Abs(s - f)); // absolute |s-f|
  Readln;
End.

A: You are using the For y ... loop to request input and to calculate number of days for each input. Within the loop, the s variable is the days counter.
The error you do is that you zero s bfore the For y ... loop and not at the beginning of the loop. Therefore, the second time you request a date, s still has the value from the first date, on top of which you then start to calculate the days for the second date.
The correction is of course to move s := 0; to the beginning of the For y ... loop,
or change the first assignment of s from
s := s + date.jour;

to
s := date.jour;

A: Finding the difference between two dates 6,000 years apart in a loop? And (ab)using the name of a standard function "Length"? Ouch!
Try this:
//----------------------------------------------------------------------
// Convert a date to its Julian Day Number
//----------------------------------------------------------------------
procedure cj(dd, mm, yyyy: longint; var jdn, dow: longint);
var
  cj_y,
  cj_c,
  cj_x,
  cj_y: double;

begin
  if dd = 0 then
    begin
      jdn:= -1
      dow:= -1;
    end
  else
    begin
      cj_y:= yyyy + (mm - 2.85) / 12;
      cj_c:= 0.75 * trunc(cj_y * 0.01);

      cj_x:= frac(cj_y);
      cj_y:= trunc(cj_y);

      jdn:= trunc(
            trunc(
            trunc(367 * cj_x) + 367 * (cj_y) -
                                1.75 * cj_y + dd) - cj_c) +
                                1721115.0;
      dow:= jdn mod 7;
    end;
end; {cj}

Formula as given is valid for days after 1582-10-15, a small tweak will allow dates going back to 0000-03-01.
Follow the link in https://groups.google.com/g/comp.lang.pascal.borland/c/itwgcfYpLEU which I posted in August 1998 in comp.lang.pascal.borland for explanations.


text:
Q: Compare two dataframes based on conditions in PySpark I want to compare records from one dataframe with another dataframe and find a match, stop the iteration for that record if a match is found based on a condition and return a result.
1st DataFrame

A
B
C

John
Doe
23

John
Doe
24

2nd DataFrame

A
B
C

Jane
Doe
23

John
Doe
24

Conditions

Array
Value

[1,1,1]
D

[0,1,1]
F

In the output I want to compare values from first Dataframe with 2nd df and generate a binary based on comparison like [0,1,1] or [1,1,1] and check if this list is present in conditions df, if present return the value corresponding to it.
Output

A
B
C
Value

John
Doe
23
F

John
Doe
24
D


text:
Q: Firebase Notification issue in ios with warning of replacement of server keys I am getting an warning where the server keys are placed which says that "tokens firebase cloud replaced the server keys for sending messages. Although you can continue to use them, the server keys are no longer supported."
I tried with the cloud key but i am still unable to receive notifications. Also I tried the server keys they are also not working and still unable to receive notifications in my App.
Please let me know something so that I can receive notifications in my App.
See screenshot for reference:
https://drive.google.com/file/d/0ByDtTMHCU39BZXVSV1RxVFhmMkE/view?usp=sharing


text:
Q: Paypal MassPay api get data from IPN I am using papyal MassPay api to send payment. While sending payment paypal not returning payment status and transaction ID as well. The only way to get details is from IPN. But i am stuck with the IPN. I am not getting how i can check each transaction and its status from IPN.
Results: Array
(
    [payer_id] => HDG123
    [payment_date] => 02:56:22 Oct 05, 2017 PDT
    [payment_gross_1] =>
    [payment_gross_2] =>
    [payment_status] => Completed
    [receiver_email_1] => test1@gmail.com
    [receiver_email_2] => test2@gmail.com
    [charset] => windows-1252
    [mc_currency_1] => CAD
    [masspay_txn_id_1] => 9DY72188PA481234
    [mc_currency_2] => CAD
    [masspay_txn_id_2] => 6U883047ND871234
    [first_name] => Hardik
    [unique_id_1] => 123719736059d601b0d1cda
    [notify_version] => 3.8
    [unique_id_2] => 2130719736059d601b0d1dbf
    [payer_status] => verified
    [status_1] => Completed
    [status_2] => Completed
    [txn_type] => masspay
    [mc_gross_1] => 82.86
    [mc_gross_2] => 102.90
    [payment_fee_1] =>
    [residence_country] => CA
    [payment_fee_2] =>
    [test_ipn] => 1
    [mc_fee_1] => 1.25
    [mc_fee_2] => 1.25
    [ipn_track_id] => c85ffe2791234
)


text:
Q: How do I replace illegal characters in a filename? I am trying to create a zip with folders inside it and I have to sanitize the folder names against any illegal characters. I did some googling around and found this method from http://www.rgagnon.com/javadetails/java-0662.html:
public static String sanitizeFilename(String name) {
    return name.replaceAll("[\\\\/:*?\"<>|]", "-");
}

However, upon testing I get some weird results. For example:
name = filename£/?e>"e

should return filename£--e--e from my understanding. But instead it returns filename-ú--e--e
Why is this so?
Please note that I am testing this by opening the downloaded zip file in WinZip and looking at the folder name that is created. I can't get the pound sign to appear. I've also tried this:
public static String sanitizeFilename(String name) {
    name = name.replaceAll("[£]", "\u00A3");
    return name.replaceAll("[\\\\/:*?\"<>|]", "-");
}

EDIT: Some more research and I found this: http://illegalargumentexception.blogspot.co.uk/2009/04/i18n-unicode-at-windows-command-prompt.html
It appears to do with Locale, windows versions and encoding factors. Not sure how I can overcome this within the code.

A: I think it depends on how you are actually reading the file name in terms of encoding.
Therefore, the £ symbol might get corrupted.
As an example not fitting your case exactly, reading UTF-8-encoded £ as an ISO Latin 1-encoded character would return £.
Make sure of the file's encoding (i.e. ISO Latin 1 vs UTF-8 would be the most common), then use the appropriate parameter for your Reader.
As a snippet, you may want to consider this example:
BufferedReader br = new BufferedReader(
    new InputStreamReader(
        new FileInputStream(new File("yourTextFile")),
        "[your file's encoding]"
    )
);


text:
Q: Topology induced by an atlas (sort of) I have a locally trivial bundle $B$ with base $X$ and projection $p$. I have open cover $\{ V_{j}\}$ and "charts" $\phi_{j}: V_{j}\times F \to p^{-1}(V_{j})$.
(*) On each $p^{-1}(V_{j})$ I can get topology induced by $\phi_{j}$ and on $p^{-1}(V_{j}) \cap p^{-1}(V_{i})$ the maps $\phi_{i},\phi_{j}$ induce the same topology.
What exactly is topology on $B$ induced by $\phi_{j}'s$?
Is it the one that $U\subseteq B$ is open iff $\phi_{i}^{-1}(p^{-1}(V_{i})\cap U)$ is open $\forall i \in I$, or is there some other natural topology?

A: The topology on the total space $B$ can be thought locally as a product space of $F$ and an open set in $X$.
As you guessed,
$$
\begin{align*}
U \text{ is open $B$} &\iff p^{-1}(V_i)\cap U \text{ is open in $B$ for all $i\in I$} \quad \text{($\because$ $U=\bigcup_{i\in I}\bigl[p^{-1}(V_i)\cap U\bigr]$) } \\
&\iff \phi_i^{-1}(p^{-1}(V_i)\cap U) \text{ is open in $V_i\times F$ for all $i\in I$} \quad \text{($\because$ $\phi_i$ is a homeomorphism) }
\end{align*}
$$
but the condition is not convenient to use.
Actually it may be better to start with two topologies given on the total space $B$ and the base space $X$, and a continuous surjective projection $p\colon B\to X$.


text:
Q: Django URL Translation - Stay on the same page when changing language I developped a Django app with i18n for urls as well.
That look really nice but when changing the language I would like to stay on the same/previous page.
What is the best way of doing that ?
Basically to get the new url I need to do a reverse on the name of the previous page after having changed the language and do a redirect but how can I know the url name of the previous page?
Edit:
A solution that came from a collegue:
Calculate a next parameter for each language using request.resolver_match.
   For each language : activate(language) + reverse('{app_name}:{url_name}', args, kwargs) using request.resolver_match elements
Do you see a better idea?

A: After change language with django-modeltranslation redirecting to home ?
If you want to redirect to the same page, you can replace this part of code:
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}

{% trans "Language" %}:

    {% for language in languages %}

          {{ language.name_local }}

    {% endfor %}

to:
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}

{% trans "Language" %}:

    {% for language in languages %}

          {{ language.name_local }}

    {% endfor %}

Attention please:

<a href="/{{ language.code }}/

replaced to <a href="/{{ language.code }}/{{request.get_full_path|slice:"4:"}}"

A: Two options for you:
Option 1
If you use the form from the documentation then will take you which brings you back to the page you were on.
Option 2
When changing the language you could use the referrer header, HTTP_REFERER , and redirect back to where you came from
# Change the language
# ... code ...

# Redirect back to where we came from
redirect_to = request.META.get('HTTP_REFERER', reverse('default-redirect-page'))
return HttpResponseRedirect(redirect_to)


text:
Q: What is the trick needed to compute the integral $\int \frac{1}{x^{2}+x+1} dx$? Working through Spivak's Calculus and using old assignments from the course offered at my school I'm working on the following problem, asking me to find the integral $$\int \frac{1}{x^{2}+x+1} dx$$
Looking through Spivak and previous exercises I worked on, I thought using a partial fraction decomposition would be the technique, but even in Spivak the only exercises I've seen which are similar involve:
$$\int \frac{1}{(x^{2}+x+1)^{n}} dx\ ,\text{where}\ n> 1$$
In which case it is pretty straightforward to solve. So there must be a reason why the exercise isn't presented unless it is so straightforward.
Integration by parts and substitution (at least for now) have proven fruitless as well. So I come here to ask if I'm missing any special trick to compute this integral ?

A: It's actually very simple to identify this integral as this:
$$\int \frac{1}{x^2+x+1} dx = \int \frac{1}{\left(x+\frac{1}{2} \right)^2+ \frac{3}{4}} dx.$$
Now you can see that you can use the following rule for integration: $$\int \frac{1}{x^2+a^2}dx=\frac{1}{a} \arctan \left(\frac{x}{a} \right)+ C.$$
And now you get $$\int \frac{1}{\left(x+\frac{1}{2} \right)^2+ \frac{3}{4}} dx = \frac{2}{\sqrt{3}} \arctan \left(\frac{2x+1}{\sqrt{3}} \right) + C.$$

A: I'll take a different approach from the answers so far. For this approach, you'll have to be at least a bit comfortable working with complex numbers.
We can factor $x^2 + x + 1$ as $\left(x - \frac{1 + \sqrt{3}i}{2}\right)\left(x - \frac{1 - \sqrt{3}i}{2}\right)$.
That means we can rewrite the integral using partial fractions:
$\int \frac{dx}{x^2+x+1} = \int \frac{A dx}{x - \frac{1 +\sqrt{3}i}{2}} + \int  \frac{B dx}{x - \frac{1 -\sqrt{3}i}{2}}$ for some $A, B \in \mathbb{C}$.
We can find $A$ and $B$ easily:
$Ax - A \frac{1 +\sqrt{3}i}{2} + Bx - B \frac{1 -\sqrt{3}i}{2} = 1$.
This gives us that $A = -B$, and $A = -\frac{\sqrt{3}i}{3}$.
These integrals are of the form $\int \frac{Kdx}{x-L}$, and are easy enough to solve: just use the substitution $u = x - \frac{1 +\sqrt{3}i}{2}$ for the first one, and $u =x -  \frac{1 -\sqrt{3}i}{2}$ for the second one.

A: Though the efficient way has been given several times, decomposition in simple fractions remains your good friend.
The polynomial $x^2+x+1$ has complex roots, let $\omega$ and $\omega^*$, which, incidentally, are cube roots of unity. Now,
$$\frac1{x^2+x+1}=\frac1{(x-\omega)(x-\omega^*)}=\frac1{2i\Im(\omega)}\left(\frac1{x-\omega}-\frac1{x-\omega^*}\right)$$ and after integration,
$$\frac1{2i\Im(\omega)}\log\frac{x-\omega}{x-\omega^*}.$$
As $|x-\omega|=|x-\omega^*|$, the logarithm reduces to the difference of the arguments,
$$-\frac1{\Im(\omega)}\arctan\frac{\Im(\omega)}{x-\Re(\omega)}=-\frac2{\sqrt3}\arctan\frac{\sqrt3}{2x+1}.$$

There is even a faster way, noticing that
$$\frac1{x-\omega}=\frac{x-\omega^*}{(x-\omega)(x-\omega^*)}=\frac{x-\Re(\omega)}{x^2+x+1}+i\frac{\Im(\omega)}{x^2+x+1}.$$
Hence, taking the imaginary part,
$$\int\frac{dx}{x^2+x+1}=\frac{\Im(\log(x-\omega))}{\Im(\omega)}=-\frac1{\Im(\omega)}\arctan\frac{\Im(\omega)}{x-\Re(\omega)}.$$
As a byproduct,
$$\int\frac{{x-\Re(\omega)}}{x^2+x+1}dx=\frac{\Re(\log(x-\omega))}{\Im(\omega)}=\frac1{\Im(\omega)}\log\sqrt{(x-\Re(\omega))^2+\Im^2(\omega)}.$$

A: Hint : $x^2+x+1 = (x+\frac{1}{2})^{2}+\frac{3}{4}$

A: $\int \frac{1}{(x+1/2)^2 + 3/4} dx= \frac{2}{\sqrt3}\tan^{-1}\frac{2x+1}{\sqrt3} +c$


text:
Q: C++ invalid conversion from 'const char*' to char* I am new to C++. I have an exercise about constructor with const char* parameter.
class Book
{
private:
   char* title;
}
public:
   Book (const char* title)
   {
      this->title = title;
   }

When I code the constructor like that, I receive error cannot convert const char to char*.
I tried using
strcpy(this->title, title);
then, it run, but I don't get the expected result.
Can anyone help me.
Thank you very much.

A: C++ doesn't let you easily change a const char * into a char * since the latter has no restrictions on how you can change the data behind that pointer.
If you're doing C++, you should be avoiding char * (legacy C) strings as much as possible. By all means take them as parameters if you must, but you should be turning them into C++ strings at the earliest opportunity:
class Book {
private:
   std::string m_title;
public:
    Book (const char *title) {
        m_title = title;
    }
};

The one thing you don't want to become is a C+ developer, that strange breed that never quite made the leap from C across to the C++ way of thinking :-)

And, actually, if a given book is never expected to change its title, you're better off making it constant and initialising it, rather than assigning to it, something like:
#include <iostream>
#include <string>

class Book {
    public:
    Book (const char* title): m_title(title) {};
    void Dump() { std::cout << m_title << "\n"; }

    private:
    const std::string m_title;
};

int main() {
    Book xyzzy("plugh");
    xyzzy.Dump();
}

A: You are doing an exercise, did the course you are following not explain what you are supposed to do?
I would guess that this is an exercise in dynamic memory allocation and what you are expected to do is use strcpy after you have allocated some memory so that you have somewhere to copy the string to. Like this
this->title = new char[strlen(title) + 1];
strcpy(this->title, title);

You need to allocate one extra char because C style strings are terminated with an additional nul byte.
But any C++ programmer who was doing this for real (instead of it being a learning exercise) would use a std::string as paxdiablo says.


text:
Q: How can I initialize an array with a length inferred from the variable's type? I have a custom type for an array and I want to initialize a variable of that type. It looks something like this:
type Registers = [u8; 16];

fn main() {
    let mut registers: Registers;
}

I do not want to do something like the following because at some point I may want to change the size of my array type:
let mut registers: Registers = [0; 16];

Is there any way to use just the name of the type to initialize the variable? Am I forced to specify the initialization just like above?
My question is a bit different from Can array lengths be inferred in Rust? because the size of the array should be inferred from the type itself, not the type of the array inferred from the value.

A: You cannot infer the length of an array because it is an expression that must be evaluated at compilation time. As far as I can figure, the concept of an "inferred expression" doesn't make sense.

I may want to change the size of my array type

You can avoid this being a problem by introducing a constant:
const N_REGISTERS: usize = 16;
type Registers = [u8; N_REGISTERS];

fn main() {
    let mut registers: Registers = [0; N_REGISTERS];
}

You could also use the Default implementation of an array, but only for certain sizes of array and only if you want the default value of your array's element type:
type Registers = [u8; 16];

fn main() {
    let mut registers = Registers::default();
}

A: As long as const generics are unavailable, Default will not be implemented for all array types. This makes array initialization not very ergonomic, as you have experienced.
As a commonly employed alternative, you can turn the type alias into a newtype, with which you can isolate array initialization to a single point in the code.
pub struct Registers(pub [u8; 16]);

impl Default for Registers {
    fn default() -> Self {
        Registers([0; 16])
    }
}

At this point, and depending on your use case, you can also implement other useful traits for this type, such as AsRef<u8> and AsMut<u8>.
impl AsRef<[u8]> for Registers {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}


text:
Q: How to generate Laravel Link with anchor I use Laravel URL::Route for link pages, And I passed query string like following code, but how to add anchor tag for this?

eg: myproject.local/projects?week_ending=value#anchor

How to do that #anchor part with URL::Route? thank you
URL::Route('projects', array('week_ending'=>$week_end_day))

A: The most obvious way for that will be:
URL::Route('projects', array('week_ending'=>$week_end_day)) . '#anchor'


text:
Q: "com.android.vending.INSTALL_REFERRER" fetching referrer parameters on Broadcast has up to 15 seconds delays on some devices My server creates a link that redirects and passes parameters to google play store;
The sms I receive by my Server;
https://goo.gl/{UNIQUE_ID}
when I click, I actually click on this this url below;
http://www.mycompany.com/env=dev&token=123&id=456
The link above directs me to google play store to my app included parameters;
https://play.google.com/store/apps/details?id=com.mycompany.app&referrer=123,456
Here is the question;(First time installation)
When I install the app opened with the link above, I want to pass those "token", "id" parameters to my app in first time then I will skip login. These parameters creating by server because they are also unique to user.
I have setup the "com.android.vending.INSTALL_REFERRER" and I am able to receive parameters as expected but not consistent on every devices and could face with big delays.
 <receiver
        android:name=".GooglePlayReceiver"
        android:exported="true"
        android:permission="android.permission.INSTALL_PACKAGES">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>

My GooglePlayReceiver Broadcastreceiver is;
public class GooglePlayReceiver extends BroadcastReceiver {

Context mContext;
String purchaseId = null;

public GooglePlayReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
    try {
        mContext = context;
        Bundle extras = intent.getExtras();
        String verificationCode = null;
        String phoneNumber = null;
        if (extras != null) {
            String code = extras.getString("referrer");
            String[] strArr = code != null ? code.split(",") : new String[0];
            token = strArr[0];
            id = strArr[1];
        }
    } catch (Exception ex) {
    }
}}

This flow has big delays on some devices. For ex, Google Pixel 2 fetches the parameters immediately without delay, Samsung Galaxy S7 has 5-10 seconds delay.
How to solve this?

A: Because the INSTALL_REFERRER is sent as a broadcast (documentation) it uses the publish subscribe model. There is no guarantee about timing.
Because of this you shouldn't design your app startup flow to rely on receiving the broadcast within a certain length of time. Android is open source, and changes made my different phone manufacturers will cause different promptness in the delivery of broadcasts.
I'd have a different design for your app:

*

*take the user always to the normal setup flow

*if the broadcast arrives later, allow the user to skip login


text:
Q: Why is my regex not working using sed in bash script on Mac OSX? I am trying to capture CBX-1234 from the string CBX-1234--CBX-5678 or CBX-12345--CBX-5678. I am using a bash script on Mac OSX using sed to run the regular expression.
string="CBX-1234--CBX-5678"
shortenedString=$(echo "$string" | sed "s/^([A-Za-z]+-[0-9]+)/\1/")

This outputs the following error message:

sed: 1: "s/^([A-Za-z]+-[0-9]+)/\1/": \1 not defined in the RE

How can I capture the substring? I am open to suggestions using sed or other means in bash.

A: You need to add -E to the sed command line to make it use extended regular expressions:
sed -E 's/^([A-Za-z]+-[0-9]+)/\1/'

If what you want to do is to shorten the string CBX-1234--CBX-5678 to CBX-1234, you additionally need to modify the substitution to take the whole string into account:
sed -E 's/^([A-Za-z]+-[0-9]+).*/\1/'

You may alternatively use the bash parameter expansion
shortenedString="${string%%--*}"

This will remove everything from $string from the first occurrence of --.

A: You can use echo "$string" | cut -d "-" -f 1,2.

A: I always use sed -r
$ echo "abhellocd" | sed -r "s/.*(hello).*/\1/g"
hello

From the man page of sed:
   -r, --regexp-extended
          use extended regular expressions in the script.

The option -E isn't listed by me. Although it works too.


text:
Q: Building an array of verbs in J Is it possible to build arrays of verbs?
I've tried this:
f =: >:
f2 =: f f

There's no syntax error but f2 is clearly not an array of verbs.
For instance
f2 yields f f
$ f2 yields $ f2
0 { f2 yields 0 { f2

2 3 $ f behaves in a similar way.

I'd also like to know if verbs can be activated by the name.
Edited
Instead of f2 =: f f, which is a composition, let's have
f =: >:
f2 =: 2 1 $ f

f2 yields 2 1 $ f
$ f2 yields $ f2
0 { f2 yields 0 { f2

It seems that f2 represents the sequence 2 1 $ f, while in the case of an atom, e.g. 2 1 $ 7, the right side is a vector.

A: As the comments point out, f2=: f f creates a composition and f3=: 2 1 $ f creates a composition as well. In the case of f2 you are defining a hook and in the case of f3 you are defining a fork that will take the results of f when it is given an argument and return the 2 1 shape of that result. The reason that it just parrots back your input is that is the way that J displays verbs without arguments. It shows you the construction, because it does not know what the verb will be applied to.
I think what you may want is the process of making a verb into a gerund, which is the noun form of a verb that can be activated in a number of ways. Creating a gerund is done by inserting a backtick between two verbs or for a single verb, a backtick between the verb and an empty string. Examples of conjunctions that work on gerunds are Agenda and Evoke Gerund.
Although this can be done in J, it is pretty clunky because J does not have the meta-operators that are necessary to manipulate verbs as if they are nouns, aside from turning them into gerunds.

A: A collection of functions is called a gerund in J and is formed using the tick "`":
g =: +`-`f
┌─┬─┬─┐
│+│-│f│
└─┴─┴─┘

You can use @. to apply the appropriate verb using its index:
4 2 3 (g @. 0) 1 5 6
5 7 9
4 2 3 (g @. 1) 1 5 6
3 _3 _3
4 2 3 (g @. 2) 1 5 6
1 0 0

NB. defining a 2x2 gerund:
k =: 2 2 $ +`-`*`%
┌─┬─┐
│+│-│
├─┼─┤
│*│%│
└─┴─┘

1 (((<0 0) { k) @. 0) 2
3
1 (((<0 1) { k) @. 0) 2
_1
1 (((<1 0) { k) @. 0) 2
2
1 (((<1 1) { k) @. 0) 2
0.5

The index can also be a new verb that depends on the arguments or a list of indices.


text:
Q: Cannot add or update a simple row to SQL Server table Coming from an Access DB background using SQL select statements, I am finding that there is more work involved in pushing data into an SQL Server database and updating records. My initial understanding of adding records in SQL Server required a VERY LONG statement that included the INSERT command. This to me seems to be unnecessarily complicated and I have to believe that with .NET today, it has to be much simpler.
I have researched and reviewed several code samples for DataTable, DataSet, SqlCommand, SqlAdapters, etc. NONE of them work for me despite the fact that my code has no errors in it.  I've gone through so many mutations of these examples that I am appealing to Stack Overflow for some help.
Here's what I am trying to do.

*

*Connect to a SQL Server hosted externally (works!)

*Open a single table called Dongles.

*Check for a row using the serial number as a criteria.

*If it exists, UPDATE the record.

*If not, then ADD the new record.

I am providing the latest mutation of the code samples that I have worked with. Before running the code, I manually added 1 record to the database so I know the SerialNumber argument matches.  Unfortunately, the if (dt.Rows.Count > 0) statement returns false and the update is never attempted.
Now I will tell you this....I have tried other mutations that did successfully go through the lines that update each field.  But when the Update() function was called (successfully), nothing was propagated to the actual database.
Here's the code:
SqlCommand cmd = new SqlCommand("SELECT * FROM Dongles WHERE SerialNumber = " + m_dongle.SerialNumber, server.SQLConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder cb = new SqlCommandBuilder(da);

DataTable dt = new DataTable();
da.Fill(dt);

if (dt.Rows.Count > 0)
{
   dt.Rows[0]["IsLeased"] = m_dongle.IsLeased == true ? 1 : 0;
   dt.Rows[0]["LeaseDaysRemaining"] = m_dongle.LeaseDaysRemaining;
   dt.Rows[0]["DateAssigned"] = DateTime.Now;
   dt.Rows[0]["ConfiguredBy"] = m_dongle.ConfiguredBy;
   dt.Rows[0]["LicenseHolder"] = m_dongle.LicenseHolder;
   dt.Rows[0]["ContactName"] = m_dongle.ContactName;
   dt.Rows[0]["ContactPhone"] = m_dongle.ContactPhone;
   dt.Rows[0]["ContactEmail"] = m_dongle.ContactEmail;
   dt.Rows[0]["SerialNumber"] = m_dongle.SerialNumber;
   dt.Rows[0]["IsNetworkDongle"] = m_dongle.IsNetworkDongle;
   dt.Rows[0]["NetworkMaxUsers"] = m_dongle.NetworkMaxUsers;
   dt.Rows[0]["NetworkAbsoluteMaxUsers"] = m_dongle.NetworkAbsoluteMaxUsers;
   dt.Rows[0]["IsAssigned"] = m_dongle.IsAssigned;
   dt.Rows[0]["DongleModel"] = m_dongle.DongleModel;
   dt.Rows[0]["SalesforceID"] = m_dongle.SalesforceID;

   da.Update(dt);

   MessageBox.Show("Dongle profile updated successfully.", "Profile Saved",
                   MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}

A: What kind of column is SerialNumber?? If it's a string column, you would need to put quotes around the parameter - and while you're at it, to prevent SQL injection attacks - use parametrized queries instead of concatenating together your SQL statements... (as an added benefit, the parameters will automagically use quotes around values, where needed):
SqlCommand cmd = new SqlCommand("SELECT * FROM Dongles WHERE SerialNumber = @SerialNo", server.SQLConnection);

cmd.Parameters.Add("@SerialNo", SqlDbType.VarChar, 50).Value = m_dongle.SerialNumber.Trim();

SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder cb = new SqlCommandBuilder(da);

DataTable dt = new DataTable();
da.Fill(dt);

if (dt.Rows.Count > 0)
{
    .......
}


text:
Q: Добавление значения со строковым индексом в массив Имеется массив array(). Как программно добавить в него use = 123qwerty и like  = yes1, т.е. чтобы массив выглядел так: array("use" => "123qwerty", "like" => "yes1") ?

A: //так
$arr['use'] = '123qwerty';
$arr['like'] = 'yes1';
//или так
$arr2=array('use' => '123qwerty', 'like' => 'yes1');


text:
Q: Why addAnimation:forKey not working in viewDidLoaded I have the following method called by viewDidLoad. This method is to create a CALayer to show a image. This layer has a mask whose path is a UIBezierPath created by my private method. I want the mask to rotate infinitely, and then I add a CABasicAnimation object to the mask.
- (void) createPathLmask
{
    // mask layer
    self.pathLayer                 = [CALayer layer];
    self.pathLayer.bounds          = CGRectMake(0.0, 0.0, 120, 120);

    CGPoint position = self.view.layer.position;
    position.y += 140;
    self.pathLayer.position        = position;
    self.pathLayer.backgroundColor = [UIColor redColor].CGColor;

    UIImage *backimage = [UIImage imageNamed:@"image2"];
    self.pathLayer.contents = (__bridge id)backimage.CGImage;
    self.pathLayer.contentsGravity = kCAGravityResizeAspectFill;

    // mask
    CAShapeLayer *mask = [CAShapeLayer layer];
    mask.bounds          = CGRectMake(0.0, 0.0, 120, 120);
    mask.position        = CGPointMake(60.0f, 60.0f);
    mask.contentsGravity = kCAGravityResizeAspectFill;
    mask.path            = [self createBezierPathInRect:mask.bounds].CGPath;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // rotate the mask repeatedly
        CABasicAnimation *animation = [CABasicAnimation animation];
        animation.keyPath = @"transform.rotation";
        animation.duration = 4.0f;
        animation.byValue  = @(M_PI * 2);
        animation.repeatCount = HUGE_VALF;
        [mask addAnimation:animation forKey:@"rotation_repeatedly"];
    });

    self.pathLayer.mask = mask;

    [self.view.layer addSublayer:self.pathLayer   ];
}

I find that the rotation animation can only work when I put the addAnimation:forKey into the dispatch_after block with 1 second delay. If those codes are moved out of the block, the mask will not rotate.
So there must be something not ready when animation is added to the layer in viewDidLoaded. I am wondering what is not ready yet? Is there any document or explanation about the suitable chance to add the animation?

A:
So there must be something not ready when animation is added to the layer in viewDidLoaded

Correct. This is way too early for animation. Keep in mind that the view at this point merely exists and that's all; it isn't even part of the interface. You cannot animate a view that isn't part of the view hierarchy. There is nothing, at this point, to animate.
The view first becomes part of the interface between the first call to viewWillAppear and the first call to viewDidAppear. That is what "appear" means (as opposed to what "loaded") means.

A: There's great documentation on Apple's site here. Putting in simply though:

*

*ViewWillAppear - This method is called before the view controller's view is about to be added to a view hierarchy and before any animations are configured for showing the view. You can override this method to perform custom tasks associated with displaying the view. For example, you might use this method to change the orientation or style of the status bar to coordinate with the orientation or style of the view being presented.


text:
Q: Add multiplier to NSLayoutAnchor constraints in Swift Anchor constraints simplify adding constraints but the multiplier property available in storyboard does not seem to be available for all types of constraints.
For example, as per the answer here, you can center a label in a view with:
view.addSubview(loadingLabel)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loadingLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

However, apparently, while you can set the multiplier for length constraints as in:
someView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4)
You cannot add a similar parameter to the CenterX or CenterY parameter, possibly because Apple doesn't think that makes sense for a point, although you can do this in Storyboard as discussed in this question.
What is the best way to add a multiplier to the constraints for centering a point in order to make the point a proportion of the screen size from the top?

A: You can't add multipliers to the anchor methods for X and Y axis constraint, they are only available for the dimensional anchors. But, the NSLayoutContraint has an option for setting the multiplier. So for example, if you want to set the label in the middle of the top and centre of the super view along the Y axis here's how you do this:
view.addSubview(loadingLabel)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
NSLayoutConstraint(item: loadingLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 0.5, constant: 0).isActive = true


text:
Q: Android how to write int values to a buffer and take values from the buffer using a timer? I am working on an Android application which is receiving UDP packets, parsing to an int array and passing to another method. What I need is that, the values should stored in a buffer, then take the values from the buffer and plot in a graph. After that the buffer memory should be freed up. I am not aware on how to save the int array values to a buffer and take the values from the buffer using timer. Could anyone please help me on this?

A: Finally I found a way to solve my issue.
For storing the values to a buffer I have used ArrayList.
public void dataFromJnich0(int ch0[] ){
    for (int index = 0; index < ch0.length; index++) {
        ch0Buffer.add(ch0[index]);
    }
    plotGraph();
}

Instead of Timer I have used Thread.sleep for solving my issue.
    public void plotGraphs() {
    runOnUiThread(new Runnable() {
        public void run() {
            addEntryGraph0();
            addEntryGraph1();
            addEntryGraph2();
            addEntryGraph3();
            addEntryGraph4();
            addEntryGraph5();
            ch0Buffer.subList(0, 100).clear();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}


text:
Q: Encrypting mails with special characters in attachment names I'm using MimeKit for creating s/mime encrypted mails with attachments.
As soon as an attachment name has special chars, e.g. äüö, the attachemnt name gets lost and is displayed like "unnamend attachment 123.dat" in Outlook.
Unencrypted mails do fine, so the only difference is just msg.Encrypt(context).
Are there some constraints in MimeKit regarding this use case or do I have to do more to get this working?

A: Iterate over the ContentType and ContentDisposition parameters of the attachment (before encrypting) and set the EncodingMethod of each parameter to ParameterEncodingMethod.Rfc2047.
The problem is probably that Outlook can't handle rfc2231-style encoding of parameter values.
example:
foreach (var param in attachment.ContentType.Parameters)
    param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
foreach (var param in attachment.ContentDisposition.Parameters)
    param.EncodingMethod = ParameterEncodingMethod.Rfc2047;


text:
Q: How to debug why my "Form Events Exercise" program is not working?
Form Events Exercise
Time to get some practice working with forms and form events! index.html already has a form element that contains two  elements, one for quantity and one for a product name.  index.html also contains an empty
 where you will append new
's.  Watch the gif at the bottom for an overview of how your code should work. Your task is to follow these steps:
Listen for the form submission
When the form is submitted, prevent the default behavior
Grab the quantity input value and the product input value
Create a new
 element.  Set the text on the new
 to include the quantity and product name from the form.
Append the new
 to the
 on the page
Reset the inputs
Please note:

*

*Udemy's interface does not yet recognize some of the newer JS syntax, e.g., .append()
You will need to use alternate (older) syntax for this method in order to get the tests to pass.

*The form will need to be assigned to a variable named form for the test to pass, I've already included this line of code for you in the app.js code

index.html
<!DOCTYPE html>

    <title>Grocery List</title>

Grocery List

    <form action="/nowhere">
        Enter A Product
        <input type="text" id="product" name="product">
        Enter A Quantity
        <input type="number" id="qty" name="qty">
        <button>Submit</button>
    </form>

app.js
const form = document.querySelector('form');
const qty = document.querySelector('#qty');
const product = document.querySelector('#product');
const list = document.querySelector('#list');

form.addEventListener('submit', function (e){
    e.preventDefault();
    const productName = input.value;
    const qtyItem = input.value;
    const li = document.createElement('LI');

    li.innerText = product;
    li.innerText = qty;
    list.appendChild(product);
    list.appendChild(qty);

});

A: I'm also currently taking Colt's class. Here is my solution:
const form = document.querySelector('form');
const qty = document.querySelector('#qty');
const product = document.querySelector('#product');
const list = document.querySelector('#list');

form.addEventListener('submit', function (e){
    e.preventDefault();
    //change your input in input.value to the id set in the html
    const productName = product.value;
    const qtyItem = qty.value;
    const li = document.createElement('LI');

    //this code: the second line will override the first line
    //li.innerText = product;
    //li.innerText = qty;
    //solution: join them
    li.innerText = qtyItem + " " + productName;
    list.appendChild(li);
    //add this line of code to empty the input after pressing submit
    product.value="";
    qty.value="";

});

A: const form = document.querySelector('form');
const product = document.querySelector('#product');
const quantity = document.querySelector('#qty');
const list = document.querySelector('#list');

form.addEventListener("submit", function(e){
    e.preventDefault();
    const text1 = product.value;
    const text2 = quantity.value;
    const newLI = document.createElement("li");

    newLI.innerText = `${text2} ${text1}`;
    list.appendChild(newLI);

    product.value = "";
    qty.value = "";
});


text:
Q: How to insert this array to mysql using loop? How to insert this array [$obj] to mysql using loop?
Array
(
    [apple] => Array
        (
            [0] => fruit
            [1] => 15
        )

    [cat] => Array
        (
            [0] => animal
            [1] => 400
        )

    [pumpkin] => Array
        (
            [0] => vegetables
            [1] => 20
        )

    [orange] => Array
        (
            [0] => fruit
            [1] => 30
        )
)

I want to insert array [$obj] into mysql using loop like this.
|___id__|___ product__|_____type_____|__price__|
|   1   |     apple   |    fruit     |    15   |
|   2   |     cat     |    animal    |    400  |
|   3   |   pumpkin   |  vegetables  |    20   |
|   4   |    orange   |    fruit     |    30   |

How can I do this?
Thank you.

A: $sql = "INSERT INTO tableName (product, type, price) VALUES";
foreach($array as $key => $value)
{
    $sql += " ('$key', '$value[0]', $value[1]),";
}
$sql +=  substr_replace($sql,"",-1). ";";
//perform your INSERT here.

Be sure to replace tableName and $array by their respective names

A: try this out $obj is your array
$finalarray = array();
foreach($obj as $main_key=>$main_value)
{
$product = $main_key;
$type = $main_value[0];
$price = $main_value[1];
$string = "('','$product','$type','$price')";
$finalarray[] = $string;

}
$final_values_array = implode(',',$finalarray);
mysql_query("INSERT INTO TABLENAME('id','product','type','price') VALUES $final_values_array");

A: Try This one
$array=Array
(
    [apple] => Array
        (
            [0] => fruit
            [1] => 15
        )

    [cat] => Array
        (
            [0] => animal
            [1] => 400
        )

    [pumpkin] => Array
        (
            [0] => vegetables
            [1] => 20
        )

    [orange] => Array
        (
            [0] => fruit
            [1] => 30
        )
)
$query = "INSERT INTO tableName (product, type, price) VALUES";
$sub='';
foreach($array as $key => $value)
{
    $sub.="('$key', '$value[0]', $value[1]), ";
}
$sql = $query . substr_replace($sub,"",-1);

This is batch insert


text:
Q: Twitter API 2.0 - Unable to fetch user.fields I am using API version 2.0 and unable to fetch the user.fields results. All other parameters seem to be returning results correctly. I'm following this documentation.
url = "https://api.twitter.com/2/tweets/search/all"

query_params = {
    "query": "APPL",
    "max_results": "10",
    "tweet.fields": "created_at,lang,text,author_id",
    "user.fields": "name,username,created_at,location",
    "expansions": "referenced_tweets.id.author_id",
}

response = requests.request("GET", url, headers=headers, params=query_params).json()

Sample result:
{
  'author_id': '1251347502013521925',
  'text': 'All conspiracy. But watch for bad news on Apple.  Such a vulnerable stocktechnically for the biggest market cap @ $2.1T ( Thanks Jay). This is the glue for the bulls. But, they stopped innovating when Steve died, built a fancy office and split the stock. $appl',
  'lang': 'en',
  'created_at': '2021-06-05T02:33:48.000Z',
  'id': '1401004298738311168',
  'referenced_tweets': [{
    'type': 'retweeted',
    'id': '1401004298738311168'
  }]
}

As you can see, the following information is not returned: name, username, and location.
Any idea how to retrieve this info?

A: Your query does actually return the correct data. I tested this myself.
A full example response will be structured like this:
{
  "data": [
    {
      "created_at": "2021-06-05T02:33:48.000Z",
      "lang": "en",
      "id": "1401004298738311168",
      "text": "All conspiracy. But watch for bad news on Apple.  Such a vulnerable stocktechnically for the biggest market cap @ $2.1T ( Thanks Jay). This is the glue for the bulls. But, they stopped innovating when Steve died, built a fancy office and split the stock. $appl",
      "author_id": "1251347502013521925",
      "referenced_tweets": [
        {
          "type": "retweeted",
          "id": "1401004298738311168"
        }
      ]
    }
  ],
  "includes": {
    "users": [
      {
        "name": "Gary Casper",
        "id": "1251347502013521925",
        "username": "Hisel1979",
        "created_at": "2020-07-11T13:39:58.000Z"
      }
    ]
  }
}

The sample result you provided comes from within the data object. However, the expanded object data will be nested in the includes object (in your case name, username, and location). The corresponding user object can be referenced via the author_id field.


text:
Q: Return result of an mysql function I have installed this Levenshtein function in MYSQL. The maker advises to use this:
select levenshtein('butt', 'but') from test;
select levenshtein_ratio('butt', 'but') from test;

I want to calculate the Levenshtein Ratio between $search and each "name" entry in the DB and then echo it in PHP.
How can I accomplish that? Thanks in advance
$search = "Paul"; // The string I want compared to each DB entry

$query = "SELECT name, ??? FROM names"; // What's the MYSQL I need to use?

$response = @mysqli_query($dbc, $query);

while($row = mysqli_fetch_array($response)){

  echo "Levenshtein Ratio: ".$row['???'];
  echo "
";

}

A: You need to use an alias the function return
SELECT levenshtein('butt', 'but') as levenshtein FROM

then it can be accessed from the levenshtein index.
$row['levenshtein']

Also note:

In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

So if you didn't want the alias you could do:
$row[1]

this is less readable/maintainable to me though.
When in doubt about what an array contains you can check it with print_r or var_dump. Those will give you the indices and the values the array has.

A: How about this ?
<?php

$search = "Paul"; // The string I want compared to each DB entry
$query = "SELECT name, levenshtein(name, '".mysqli_real_escape_string ($dbc, $search)."') AS result FROM names";

$result = @mysqli_query($dbc, $query);

while($row = mysqli_fetch_array($result)){

  echo "Levenshtein Ratio for ".$row['name'].' : '.$row['result']."
";

}


text:
Q: "Value does not fall within the expected range" exception in ListView For Windows 8 application development environment.
Code:
   var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
   listView.ItemsSource = deserialized; // error

Data model:
    public class C
    {
        public List<Y> programs { get; set; }
        public string name { get; set; }
        public int code { get; set; }
    }
    public class RootObject
    {
        public List<C> cs { get; set; }
        public string date { get; set; }
    }
    public class Y
    {
        public string category { get; set; }
        public string time { get; set; }
        public string name { get; set; }
    }

What can I do ? I don't find solution.

A: ItemsSource is looking for an IEnumerable, but you're providing a single object in RootObject. You'd get the same error if you create one of your RootObject instances in code and try the same assignment.
What specifically should be displaying in the list?  If you simply change your code to:
listView.ItemsSource = deserialized.cs;

the listView should display your C objects.

A: I always have trouble figuring out how to go from the serializer output.  I do have working code (windows 8 store) that I'm pasting below.  It is pretty obvious what it does.
                HttpResponseMessage responseGetEmailByPersonsBare =
                         await clientGetEmailByPersonsBare.PostAsync(UrlBase + EmailDetailGetEmailByPersonsBare, contentGetEmailByPersonsBare);
                     Stream myStream = await responseGetEmailByPersonsBare.Content.ReadAsStreamAsync();
                     var djsGetEmailByPersonsBare = new DataContractJsonSerializer(typeof(AEWebDataStructures.RootObjectEmailDetail));

                     var rootObjectEmailDetail = (AEWebDataStructures.RootObjectEmailDetail)djsGetEmailByPersonsBare.ReadObject(myStream);
                     responseGetEmailByPersonsBare.EnsureSuccessStatusCode();
                     returnTaskInfo.EmailDetails = rootObjectEmailDetail.Data;
                     returnTaskInfo.StatusReturn = AEWebDataStructures.StatusReturn.Success;


text:
Q: Kohana: Cannot redeclare class Unable to start project in Kohana. I have cloned it from github, than set my database info in config file and get error: Cannot redeclare class.
I have 2 methods autoload functions.
public static function auto_load($class, $directory = 'classes')
    {
        // Transform the class name according to PSR-0
        $class     = ltrim($class, '\\');
        $file      = '';
        $namespace = '';

        if ($last_namespace_position = strripos($class, '\\'))
        {
            $namespace = substr($class, 0, $last_namespace_position);
            $class     = substr($class, $last_namespace_position + 1);
            $file      = str_replace('\\', DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR;
        }

        $file .= str_replace('_', DIRECTORY_SEPARATOR, $class);

        if ($path = Kohana::find_file($directory, $file))
        {
            // Load the class file
            require_once $path;

            // Class has been found
            return TRUE;
        }

        // Class is not in the filesystem
        return FALSE;
    }

    /**
     * Provides auto-loading support of classes that follow Kohana's old class
     * naming conventions.
     *
     * This is included for compatibility purposes with older modules.
     *
     * @param   string  $class      Class name
     * @param   string  $directory  Directory to load from
     * @return  boolean
     */
    public static function auto_load_lowercase($class, $directory = 'classes')
    {
        // Transform the class name into a path

        $file = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class));

        if ($path = Kohana::find_file($directory, $file))
        {
            // Load the class file
                require_once $path;

            // Class has been found
            return TRUE;
        }
        // Class is not in the filesystem
        return FALSE;
    }

I have tried to add class_exists() before require() but it doesn't work& What I should do to start a project?

A: Possibly required class is included in some other file already.
I don't know how exactly you check class collision problem, but you should do something like:
function include_quietly($file) {
 $conflicts = false;
 $txt = file_get_contents($file);
 preg_match_all("#class\s+(\w+)\s*{#muis", $txt, $matches, PREG_SET_ORDER);

 foreach ($matches as $m) {
   if (class_exists($m[1])) {
     $conflicts = true;
     break;
   }
 }

 if (!$conflicts)
   include_once $file;
 else
   echo "include conflicts in file {$file}\n";
}

include_quietly($path);


text:
Q: Setting custom labels on stacked ggplot2 plot This question is a continuation of my previous question here.
I have a heatmap with a dataset available.  The dataset is pasted below:
library(ggplot2)
library(colorspace)
library(directlabels)

smalltest <- structure(list(x = c(-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
                                  -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -8,
                                  -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -8, -7,
                                  -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -8, -7, -6,
                                  -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -8, -7, -6, -5,
                                  -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8),
                            y = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                                 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
                                 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4,
                                 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5,
                                 5, 5, 5, 5, 5, 5, 5, 5),
                            z = c(0.353727812855041, 0.512450876310741,
                                  0.668920303216554, 0.770942367746301, 0.829915628317595, 0.873001682466956,
                                  0.900219155289838, 0.918353789896507, 0.936488424503176, 0.954641684205298,
                                  0.961439844045867, 0.972770110446816, 0.975042372092157, 0.981846740297877,
                                  0.986385055223408, 0.986385055223408, 0.986385055223408, 0.33104865495769,
                                  0.464820298870698, 0.62128351741136, 0.752801524774481, 0.804964208774903,
                                  0.850322524569605, 0.879812259037828, 0.913821683336127, 0.934222371222986,
                                  0.950109577644919, 0.959173790765678, 0.970504057166626, 0.975042372092157,
                                  0.981846740297877, 0.986385055223408, 0.986385055223408, 0.986385055223408,
                                  0.31064175870568, 0.428544821292209, 0.589558771488704, 0.725596468681902,
                                  0.786835782533385, 0.838986049803505, 0.872995474101805, 0.897946893644497,
                                  0.920613634811545, 0.943299001074047, 0.956907737485488, 0.970504057166626,
                                  0.970504057166626, 0.981840531932726, 0.986385055223408, 0.986385055223408,
                                  0.986385055223408, 0.29023486245367, 0.419493024901753, 0.569145666871543,
                                  0.702929727514853, 0.775480682671832, 0.827655783402557, 0.866197314261236,
                                  0.891148733803927, 0.916075319886014, 0.931943901212494, 0.952369422559957,
                                  0.970504057166626, 0.970504057166626, 0.981840531932726, 0.981840531932726,
                                  0.986385055223408, 0.986385055223408, 0.272100227847001, 0.396807658639251,
                                  0.557778150279687, 0.691580836018451, 0.766410261185922, 0.807248887150547,
                                  0.857126892775325, 0.888876472158586, 0.911543213325635, 0.929684056297455,
                                  0.941020531063555, 0.959155165670224, 0.968231795521285, 0.977302217007196,
                                  0.981840531932726, 0.984112793578067, 0.984112793578067, 0.265302068006432,
                                  0.396789033543797, 0.557784358644838, 0.680244361252351, 0.761871946260391,
                                  0.800444518944826, 0.841264519813997, 0.882078312318017, 0.909277160045445,
                                  0.931950109577645, 0.941014322698404, 0.954623059109845, 0.961421218950414,
                                  0.972763902081665, 0.977302217007196, 0.984112793578067, 0.984112793578067)),
                       row.names = c(NA, -102L), class = c("tbl_df", "tbl", "data.frame"))

I can generate a heatmap and contour lines based on the dataset presented above.
    ggplot(smalltest, aes(x = x, y = y)) +
      geom_tile(aes(fill = z)) +
      scale_fill_continuous_divergingx(palette = 'RdBu', rev = FALSE, mid = 0.9, l3 = 0, p3 = 0.95, p4 = 0.85) +
      scale_x_continuous(expand = c(0, 0), breaks = -8:8) +
      scale_y_continuous(expand = c(0, 0), breaks = 0:5) +
      geom_contour(aes(z = z), breaks = c(0.8, 0.9, 0.95), color = 'black', size = 1) +
      geom_dl(aes(label = c(rep(NA, 99), 'Low', 'Middle', 'High')), method = 'last.points')

I have the following questions:

*

*How do I have the geom_dl() only look/use the ends or the sides of the contour lines for those labels?  I added the rep(NA,99) initially as I get an error stating that the length of label must either be equal to 1 or the length of the dataset (102 here).  But how can I simply just pass through a vector of custom strings?

*How do I extend the contour lines to the ends of the tile?

Thanks!
Created on 2019-11-07 by the reprex package (v0.3.0)


text:
Q: How do I ensure the Internet works on Windows 7 with 2 simultaneous wireless connections? My church has two separate wireless networks, one called ChurchInternet which broadcasts on a 2.4 GHz frequency and another called ChurchAudio which broadcasts on a 5 GHz frequency. Both are broadcast by (separate) Linksys routers. ChurchInternet is connected to the Internet while ChurchAudio has no Internet connectivity and is used for connecting to the sound equipment (we have a nice new mixer). We don't want anyone connecting to the ChurchAudio (which is why it's separate), but we do allow people with the password to connect to ChurchInternet.
We've got a desktop computer running Windows 7 in the church that we would like to be able to connect to both. This computer has two separate USB wireless adapters.
One of the adapters is a little older than the other, and can only see 2.4 GHz networks. So I obviously want that one to connect to ChurchInternet. That first adapter is called Wireless Connection 13
The second (newer) adapter is capable of seeing both 2.4 GHz and 5 GHz networks. So that has to be the one to connect to the 5 GHz ChurchAudio network. That one is called Wireless Connection 5
Unfortunately, I can't seem to get it to work correctly — for two big reasons:

*

*By default, both adapters try to connect to ChurchInternet. This is obviously not desirable, but I don't know how to make it not do that by default. Here's what it looks like on start up:

And this is what ipconfig looks like on initial start up:

I blurred it out here but I can tell you that it gives itself two different sets of IP addresses for the same connection. This is bad and I don't want it to do that! I want it be smart enough to know that Wireless Connection 5 should connect to ChurchAudio instead.

*Even after I manually disconnect Wirless Connection 5 from ChurchInternet and then manually tell it connect to connect to ChurchAudio instead, I become unable to actually use the Internet, and I have no idea why. Everything at that point looks like it should be working — this is what I see in Windows Network & Sharing Center:

But that graphic is deceiving. Even though it says it has Internet access, and recognizes that the ChurchInternet network has Internet access, I can't actually connect to anything. Ping requests time out. Browser requests just get stuck on a blank screen before eventually dying. By all accounts, it seems like it's trying to reach the Internet through ChurchAudio while completely ignoring the fact that it's connected to ChurchInternet.
How do I get this working?

A: Here's what has worked for me on several occasions:
Try setting the interface metric of Wireless Network Connection 13 to a low value like 1.And set the metric of Wireless Network Connection 5 to a higher value like 10.
Here's how you do this:

*

*In the Run command box (Win+R), enter shell:ConnectionsFolder

*Select Wireless Network Connection 13 and press Alt+Enter

*In the Properties window that pops up, scroll down to find:Internet Protocol Version 4 (TCP/IPv4) and double click it.

*In the window that pops up, click the Advanced button and uncheck Automatic metric and set the interface metric to a low value like 1 and click OK.

Do the same thing with Wireless Network Connection 5 but set its interface metric to a higher value (like 10, for instance).
For further reference, take a look at this HowToGeek article or this SuperUser question.

A: Either it's windows being stuffy (Which you can't do anything about). Or you only have one wireless networking card. IF thats the case and you're on a desktop you can buy another card like these: http://www.amazon.com/b?node=13983711 if you're on a laptop there's nothing you can do short of extreme hardware mods.


text:
Q: .NET NamedPipeServerStream problem - consecutive Reads return the same data I'm having a problem with NamedPipeServerStream - when my code reads data it's just repeating the output of the last Read without grabbing the new data.
Here's the smallest server code example that exhibits this behaviour:
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static NamedPipeServerStream NPSS;

        static void Main(string[] args)
        {
            string PipeName = "Test1";

            // create asynchronous pipe server
            NPSS = new NamedPipeServerStream(PipeName, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
            IAsyncResult resultConnect = NPSS.BeginWaitForConnection(NamedPipeConnectionCallback, null);

            Console.WriteLine("Press X to exit\n\n");
            while (Console.ReadKey(true).Key != ConsoleKey.X);

        }

        static void NamedPipeConnectionCallback(IAsyncResult resultConnection)
        {
            try
            {
                NPSS.EndWaitForConnection(resultConnection);
            }
            catch (OperationCanceledException) // this happens when calling thread (Main function) exits
            {
                return;
            }

            while (NPSS.CanRead)
            {
                // small buffer for demonstration purposes; it's much larger in the
                //  actual code, but still exhibits same problem
                byte[] PipeDataBuffer = new byte[16];
                MemoryStream MessageStream = new MemoryStream();
                int TotalBytesRead = 0;

                do
                {
                    int BytesRead = NPSS.Read(PipeDataBuffer, 0, PipeDataBuffer.Length);
                    MessageStream.Write(PipeDataBuffer, 0, BytesRead);
                    TotalBytesRead += BytesRead;
                } while (!NPSS.IsMessageComplete);

                byte[] Message = MessageStream.ToArray();

                if (Message.Length == 0)
                    break;

                Console.WriteLine(String.Format("Message received, {0} bytes:", TotalBytesRead));
                Console.WriteLine(new ASCIIEncoding().GetString(Message));
            }

            NPSS.Disconnect();
            NPSS.BeginWaitForConnection(NamedPipeConnectionCallback, null);
        }
    }
}

This is the test client (written in DOS assembler, NASM-style, compiles to .COM file). All it does is opens the pipe as a file (\.\pipe\Test1) and writes some data to it:
; NPTEST2.ASM
; - tests communication with named pipe

  org 0x100

  push cs
  pop ds

  mov si, pipename   ; path
  mov bx, 0x42       ; access/sharing mode
  mov cx, 0          ; attributes
  mov dx, 1          ; open file (not create/truncate)
  mov ax, 0x716c     ; long filename open
  int 0x21

  jc quit
  push ax            ; file handle returned in ax

  pop bx             ; file handle
  push bx
  mov ah, 0x40       ; write
  mov cx, (testdata_end-testdata)  ; size
  mov dx, testdata   ; ptr to data
  int 0x21

  pop bx             ; file handle
  mov ah, 0x3e       ; close
  int 0x21

quit:
  mov ah,0x4c        ; quit
  int 0x21

pipename:
  db "\\.\pipe\Test1",0

testdata:
  db "!", 0x22, "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
testdata_end:

And here is a typical output of the server, in this case from running the client three times in succession:

Press X to exit

Message received, 110 bytes:
!"#$%&'()*+,-./0!"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
Message received, 94 bytes:
!"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
Message received, 94 bytes:
!"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

As you can see, the first message is 16 bytes (i.e. one buffer length) longer than it should be, because the first 16 bytes is repeated at the beginning.
So far I've tried changing:

*

*the transmission mode from message to byte

*running the client and server on different hosts rather than just local

*using the async BeginRead and EndRead calls instead of Read

*converting the code to be entirely synchronous, using just WaitForConnection and Read
but none of this made any difference to the problem.
Can anyone please shed any light on what I'm doing wrong here, or other things I can check? Thanks!
EDIT: Further research - what has made a difference is using a Windows test client rather than one running under the NTVDM (DOS machine). That is, this code:
int main(int argc, char* argv[])
{
    FILE *f = fopen("\\\\.\\pipe\\Test1", "r+b");
    if (f)
    {
        fwrite("!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 94, 1, f);
        fclose(f);
    }
    return 0;
}

which should be equivalent to the DOS assembler code above, actually behaves properly.
Running Process Monitor when the test clients are running shows that the DOS one occasionally has a result of CANCELLED for WriteFile, whereas the Windows client does not. A bit of a problem as this is supposed to be an addon for a DOS program :(

A: The first thing I'd try changing is here:
            do
            {
                // !!! problematic function call here !!!
                int BytesRead = NPSS.Read(PipeDataBuffer, 0, PipeDataBuffer.Length);
                // !!!
                MessageStream.Write(PipeDataBuffer, 0, BytesRead);
                TotalBytesRead += BytesRead;
            } while (!NPSS.IsMessageComplete);

It doesn't check that BytesRead is +ve; now I would expect MessageStream.Write to explode if it was negative, but... either way; I would definitely check for an unexpected <=0 condition there.

A: I figured it out.
( it wasn't a problem in NamedPipeServerStream.)
Looks like it was due to a poor choice of DOS system calls. If I use the open call via INT 0x21 / AH=0x3D, it works without problems. The stack trace in Process Monitor shows a very different code path for this method too. It's all rather odd, but at least it's working. I guess this technical information is useful to no-one else in the world but I thought I'd update anyway :)
; NPTEST3.ASM
; - tests communication with named pipe

  org 0x100

  push cs
  pop ds

  mov dx, pipename   ; path
  mov ax, 0x3d42     ; open
  int 0x21

  jc quit
  push ax            ; file handle returned in ax

  pop bx             ; file handle
  push bx
  mov ah, 0x40       ; write
  mov cx, (testdata_end-testdata)  ; size
  mov dx, testdata   ; ptr to data
  int 0x21

  pop bx             ; file handle
  mov ah, 0x3e       ; close
  int 0x21

quit:
  mov ah,0x4c        ; quit
  int 0x21

pipename:
  db "\\.\pipe\Test1",0

testdata:
  db "!", 0x22, "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
testdata_end:


text:
Q: `0x15` returns 00010101, not Hi I'm mangling with the bit-wise representation in c programming
I printed out 0x15 expecting 0000 1111 but got 0001 0101. Which is 0x21.
I used this macro to print out the number in binary
#include <stdio.h>

#define BYTE_TO_BINARY_PATTERN_1BYTE "%c%c%c%c %c%c%c%c"
#define BYTE_TO_BINARY(byte)    \
    (byte & 0x80 ? '1' : '0'), \
    (byte & 0x40 ? '1' : '0'), \
    (byte & 0x20 ? '1' : '0'), \
    (byte & 0x10 ? '1' : '0'), \
    (byte & 0x08 ? '1' : '0'), \
    (byte & 0x04 ? '1' : '0'), \
    (byte & 0x02 ? '1' : '0'), \
    (byte & 0x01 ? '1' : '0')

int main(){
    printf(BYTE_TO_BINARY_PATTERN_1BYTE, BYTE_TO_BINARY(0x15));
    printf("\n");
    return 0;
}

I'm suspecting that maybe there is a specific way a hexadecimal literals are saved in the memory, could anyone see what I'm missing here?
Or, the Hexadecimals are saved as 4bytes in the memory and there is some sort of error in the macro script that I'm using?

A: 15 would give you 00001111.
But 0x15 will give you 00010101, which is 21 (not 0x21).


text:
Q: How to solve TemplateRuntimeError: no test named '>' when compile chromium? When compile chromium, I get the following error messages:
ninja: Entering directory `out/Cros'
[44/32769] ACTION //components/exo/wayland/compatibility_test:generated_client_event_receiver_version_tests(//build/toolchain/linux:clang_x64)
FAILED: gen/components/exo/wayland/compatibility_test/all_generated_client_event_receiver_version_tests.cc
python3 ../../components/exo/wayland/compatibility_test/wayland_protocol_codegen.py ../../third_party ../../buildtools/linux64/clang-format ../../components/exo/wayland/compatibility_test/template_client_event_receiver_version_tests.cc.tmpl gen/components/exo/wayland/compatibility_test/all_generated_client_event_receiver_version_tests.cc ../../components/exo/wayland/protocol/aura-shell.xml ../../third_party/wayland/src/protocol/wayland.xml ../../third_party/wayland-protocols/src/stable/presentation-time/presentation-time.xml ../../third_party/wayland-protocols/src/stable/viewporter/viewporter.xml ../../third_party/wayland-protocols/src/stable/xdg-shell/xdg-shell.xml ../../third_party/wayland-protocols/src/unstable/fullscreen-shell/fullscreen-shell-unstable-v1.xml ../../third_party/wayland-protocols/src/unstable/input-timestamps/input-timestamps-unstable-v1.xml ../../third_party/wayland-protocols/src/unstable/linux-dmabuf/linux-dmabuf-unstable-v1.xml ../../third_party/wayland-protocols/src/unstable/linux-explicit-synchronization/linux-explicit-synchronization-unstable-v1.xml ../../third_party/wayland-protocols/src/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml ../../third_party/wayland-protocols/src/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml ../../third_party/wayland-protocols/src/unstable/relative-pointer/relative-pointer-unstable-v1.xml ../../third_party/wayland-protocols/src/unstable/text-input/text-input-unstable-v1.xml ../../third_party/wayland-protocols/src/unstable/xdg-shell/xdg-shell-unstable-v6.xml ../../third_party/wayland-protocols/unstable/alpha-compositing/alpha-compositing-unstable-v1.xml ../../third_party/wayland-protocols/unstable/color-space/color-space-unstable-v1.xml ../../third_party/wayland-protocols/unstable/cursor-shapes/cursor-shapes-unstable-v1.xml ../../third_party/wayland-protocols/unstable/gaming-input/gaming-input-unstable-v2.xml ../../third_party/wayland-protocols/unstable/keyboard/keyboard-configuration-unstable-v1.xml ../../third_party/wayland-protocols/unstable/keyboard/keyboard-extension-unstable-v1.xml ../../third_party/wayland-protocols/unstable/notification-shell/notification-shell-unstable-v1.xml ../../third_party/wayland-protocols/unstable/remote-shell/remote-shell-unstable-v1.xml ../../third_party/wayland-protocols/unstable/secure-output/secure-output-unstable-v1.xml ../../third_party/wayland-protocols/unstable/stylus/stylus-unstable-v2.xml ../../third_party/wayland-protocols/unstable/stylus-tools/stylus-tools-unstable-v1.xml ../../third_party/wayland-protocols/unstable/vsync-feedback/vsync-feedback-unstable-v1.xml
Traceback (most recent call last):
  File "../../components/exo/wayland/compatibility_test/wayland_protocol_codegen.py", line 120, in <module>
    main()
  File "../../components/exo/wayland/compatibility_test/wayland_protocol_codegen.py", line 111, in main
    expanded = expand_template(args.template,
  File "../../components/exo/wayland/compatibility_test/wayland_protocol_codegen.py", line 58, in expand_template
    return env.get_template(os.path.basename(template)).render(context)
  File "/usr/lib/python3/dist-packages/jinja2/environment.py", line 989, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/lib/python3/dist-packages/jinja2/environment.py", line 754, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python3/dist-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "../../components/exo/wayland/compatibility_test/template_client_event_receiver_version_tests.cc.tmpl", line 32, in <module>
    {% if interface.events|selectattr("since")|selectattr("since", ">", min_version)|list|length %}
  File "/usr/lib/python3/dist-packages/jinja2/filters.py", line 750, in do_list
    return list(value)
  File "/usr/lib/python3/dist-packages/jinja2/filters.py", line 942, in _select_or_reject
    if modfunc(func(transfunc(item))):
  File "/usr/lib/python3/dist-packages/jinja2/filters.py", line 935, in <lambda>
    func = lambda item: context.environment.call_test(
  File "/usr/lib/python3/dist-packages/jinja2/environment.py", line 449, in call_test
    raise TemplateRuntimeError('no test named %r' % name)
jinja2.exceptions.TemplateRuntimeError: no test named '>'
[61/32769] CXX obj/mojo/public/tools/fuzzers/fuzz_mojom_blink/fuzz.mojom-blink.o
ninja: build stopped: subcommand failed.

I was not sure if it's related to the version of jinja2.
And mine is v2.8 for sure.
autoninja -C out/Default is OK with me.
This question appears when I try to compile CrOS on my Ubuntu 16.04.
And autoninja -C out/Cros chrome is also fine. @_@

A: Find the reason!
It was because that ninja used jinja2 in the system instead of the version under src/third_party dir.
I solved this problem by uninstalling system jinja2.
Thanks for the guidance of tikuta@chromium.org. \o/