text:
Q: awk: Create new record and update NR More of a general question rather than a specific problem to solve.
Say I have a file like
entry 1
entry 3
entry 6

And I want to fill in the missing entries via awk. Could one insert a new record and update NR? Idea is:
awk 'BEGIN {print "NR","line"
     $2!=NR {<create record> "entry",NR ; <repeat commands on same record>}
     {print NR,$0}' file

So the command would:

*

*insert a new record

*give the new record the matching NR and update the following record numbers

*have the ability to recheck the condition (i.e.: when entry 6 is reached, it should create entry 4 but realize that entry 5 is missing, too. So it should recheck the condition for the entry 6 record)

Desired output
NR line
1  entry 1
2  entry 2
3  entry 3
4  entry 4
5  entry 5
6  entry 6

A: You cannot create a new input record in one pass of an input file. Creating a new input record would mean that this code:
awk '
    {
        print $0
        magic to create a new record with contents "Foo"
    }
'

would print the original record then enter an infinite loop printing "Foo" because by definition awk executes the above code once per input record.
You can do things to execute code on strings whether they're from an input record or created internally, e.g.:
awk '
    {
        prt($0)
        other stuff
        prt("Foo")
    }
    function prt(str) {
        print str
    }
'

but that's not the same as actually creating a new input record.
You could also do a 2-pass approach to create and write to a temp file on the first pass so that when reading the temp file for the second pass the newly printed strings are now present as input records.
You're overload/abusing the meaning of NR though. NR is the count of input records read, you're trying to print a count of output records printed which is a completely different thing. There is no builtin variable for that as it's trivial to just keep track of it yourself in a separate variable rather than messing with NR, e.g. with onr below:
$ cat file
awk '
    BEGIN { print "NR", "onr", "line" }
    NR == 1 { val = $2-1 }
    {
        for (val++; val<$2; val++) {
            processString($1 FS val)
        }
        processString($0)
    }

    function processString(str) {
        print NR, ++onr, str
    }
' file
NR onr line
1 1 entry 13
2 2 entry 14
2 3 entry 15
3 4 entry 16
3 5 entry 17
3 6 entry 18

Again though - we are NOT creating new input records and so (as always) it'd be completely inappropriate to try to adjust the value of the builtin variable NR. Instead we're simply generating new output records and keeping track of the total number of output records in a user-defined variable named onr.
I added both NR and onr to the output and changed the sample input to:
$ cat file
entry 13
entry 15
entry 18

to highlight that there's actually 3 separate data items in play:

*

*NR = the number of input records,

*onr = the number of output records,

*val = the value of the $2 to be printed for each record

and for clarity, cohesion, coupling, maintenance etc. of your program it's best not to overload any of them.

A: EDIT + Warning
As stated in the comments below, NR and FNR are by definition counters for input records and should therefore stay untouched. (Ref: gawk manual) Do not manipulate there values as suggested below despite the ability to do so without restriction! I'll leave this answer as a warning.

Okay, thanks to the comments of Jeff Schaller, Romeo Ninov and fra-san, the following approaches work:

*

*manually increasing NR or FNR

*use a properly defined loop with NR / FNR
Possible script:
awk 'BEGIN {print "NR","line"}
     $2 > NR { for (NR; NR<$2; NR++) print NR,"entry "NR }
     {print NR,$0}' infile

Replace NR by FNR to ensure proper numbering in case of multiple input files (and maybe still use NR++ to ensure the correct total number).
Hereby NR++ simulates updating NR, while the loop simulates rerunning commands on the same record (pseudo-opposite of the next statement) which in total makes it like a newly created record with matching NR (FNR).


text:
Q: Customizing default inputs? I wonder if it's possible to customize my C# application (winforms) to get a better design, I made a PSD (photoshop document) so I can generate png jpeg... pictures if I need them.
Example of a form like the one I want :

A: Indeed as it was pointed out in the comments, it is easy to use WPF (indows Presentation Foundation) to achieve that result, but if you really need that it must be made in windows forms I can help you with that...
ControlBox and Border
It seens that your form does not have a control box (minimize, maximize and close buttons)
to achieve that you can set
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None

I'm not sure if that galaxy behind your form is part of the application so i'll be considering that it is not
To achieve that irregular shape of the form we have to do a workaround here
Irregular Shape of the Form
we are going to set a Color to TransparentKey, so everything in the form in that specific color will be transparent, like it does not exists (if you click in that part it will go into de desktop or whatever application you have behind in your form)
So let's use a specific color which we will probably dont use in the form
form.TransparencyKey = Color.FromArgb(111, 111, 111); //You can do it by the editor

So in order to make that white part we are going to use an Panel and a PictureBox outsite of the Panel trying to copy the shape of your image
Stylized Inputs
To make it easier and reusable I'm going to make a userControl in this one
the usercontrol will have

*

*a Panel called HighLightPanel, its dock property will be set to Fill

*a Panel called BackColorPanel, it will be inside the HighLightPanel

*a PictureBox called InputPicture, its dock property will be set to Left, it will be inside BackColorPanel and its acessor will be public

*a TextBox called TextBox, its dock property wil be set to fill, it will be inside BackColorPanel, the BorderStyle Property set to None, you should set the size and font you most desize in this one, I'm going to use Segoe UI; 15,75pt and its acessor will be public

Now we have to make some properties in our UserControl to make it work without work in other controls
First in the SizeChanged event of the HighLightPanel we will make the BackColorPanel be exacly two points smaller in every direction and its position to 1;1 so we can see the HighLightPanel
 private void HighlightPanel_SizeChanged(object sender, EventArgs e)
 {
         this.BackColorPanel.Size = new Size(
              HighlightPanel.Width - 2,
              HighlightPanel.Height - 2);
 }

Now we will create two propertys to handle the Highlight Color
public Color HighlightBorderColor { get; set; }
public Color NonHighlightBorderColor { get; set; }

And in the Enter and Leave Property of our TextBox we are going to change the HighlightPanel
private void TextBox_Enter(object sender, EventArgs e)
{
    HighlightPanel.BackColor = HighlightBorderColor;
}
private void TextBox_Leave(object sender, EventArgs e)
{
    HighlightPanel.BackColor = NonHighlightBorderColor;
}

So now every time the user enter the Input it will appear that the Input has an Border in the specified Color
Now to enhance its usability to developers we will make some wrappers in its controls to be easier change property of child controls in the editor
public Image InputImage
{
    get { return InputPicture.Image; }
    set { InputPicture.Image = value; }
}
public PictureBoxSizeMode InputImageLayout
{
    get { return InputPicture.SizeMode; }
    set { InputPicture.SizeMode = value; }
}
public char PasswordCharacter
{
    get { return TextBox.PasswordChar; }
    set { TextBox.PasswordChar = value; }
}
public bool ShowInputImage
{
    get { return InputPicture.Visible; }
    set { InputPicture.Visible = value; }
}

In the InputImage set the picture you want for the User and the Key
Insert the two controls in the position you like
Position of the Form
if you want your form to be moveable without the border you will have to use this snippet, it is more easy in WPF
#region MoveForm
Point LastPoint;
bool ShouldMove;
private void form_MouseDown(object sender, MouseEventArgs e)
{
    LastPoint = e.Location;
    ShouldMove = true;
    this.TransparencyKey = Color.FromArgb(111, 111, 111);
}
private void form_MouseUp(object sender, MouseEventArgs e)
{
    ShouldMove = false;
}
private void form_MouseMove(object sender, MouseEventArgs e)
{
    if (ShouldMove)
    {
        this.Location = new Point(
             this.Location.X - LastPoint.X + e.X,
             this.Location.Y - LastPoint.Y + e.Y);
    }
}
#endregion

A: If you need a lot of special graphics effects learning WPF will indeed be a sound investement.
If all you want is that login screen, it is trivial in Winforms and doesn't take any horrible hacks as you've been told..
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.BackColor = System.Drawing.Color.LavenderBlush;
this.TransparencyKey = System.Drawing.Color.LavenderBlush;
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Text= "";

These seven lines are all it takes for a form to be transparent. I copied them from the Designer code; you can simply set the 7 Properties in the property grid.
Now add a panel, dock it to the bottom and give it the right color; add a picturebox and your other controls and you are set.
To create the two input groups you also need just a few regular controls and only a few simple lines of code:
You place one Panel, BorderStyle = FixedSingle; and add a Label and a TextBox to it. The Label  has AutoSize = False; and both ImageAlign and TextAlign are set to MiddleLeft. You assign an image to the Label's Image and prefix the Text with enough blanks to not overlap. Obviously you should define a PasswordChar for the 2nd TextBox. Now all you need is to script the Enter and Leave events to change the BackColor of the respective Panels between, say SystemColors.Control and SystemColors.MenuHighlight. Size the Labels to almost fill the Panels and you are done. Less code than the WPF version, I'd bet.
If you need such input an controls again and again, simply create Usercontrols for each type you need!
Here is an example of the limits you will hit: Wouldn't it be nice to add a dropshadow effect to the image? It is doable in Winforms. But it would involve painting that effect; this would take at least 15 or 20 lines of involved code instead of simply turning the effect on with (estimated) 1-3 simple lines.
Do you need any nice hover effects? Not easy, to say the least..
These limits will be all over the place, so it really depends on how fancy your requirements will get.
Maybe you should use this example as a starter to compare the two techniques and to warm you up to WPF?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to solve this weibull distribution equation using least square? $$f_y=e^{-[(A_y+\delta)/\gamma]^\delta}$$
I'm not sure how to I derive the least square method to solve the unknown parameter for delta and gamma. Any help would be appreciated.
What I did tried to do is to get along the line of bringing down the power of e using the ln function, and applied another ln function to the following equation after the first ln to bring down the delta. That's where I'm stuck at.


text:
Q: How to fix Vector Position within Struct Player object so it'll work with me.position in Main? I am teaching myself C++11 and this was one of my homework assignment, however the vector position; doesn't seem to work.
I've tried #include  and std::vector, nothing seems to work.
#include <iostream>
#include <string>
using namespace std;

struct Player
{
    string name;
    int hp;
    vector position;
};

int main()
{
   Player me;
   me.name = "Metalogic";
   me.hp = 100;
   me.position.x = me.position.y = me.position.z = 0;

   return 0;
}

I'd like for it to cout << player << hp << position

A:
I've tried #include and std::vector, nothing seems to work.

Your way to use the vector is wrong, you have to write in entries specifying index or to push_back(..) etc.
So of course you can  use a vector having 3 entries for memorizing x,y and z but what about to define a struct Position to be able to add additional behaviors on it (move etc) ?
struct Position {
  int x;
  int y;
  int z;
}

struct Player
{
    string name;
    int hp;
    Position position;
};

int main()
{
   Player me;
   me.name = "Metalogic";
   me.hp = 100;
   me.position.x = me.position.y = me.position.z = 0;

   return 0;
}

Note you can also have a default constructor initializing the x, y and z to 0 to not have to do each time
struct Position {
  Position() : x(0), y(0), z(0) {}
  int x;
  int y;
  int z;
}

struct Player
{
    string name;
    int hp;
    Position position;
};

int main()
{
   Player me;
   me.name = "Metalogic";
   me.hp = 100;

   return 0;
}

I'd like for it to cout << player << hp << position

hp and position are part of Player so std::cout << player is enough
Just adding the operator<<
#include <iostream>
#include <string>

struct Position {
  Position() : x(0), y(0), z(0) {}

  friend std::ostream& operator<<(std::ostream& os, const Position & p) {
     os << "[" << p.x << ' ' << p.y << ' ' << p.z << ']';
     return os;
  }
  int x;
  int y;
  int z;
};

struct Player
{
    friend std::ostream& operator<<(std::ostream& os, const Player & p) {
       os << p.name << ' ' << p.hp << ' ' << p.position;
       return os;
    }
    std::string name;
    int hp;
    Position position;
};

int main()
{
   Player me;
   me.name = "Metalogic";
   me.hp = 100;
   me.position.x = 123; // y and z use default value 0

   std::cout << me << std::endl;
   return 0;
}

Compilation and execution :
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall p.cc
pi@raspberrypi:/tmp $ ./a.out
Metalogic 100 [123 0 0]
pi@raspberrypi:/tmp $

A: #include <iostream>
#include <string>

struct Vector3D
{
    int x, y, z;
};

std::ostream& operator<<(std::ostream &os, Vector3D const &position)
{
    return os << '[' << position.x << ", " << position.y << ", " << position.z << ']';
}

struct Player
{
    std::string name;
    int hp;
    Vector3D position;
};

std::ostream& operator<<(std::ostream &os, Player const &player)
{
    return os << '\"' << player.name << "\" (" << player.hp << ") " << player.position;
}

int main()
{
    Player me{ "Metalogic", 100, {} };
    std::cout << me << '\n';

    Player you{ "Luigi", 900, { 1, 2, 3 } };
    std::cout << you << '\n';
}


text:
Q: (API) Finding an opportunity's "Project start date" and "Project end date" I'm creating a script that continuously pushes back an opportunity's close date to be greater than 2 months, and the project start date and project end date to be greater than 1 month.
I'm able to completely interact with the API and get the opportunity data (source), but I'm not able to find the data for the fields labeled as "Project start date" and "Project end date", as shown in the lightning dashboard interface:

Tl;dr; This data isn't returned by the API on an Opportunity object, so how do I find (and modify) this data?

A: I've found the answer by digging around the Metadata APIs. "Project Start Date" and "Project End Date" are just labels, and the field that holds that data has a different name entirely.
Project End Date is Last_Payment_Date_End_of_Payment_Sched__c
Project Start Date is Project_Start_Date_Invoice_Date__c


text:
Q: How to verify that auto start option for my android app is enabled or disabled I want to auto start my android app either at boot time or after installation of app. I have applied following code: (AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javacodegeeks.androidserviceonbootexample"
    android:installLocation="internalOnly"
    >

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

    <receiver
        android:name="com.javacodegeeks.androidserviceonbootexample.BroadcastReceiverOnBootComplete"
        android:enabled="true"
        android:exported="false"  android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_REPLACED" />
            <data android:scheme="package" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_ADDED" />
            <data android:scheme="package" />
        </intent-filter>
    </receiver>

    <service android:name="com.javacodegeeks.androidserviceonbootexample.AndroidServiceStartOnBoot"></service>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

(MainActivity)
       import android.app.Activity;
        import android.content.ComponentName;
        import android.content.Intent;
        import android.os.Build;
        import android.os.Bundle;

        import com.javacodegeeks.androidserviceonbootexample.R;

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String manufacturer = "xiaomi";
        if(manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
            //this will open auto start screen where user can enable permission for your app
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            startActivity(intent);
        }else if(Build.BRAND.equalsIgnoreCase("Letv")){

            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
            startActivity(intent);

        }
        else if(Build.BRAND.equalsIgnoreCase("Honor")){

            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
            startActivity(intent);

        }
    }
}

(OnBootCompleteBroadcastReciever.java)
    import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class OnBootCompleteBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            Toast.makeText(context,"BroadCast",Toast.LENGTH_LONG).show();
            Intent serviceIntent = new Intent(context, ServiceStartOnBoot.class);
            serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startService(serviceIntent);
        }

    }

}

(ServiceStartOnBoot.java)
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class ServiceStartOnBoot extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}

But the above code don't work. How to check if autostart permission already enabled or not. This code always open autostart permission screen . I want to show this screen only when app is not enabled for autostart.

A: Some apps like Facebook, Gmail, Whatsapp are whitelisted from manufacturers by default, that means auto start permission will automatically be on for these apps.
For now it's not possible to verify that auto start option is enabled or disabled in our app, but u can ask user for enable it manually only one time (assume when user install the application).
You can redirect user to autostart permission's settings page for enabling your app using following code (tested and working for Oppo, Vivo, Xiomi, Letv, Huawei, and Honor):
try {
    Intent intent = new Intent();
    String manufacturer = android.os.Build.MANUFACTURER;
    if ("xiaomi".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
    } else if ("oppo".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
    } else if ("vivo".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
    } else if ("Letv".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
    } else if ("Honor".equalsIgnoreCase(manufacturer)) {
        intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
    }

    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if  (list.size() > 0) {
        startActivity(intent);
    }
} catch (Exception e) {
    Log.e("exc" , String.valueOf(e));
}


text:
Q: MSXML getElementsByTagName() does not work with any TagName i use MSXML getElementsByTagName("TagName") to read out an XML file. It works fine in most caes.
However I can not read some fields.
A sample xml file i use can be found here:
http://pastebin.com/idBTN5Vb
When I read out the nodes "AreaPercent", it works fine.
When I want to read the nodes "Area" (e.g. line 81 in that file) it does not work.
I could imagine this has something to do with the below node:
    66.364914
that is named area as well.
So my question: How to read out the nodes "Area" in this file?.
If any more info is needed, just ask.
Thanks in advance


text:
Q: bash can't find sudo command on friendlyarm I'm trying to work with this friendlyarm 9 board I got recently but it can't find some basic bash commands and I couldn't find a solution for it anywhere.
When I type any command with sudo or even when I type sudo alone I get

/bin/sh: sudo: not found

It is the same when I type bash:

/bin/sh: bash: not found

Should I add something to its PATH? or anything like that?
I asked it here cause I thought it's a linux problem. If it's not can you tell me where to ask about it?
Thank you

A: it seems this version of linux im using doesn't support some bash commands and thus i didn't need them. getting permission denied was a result of the script not having executable permissions. Thanx to blubberdiblub I set the permissions for it to run.


text:
Q: Bind Nameserver Setup I setup bind on my debian box, and have setup my zone files to have my nameserver defined.
When I dig, using for example:
dig @123.456.789.123 ns1.mynameserver.com
where 123.456.789.123 is the defined IP of my nameserver, it resolves 100% fine with no errors. When I go to my sites which are using this nameserver on the internet, the site is not available  - but I presume this is because DNS has not propogated yet.
However, my question is, I did this all on my server only. Is there somewhere I should register my nameserver publically? I.e. why couldn't someone else just setup a nameserver called ns1.mynameserver.com based on their IP address?
How then would a client know which nameserver is the real authority?

A: Basically, the DNS "architecture" over the web is a tree. The root node is called "." (dot) and holds all the information about the Top-Level Domains (.com, .de, .ninja (generic TLD), and so on). These nameservers are officially registered and managed by various companies / countries, thus there can be only one "real" zone for each of these TLDs.
Registrars are other companies that handle the rent of subdomains (google.com, yahoo.de, ...) to customers (individuals and companies alike). That is where you have to go if you want to make sure that your domain is reachable by everyone on the web without any specific action on your side. Since your domain name is officially registered, anyone trying to create a duplicate of your domain would end up with no one being able to query it (well, no DNS server are linked to it or even know about it so basically its like it is non-existent). This architecture would create a new "leaf" to that tree.
"." -> .com -> google.com
    |       -> yahoo.com
    |
    |-> .de -> google.de
            -> yourdomain.de

If your domain name is meant to be used only by you and other people who know its address without the need to query for it other DNS servers, you do not have to officially register it anywhere. In that case, anyone could try to duplicate it but as long as nobody does lookup on it you are fine.
Finally, to answer your question:

*

*if you want it to be publicly reachable you have to pay for your domain and see a registar (GoDaddy, 1&1, ...)

*if its for another more private purpose, you do not need that. In that case you just have to manually edit your clients / servers to resolve your specific domain on your own DNS server (resolv.conf on Debian Linux for example).

Be aware though that if the domain name you want is already taken, you will not be able to register it.

A: There is no need to register your NS for such a setup. Maybe you forgot to add namezones for domains you are checking.


text:
Q: How can I make sure that man has pages installed? Everytime I run man it returns an error as if no man page entries were installed.  Here's an example:
% man man

No manual entry for man

However, I have installed the packages man-db and man-pages, yet it doesn't return a single entry.  I have tried with many commands like man ls, and others.
Also, if i run whatis man, the following is returned:

man: nothing appropriate.

A: Once you install the packages man-db and man-pages you need to run the mandb command to generate the search database for manpage entries.
EDIT (thanks to @fra-san): If you set the MANPATH environment variable, you also need to unset it. If that variable is set, man ignores the paths specified in the config file man_db.conf.


text:
Q: ActionCable. WebSocket is closed before the connection is established
Sometimes connection cannot be established and broke UX, this bug appears not regular and only on production environment
I've tried to increase ActionCable.ConnectionMonitor.staleThreshold, but it leads to bug while users send messages to chat.
Any approaches to handle it?


text:
Q: uksort() function not working I'm trying to sort an array in PHP using a custom function, but it's not working. Here is the (simplified) code I'm using:
        class Test {

            public function sortByVote($a, $b) {
                $v1 = $a['voteCount'];
                $v2 = $b['voteCount'];
                if ($v1 > $v2) return +1;
                if ($v1 < $v2) return -1;
                return 0;
            }

            function test() {
                $temp = array(
                    array("voteCount" => 1),
                    array("voteCount" => 4),
                    array("voteCount" => 9),
                    array("voteCount" => 2),
                    array("voteCount" => 3)
                );

                uksort($temp, array($this, "sortByVote"));
            }

        }

Can anybody see what the issue is?

A: uksort() sorts the keys. In your example, the keys are just automatically generated numeric keys from 0 - 4. I think you mean to sort by values using usort(). Or, if you're looking to maintain index association but still sort by the values, you're looking for uasort(). In short, your sort is borked.

A: You need usort() (user sort by values), not uksort() (user sort by keys)
uksort's callback receives the keys of elements in $temp
usort's callback receives the values of elements in $temp

A: This is how you can use usort to sort this array the way you want it.
class Test {
   private $myArray = [];

  public function __construct()
  {
    $this->myArray = [
         array("voteCount" => 1),
         array("voteCount" => 4),
         array("voteCount" => 9),
         array("voteCount" => 2),
         array("voteCount" => 3)
     ];
   }

  private function sortByVote($a, $b)
  {
    return $a <=> $b;
  }

  public function myArray()
  {
    return $this->myArray;
  }

  public function mySort()
  {
    return usort($this->myArray, 'Test::sortByVote');
  }

}

$t = new Test;
$t->mySort();

$result = $t->myArray();

Result:
Array
(
[0] => Array
    (
        [voteCount] => 1
    )

[1] => Array
    (
        [voteCount] => 2
    )

[2] => Array
    (
        [voteCount] => 3
    )

[3] => Array
    (
        [voteCount] => 4
    )

[4] => Array
    (
        [voteCount] => 9
    )

)


text:
Q: Trying to update data in C# does not work I have a form which updates data. Query is executing but not updating the data. What's wrong? How to fix this?
It was working when I had concatenation but I changed it to parameters and now it's not working
private void button11_Click(object sender, EventArgs e)
{
        try
        {
            if (SId.Text == "" || SellName.Text == "" || SellAge.Text == "" || SellPhone.Text == "" || SellPass.Text == "")
            {
                MessageBox.Show("Missing info");
            }

            string query = "UPDATE Sellers SET [SellerName] = @Name, [SellerAge] = @Age, [SellerPhone] = @Phone, [SellerPassword] = @Pass WHERE [SellerId] = @Id";

            SqlCommand cmd = new SqlCommand(query, Con);

            cmd.Parameters.AddWithValue("@Id", SId.Text);
            cmd.Parameters.AddWithValue("@Name", SellName.Text);
            cmd.Parameters.AddWithValue("@Age", SellAge.Text);
            cmd.Parameters.AddWithValue("@Phone", SellPhone.Text);
            cmd.Parameters.AddWithValue("@Pass", SellPass.Text);

            Con.Open();
            cmd.ExecuteNonQuery();

            MessageBox.Show("Update successful!");

            SId.Text = "";
            SellName.Text = "";
            SellPhone.Text = "";
            SellPass.Text = "";
            SellAge.Text = "";

            Con.Close();

            populate();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}

A: You have to use a connection for the shortest time possible. Instead of conection.Open() use cmd.connection.Open(). I recommend  to use this code:
     var result=0;
      using (var con= new SqlConnection(connectionString))
      {

           var cmd = new SqlCommand(query, con);

            cmd.Parameters.AddWithValue("@Id", SId.Text); //??? if @Id is int or varchar?

            cmd.Parameters.AddWithValue("@Name", SellName.Text);
            cmd.Parameters.AddWithValue("@Age", SellAge.Text);
            cmd.Parameters.AddWithValue("@Phone", SellPhone.Text);
            cmd.Parameters.AddWithValue("@Pass", SellPass.Text);
             cmd.Connection.Open();
            result=cmd.ExecuteNonQuery();
      }
         if(result>0) MessageBox.Show("Update successful!");
         else ....error

            .... your code

I marked with ?? your @Id input parameter. I have some doubts that it is a string type. Check again. If it is int or any another type you will have to convert SId.Text to this type before to create a parameter.The same about @Age.


text:
Q: How to transfer values from controller to view codeigniter into dropdownlist   if (is_array($jsonhome)) {
                foreach ($jsonhome as $query) {
                    foreach ($query['results']['place'] as $places) {

                        if (is_array($places['country'])) {
                            echo "Country:\n";
                            echo "Content: " . $places['country']['content'] . "\n\n";
                        }

                        if (is_array($places['admin1'])) {
                            echo "State:\n";
                            echo "Content: " . $places['admin1']['content'] . "\n\n";
                        }

                        if (is_array($places['admin2'])) {
                            echo "District/City:\n";
                            echo "Content: " . $places['admin2']['content'] . "\n\n";
                        }
                    }
                }
            }

    $location_data['user_current_country'] = $places['country']['content'];

            $this->load->view('header_register', $location_data);
            $this->load->view('body_complete_register', $location_data);
            $this->load->view('footer_register');

I want to transfer the country to input type select in the view codeigniter:
Say i get two countries via the above queries say India and USA i want to pass it to the view
Do i do it via ajax?
Please help i am new to codeigniter

A: So in your controller you want to build an array of options for your <select>.  Something like
//Build array of country options
$aData['countryOptions'] = array();
foreach ($jsonhome as $query) {
    foreach ($query['results']['place'] as $places) {
        $aData['countryOptions'][] = $places['country']['content'];
    }
}

$this->load->view('body_complete_register', $aData);

Then in your view you can use the form_dropdown function providing you have the form helper loaded
$this->load->helper('form');
echo form_dropdown('countries', $countryOptions);

Of if you don't want to use the helper you could do
<select name="countries" id="countries">
    <?php foreach($countryOptions as $key => $countryName) { ?>
        <option value="<?php echo $key ?>"><?php echo $countryName ?></option>
    <?php } ?>
</select>

Please note that you shouldn't be echoing anything out in the controller.  The controller is just for passing data between models, libraries and views


text:
Q: ListView disappears upon screen rotation I have a problem with screen rotation.
I have a ListView with data.
Everytime I rotate the screen, the ListView disappears.
I tried this in the Class which contains the ListView.
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    loadActivity();
}

I have also put this in the manifest
android:configChanges="keyboardHidden|orientation"

Still nothing.
Any help would be appreciated and earn a big green tick
private void loadActivity() {
    // Do all of your work here
    list = (ListView) findViewById(R.id.listView);
    personList = new ArrayList<HashMap<String, String>>();
    getData();//get business email
    final Intent intent = getIntent();
    email = intent.getStringExtra("email");
    txt.setText(email);

}

A: Jitty's answer on this thread worked for me:
Add android:configChanges="orientation|keyboardHidden|screenSize|keyboard" to your activity tag in AndroidManafest.xml


text:
Q: How do I convert an image into unicode? I have created a Baluchi keyboard via ARABIC keyboard. But there are few keys not available in Arabic too. I tried different combinations of keys to fulfill my requirement but now the issue is that for a specific key there is no Unicode combination available in the UNICODE chart.
Please help me out to covert this image in proper UNICODE text so that I can update my Baluchi keyboard.

A: Unicode is a standard, and as such you cannot add characters to it yourself. There are two things that you can do, however:

*

*You can create a font that has the character you need. In a unicode font, you could put such a character in the private use area, a number of slots in a unicode font that do not have a set symbol. You need to be aware, however, that this is more complicated than just converting an image, particularly if the alphabet you are using is Arabic-based.

*You can petition the unicode technical committee into adding the character to the standard. This is not a terribly quick process, but it has been done for several languages in the area, such as Khowar and Torwali. Even if the character is accepted, this does not mean that there will automatically be fonts that have it. Someone would still have to build the characters into a font.
Just out of curiosity (though perhaps I can help), what characters are you missing?


text:
Q: I'm confused with this sentence. There are multiple verbs, and one is plural. Does this make the subject-verb agreement incorrect? Sentence -"Our pet alligator has been stalking neighborhood pets because my brother Billy forgets to feed the poor reptile."
My questions is two fold.
If the answer to my question is wrong, and the subject-verb agreement is correct, then can there be multiple subject-verb agreements in the same sentence?

A: First, there are two clauses in the sentence. Each clause has a subject and a verb: alligator -- has been stalking and Billy -- forgets.
Second, which verb do you believe is in plural form?


text:
Q: How to run function when error raised in python I have a function called onError(). When it is ran, it prints "There was an error"
I want this function to run whenever an error occurs, for example, if I raise NameError, the function runs.
Here is my code
def onError():
    print("There was an error")

raise NameError

I know that try and except exist, but I want a way to do it without them.

A: You can define a "global" exception handler by overriding sys.excepthook.
Here's an example.
import sys

def onError(exception_type, value, traceback):
    print("There was an error")

sys.excepthook = onError


text:
Q: Getting error when load the bing map version 8 when i run my code it show a script error dialog
"Error -Script error ,URL - http://www.bing.com/api/maps/mapcontrol?callback=OnLoad"

OnLoad is function which i call to initialize the map
Url i used to get map in my html file  -
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?callback=OnLoad' async defer></script>

A: Two things to try. First make sure your network can reach the http://bing.com website. Second, make sure you have a function call OnLoad that is accessible to the map control to call. Verify spelling and that it al control doesn't try and call this function before it is available. Try adding async defer to your script tag and this will allow your other code to load a bit faster.


text:
Q: Dynamics CRM: Bring Activity Type between organizations to Sync I have an activity(Activity_ABC) which has different Activity Type code value across QA(1001) and Production(1002) organizations.This leading to Views which use Activity Type in the Filter criteria to break every time deployment is done from QA to Prod,
needing a manual update.
I found one supported way would be to restore one organization, but looking forward for any customization method for it.
What would be the impact if I update the Activity Type Global System option set xml say on QA to make it 1002 for Activity_ABC.

A: Having out of sync customizations, that too Entity (custom activity) created separately in different order on each instance (of dev/uat/prod regions) is going to be hell.
Try to restore/refresh the Prod instance to lower regions to have all in sync - BEST option.
Editing customizations directly in xml file - unsupported - unrecommended option. Which you may get succeed, but start to play around after taking backups.
Verify if that code is assigned to any other entity/activity before doing so.


text:
Q: searching by special character on linq I need a searching process on linq like this. For example, I will make searching on Name column,and user enters "Ca?an" word to textbox. Question mark will e used for sprecial search character for this sitution.
It will search by Name column and, find Canan,Calan,Cazan etc.
I hope I can explain my problem correctly.
Can anyone give me an idea about this linq query. Thank in advance...

A: You can use this regular expression (if you are using C#) to check for the "Ca?an".
string d = "DDDDDDDDDDCasanDDDDDDDDDD";
Regex r = new Regex(@"Ca([a-zA-Z]{1})an");
string t = r.Match(d).Value;

Output will be:
"Casan"
You have all your colum stored in a database, then do something like:
List<Person> list = new List<Person>(); //Filled
var res = list.Select(x => r.Match(x.Name));

Output will be a IEnumerable with all the "Persons" who contains in the Name "Ca?an", being ? no matter which letter

A: You need to convert your search-syntax into an existing search-engine - I'd suggest Regex. So the steps will be:

*

*Safely convert the entered search-string into Regex-pattern

*Perform the search in Linq on name-property

Solution:
1: Safely convert search string by replacing '?' with Regex-version of wildchar:
var userInput = "Ca?an";
var regexPattern = Regex.Escape(userInput).Replace(@"\?", ".");

2: Perform search in Linq (assuming itemList implements IEnumerable):
var results = itemList.Where(item => Regex.IsMatch(item.Name, regexPattern));

Hope this helps!


text:
Q: Ext & Complexes I have heard that given two sheaves $A$ and $B$ on a variety, one can identify elements of $Ext^d(A,B)$ with complexes of sheaves
$$0\to B \to C_1 \to \cdots \to C_d \to A \to 0.$$
My questions are,

How do I see that this is true?

and

If I have obtained an element of $Ext^n$ by some other method, can I explicitly construct the $C_j$ sheaves and the differentials?

I am sure this is well-known, so I'm marking it also as "reference-request".

A: For modules, Weibel discusses this in "Introduction to homological algebra." Section 3.4 deals with d=1 case and in Vista 3.4.6 is about the general case. He gives no proof for d>1 and refers to Bourbaki "Algebre homologique" 7.5 and Maclane "Homology" pp82-87.

A: Extremely late answer, but Eisenbud discusses this in his appendix on homological algebra in "Commutative algebra with a view towards algebraic geometry".
This is the Yoneda interpretation of Ext, and gives rise to a multiplicative structure on Ext-modules.


text:
Q: How to access values and fields from a Document List with Java MongoDB driver? I'm using the MongoDB Java drivers and I've been digging around for almost an hour now regarding how to handle Document Lists and get values from them but I haven't found anything that works for me.
Below is my relevant code section and the condensed down console output of the different Document Lists I have. If someone could explain how to basically make an array of my "scoregot" values it would be much appreciated because I can't make sense of anything out there.
    List<Document> englishOut = (List<Document>) englishCollection.find()
            .projection(Projections.include("scoreout")).into(
                    new ArrayList<Document>());

    List<Document> englishGot = (List<Document>) englishCollection.find()
            .projection(Projections.include("scoregot")).into(
                    new ArrayList<Document>());

    List<Document> assignType = (List<Document>) englishCollection.find()
            .projection(Projections.include("scoretype")).into(
                    new ArrayList<Document>());

[Document{{_id=5b3ec0d3beceb309d804ce7e, scoretype=quiz}},
Document{{_id=5b3ec18cbeceb309d804ce7f, scoretype=hw}},
[Document{{_id=5b3ec0d3beceb309d804ce7e, scoreout=25.0}}, Document{{_id=5b3ec18cbeceb309d804ce7f, scoreout=5.0}},
[Document{{_id=5b3ec0d3beceb309d804ce7e, scoregot=23.0}}, Document{{_id=5b3ec18cbeceb309d804ce7f, scoregot=5.0}},


text:
Q: data structure list class in python I am working on a data structure list class in python. I would like to get the largest item in the list.
    inlist = self.data
    if inlist[0] > inlist[1]:
        largest = inlist[0]
    else:
        largest = inlist[1]

    for item in inlist[2]:
        if item > largest:
            largest = item
    return largest

With the above getting stuck at largest gets returns
<bound method ListData.largest2 of <list.ListData instance at 0x2b35602c3440>>

while the data
[2, 5]

A: Trust the loop to get all the indicies rather than specifying them yourself.
if len(self.data) == 0:
  return None
result = self.data[0]
for item in self.data:
  if item > result:
    result = item
return result

that for loop is going through all your data.  Trying to coerce an index got you into trouble.

A: You can use the build in max() function.
mylist = [2, 5]
mymax = max(mylist)


text:
Q: Map column using two dictionaries I have a df:
ColA  ColB
1     1
2     3
2     2
1     2
1     3
2     1

I would like to use two different dictionaries to change the values in ColB. I would like to use d1 if the value in ColA is 1 and d2 if the value in ColB is 2.
d1 = {1:'a',2:'b',3:'c'}
d2 = {1:'d',2:'e',3:'f'}

Resulting in:
ColA  ColB
1     a
2     f
2     e
1     b
1     c
2     d

How would be the best way of achieving this?

A: You can use a new dictionary in which the keys are tuples and map it against the zipped columns.
d = {**{(1, k): v for k, v in d1.items()}, **{(2, k): v for k, v in d2.items()}}
df.assign(ColB=[*map(d.get, zip(df.ColA, df.ColB))])

   ColA ColB
0     1    a
1     2    f
2     2    e
3     1    b
4     1    c
5     2    d

Or we can get cute with a lambda to map.
NOTE: I aligned the dictionaries to switch between based on their relative position in the list [0, d1, d2].  In this case it doesn't matter what is in the first position.  I put 0 arbitrarily.
df.assign(ColB=[*map(lambda x, y: [0, d1, d2][x][y], df.ColA, df.ColB)])

   ColA ColB
0     1    a
1     2    f
2     2    e
3     1    b
4     1    c
5     2    d

For robustness I'd stay away from cute and map a lambda that had some default value capability
df.assign(ColB=[*map(lambda x, y: {1: d1, 2: d2}.get(x, {}).get(y), df.ColA, df.ColB)])

   ColA ColB
0     1    a
1     2    f
2     2    e
3     1    b
4     1    c
5     2    d

A: If it needs to be done for many groups use a dict of dicts to map each group separately. Ideally you can find some functional way to create d:
d = {1: d1, 2: d2}
df['ColB'] = pd.concat([gp.ColB.map(d[idx]) for idx, gp in df.groupby('ColA')])

Output:
   ColA ColB
0     1    a
1     2    f
2     2    e
3     1    b
4     1    c
5     2    d

A: One way is using np.where to map the values in ColB using one dictionary or the other depending on the values of ColA:
import numpy as np
df['ColB'] = np.where(df.ColA.eq(1), df.ColB.map(d1), df.ColB.map(d2))

Which gives:
    ColA ColB
0     1    a
1     2    f
2     2    e
3     1    b
4     1    c
5     2    d

For a more general solution, you could use np.select, which works for multiple conditions. Let's add another value in ColA and a dictionary, to see how this could be done with three different mappings:
print(df)
    ColA ColB
0     1     1
1     2     3
2     2     2
3     1     2
4     3     3
5     3     1

values_to_map = [1,2,3]
d1 = {1:'a',2:'b',3:'c'}
d2 = {1:'d',2:'e',3:'f'}
d3 = {1:'g',2:'h',3:'i'}

#create a list of boolean Series as conditions
conds = [df.ColA.eq(i) for i in values_to_map]
# List of Series to choose from depending on conds
choices = [df.ColB.map(d) for d in [d1,d2,d3]]
# use np.select to select form the choice list based on conds
df['ColB'] = np.select(conds, choices)

Resulting in:
    ColA ColB
0     1    a
1     2    f
2     2    e
3     1    b
4     3    i
5     3    g

A: I am using concat with reindex
idx=pd.MultiIndex.from_arrays([df.ColA, df.ColB])
df.ColB=pd.concat([pd.Series(x) for x in [d1,d2]],keys=[1,2]).reindex(idx).values
df
Out[683]:
   ColA ColB
0     1    a
1     2    f
2     2    e
3     1    b
4     1    c
5     2    d

A: You can create a function that does this for one element and then use an apply lambda to your dataframe.
def your_func(row):
    if row["ColA"] == 1:
        return d1[row["ColB"]]
    elif row["ColB"] == 2:
        return d2[row["ColB"]]
    else:
        return None

df["ColB"] = df.apply(lambda row: your_func(row), axis=1)

A: You can use two replace as such:
df.loc[df['ColA'] == 1,'ColB'] = df['ColB'].replace(d1, regex=True)
df.loc[df['ColA'] == 2,'ColB'] = df['ColB'].replace(d2, regex=True)

I hope it helps,
BR


text:
Q: TypeError: Cannot read property 'PlatformLocalStorage' of undefined I am running jest test on react-native  and getting this following errors
Test suite failed to run
TypeError: Cannot read property 'PlatformLocalStorage' of undefined

  2 | import thunk from 'redux-thunk';
  3 | import { persistStore, persistReducer } from 'redux-persist';
> 4 | import AsyncStorage from '@react-native-community/async-storage';
    | ^
  5 |

"dependencies":{
    "react": "16.8.3",
    "react-native": "0.59.9",
},
"devDependencies": {
  "jest": "^24.1.0",
  "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.10.0",
},

  "jest": {
    "setupFilesAfterEnv": [
      "<rootDir>/__tests__/setup/test-setup.js"
    ],
    "setupFiles": [
      "<rootDir>/__tests__/setup/test-setup.js"
    ],
    "transformIgnorePatterns": [
      "/node_modules(?![\\/]rn-fetch-blob[\\/]|[\\/]react-native[\\/]|[\\/]react-native-config[\\/]|[\\/]react-native-navigation[\\/]|[\\/]react-native-status-bar-height[\\/]|[\\/]react-native-animatable[\\/]|[\\/]react-native-restart[\\/]|[\\/]react-native-linear-gradient[\\/]|[\\/]react-native-i18n[\\/]|[\\/]react-native-modal[\\/]|[\\/]react-native-smooth-pincode-input[\\/]|[\\/]react-native-swipe-gestures[\\/]|[\\/]react-native-root-toast[\\/]|[\\/]react-native-root-siblings[\\/]|[\\/]static-container[\\/]|[\\/]react-native-elements[\\/]|[\\/]react-native-ratings[\\/]|[\\/]react-native-progress[\\/]|[\\/]react-native-dialog[\\/]|[\\/]react-native-pdf[\\/]|[\\/]react-native-webview[\\/]|[\\/]react-native-check-box[\\/]|[\\/]react-native-share[\\/]|[\\/]react-native-haptic-feedback[\\/]|[\\/]react-native-responsive-screen[\\/]|[\\/]react-native-keyboard-aware-scroll-view[\\/]|[\\/]he[\\/]|[\\/]react-native-iphone-x-helper[\\/]|[\\/]check-prop-types[\\/]|[\\/]react-native-image-progress[\\/]|[\\/]react-native-theming[\\/]|[\\/]@react-native-community/async-storage[\\/])/"
    ],
    "testPathIgnorePatterns": [
      "<rootDir>/(build|docs|node_modules)/",
      "<rootDir>/__tests__/setup"
    ],
    "preset": "react-native"
  },
  "rnpm": {
    "assets": [
      "fonts"
    ]
  }
}

Can some one please help me why this errors are coming when I run jest test in react-native app. i have updated several dev dependencies but no luck.

A: Mock the AsyncStorage library. If, like me, you've ported from the react-native variant to the react-native-community one you may need to update your mocks (if you had them already).
jest.mock("@react-native-community/async-storage", () => {
   // a map/dict/kvs of types to return - the leaves of the def
   // are jest functions
   const apiMock = {
    getItem: jest.fn(() => {  // mock's AsyncStorage.getItem()
      return JSON.stringify("some mock data");
    }),
   };
   return apiMock;
 });

A: The solution is to mock the Package.

*

*In your project root directory, create
__mocks__/@react-native-async-storage directory.

*Inside that folder, create async-storage.js file.

*Inside that file, export Async Storage mock.

export default from '@react-native-async-storage/async-storage/jest/async-storage-mock'

The full instruction is here https://react-native-async-storage.github.io/async-storage/docs/advanced/jest


text:
Q: OnNavigatedTo is not called when using NavigationService.SelectTabAsync According to the documentation of Prism "when selecting a tab programmatically both the INavigationAware and IConfirmNavigation interfaces are invoked". But unfortunately this is not the case for me.
I did the following with Prism.DryIoc.Forms v7.2.0.1422 (also latest version did not work) and Xamarin.Forms v4.8.0.1560:
My MainPage:
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage
    x:Class="SampleApp.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:prim="http://prismlibrary.com"
    xmlns:views="clr-namespace:SampleApp.Views;assembly=SampleApp"
    Title="{Binding Title}">

    <NavigationPage Title="Page A">
        <x:Arguments>
            <views:APage Title="Page A" />
        </x:Arguments>
        <NavigationPage.Behaviors>
            <prim:NavigationPageActiveAwareBehavior />
        </NavigationPage.Behaviors>
    </NavigationPage>
    <NavigationPage Title="Page B">
        <x:Arguments>
            <views:BPage Title="Page B" />
        </x:Arguments>
        <NavigationPage.Behaviors>
            <prim:NavigationPageActiveAwareBehavior />
        </NavigationPage.Behaviors>
    </NavigationPage>
    <NavigationPage Title="Page C">
        <x:Arguments>
            <views:CPage Title="Page C" />
        </x:Arguments>
        <NavigationPage.Behaviors>
            <prim:NavigationPageActiveAwareBehavior />
        </NavigationPage.Behaviors>
    </NavigationPage>
</TabbedPage>

In BPageViewModel selecting tab "APage" with NavigationParameters:
private async Task SayHelloOnPage()
{
   var navParam = new NavigationParameters
   {
      { "SayHelloTo", "Prism" }
   };
   await NavigationService.SelectTabAsync(nameof(APage), navParam);
}

In APageViewModel override OnNavigatedTo method:
public override void OnNavigatedTo(INavigationParameters parameters)
{
   base.OnNavigatedTo(parameters);

   System.Diagnostics.Debug.WriteLine($"OnNavigatedTo is called", nameof(APageViewModel));

   if (parameters.ContainsKey("SayHelloTo"))
   {
       var name = parameters["SayHelloTo"] as string;
       if (name != null)
       {
         System.Diagnostics.Debug.WriteLine($"Say Hello to {name}", nameof(APageViewModel));
       }
   }
}

See also this example project on my DropBox
Is this a bug or do I miss something?

A: I believe this is a bug, or at least an oversight in the API. It does call OnNavigatedTo, but only on the Page that is directly part of the TabbedPage. If you have your target page inside a NavigationPage, only the NavigationPage will get the OnNavigatedTo call. See https://github.com/PrismLibrary/Prism/blob/master/src/Forms/Prism.Forms/Navigation/TabbedPages/INavigationServiceExtensions.cs#L73-L74 .
I worked around this by copying the above implementation to my project and then changing the behaviour to instead call OnNavigatedTo on the relevant child page of the NavigationPage.


text:
Q: ng-select don't set value on reactive forms I have a ng-select and angular reactive forms. I configured it:
this.form1 = this.fb.group({
  test: [null, null]
});

this.items = [
    {
     code: 'A',
     description: 'TEST A'
    },
    {
     code: 'B',
     description: 'TEST B'
    }

 ]

   <ng-select [items]="items"
       (change)="onSelected($event)"
       bindLabel="description"
       class="selectbox">
    </ng-select>

onSelected(event){
   this.form1.controls['test'].setValue(event);

   // this.form1.controls['test'].value =  {code: 'A',description: 'TEST A'}
}

Now the ng-select works. But if I set value on init i try to make
  this.form1.patchValue({
     test: {code: A}
  })

but don't worlks. I would like to set ui-select on init with this.form1.patchValue({
         test: {code: A}
      })
any ideas? Thank's
Marco

A: bind formControlname to ng-select, and then on init set
this.form1.patchValue({
     test: {code: A}
  }) or if your ng-select is set to [multiple]="true" then
this.form1.patchValue({
     test: [{code: A}]
  })


text:
Q: Vary height of hero image with browser window size I am trying to achieve an effect which can be seen on the https://lexus.com.au website where

*

*no matter what the browser screen height (desktop or laptop etc) the hero image and the cta bar always fill the browser screen.

*The height of the hero image varies as the browser height changes.

*The image also centres on the main content as the screen changes.

*The CTA bar at the bottom of the screen always remains the same height and location.

Is this done with JS using window.InnerHeight or some other method?

A: TL:DR:
Is this done with JS using window.InnerHeight or some other method? No
There are 2 reasons that contribute to this and while there are likely more, these are the ones I can see without rebuilding what was done just to give you the answer.

*

*They use the  background-position: % % to position the image.  The first value is the horizontal position and the second value is the vertical. The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50%. Default value is: 0% 0%  https://www.w3schools.com/cssref/pr_background-position.asp
This is what gives the image that look of squeezing under the top banner.

*Then these were done to position the element itself within the above div.  background-size: cover; display: table;  https://mattboldt.com/kicking-ass-with-display-table/
It's important to understand that throughout this the reason for it taking up the full width is simple; width was set to 100%. That is actually the easiest part of the whole effort. However combining the above elements to get the correct effect will take some playing with on a codepen. That being said what I've given you is what you need to know to succeed.
Links below are good links to get you started on fully understanding how to complete this task.


text:
Q: Curve Trajectory object orientation I have a spaceship in a 3D environnement. I drew a B-Spline curve using control points (converted to a Bezier curve to be able to draw it). Each time the draw event is called, the ship is at the point (0,0,0) and is translated to the next coordinate on the curve. Now, before doing this translation, I would need to make a rotation so that the ship's orientation is along the curve's tangent at that point.
I'm able to approximate the tangent by finding a point on the curve that is near the current one by doing this. I use OpenGL in C++
float mDifference[1][3] = {nearPoint[0][0] - currentPosition[0][0],
                           nearPoint[0][1] - currentPosition[0][1],
                           nearPoint[0][2] - currentPosition[0][2]};

float norm = sqrt(mDifference[0][0] * mDifference[0][0]
             + mDifference[0][1] * mDifference[0][1]
             + mDifference[0][2] * mDifference[0][2]);

float tangent[1][3] = { mDifference[0][0] / norm,
                        mDifference[0][1] / norm,
                        mDifference[0][2] / norm};

//tangent = rotationVector?
spacecraftTransformGroup->setRotationVector(tangent[0][0],tangent[0][1],tangent[0][2]);

I think the rotation vector is the tangent, but can't find the angle needed to rotate the ship. How can I rotate the ship to align it with the tangent?

A: Well an orthonormal (ie orientation) matrix is made up of the following:
Direction,
Tangent,
BiTangent (Up vector).
So if you have your direction and tangent you can cross product to get your bitangent and form your matrix from the 3 direction vectors (D, T, B) and position vector (P) as follows
 Tx, Bx, Dx, Px
 Ty, By, Dy, Py
 Tz, Bz, Dz, Pz
  0,  0,  0,  1

Your object is now oriented along the direction vector ...

A: First off, see this site for information on finding the actual tangent at a given point along the B-Spline curve.
Second, you can use atan(y/x) to obtain the angle (in radians) of the tangent vector.  Use that angle to rotate your ship, assuming the 'zero' angle has your ship pointing along the x-axis.


text:
Q: How ParseExact know my local TimeZone? I use this code to convert my UTC string Time with format "yyyy-MM-ddTHH:mm:ssZ" to date time . for example :
string PurchaseDate == "2017-12-12T14:29:26Z";
datetime dt =  DateTime.ParseExact(PurchaseDate , "yyyy-MM-ddTHH:mm:ssZ", null);

i know that PurchaseDate time is UTC time (because of "Z"). dt return {12/12/2017 5:59:26 PM} that it is my local Time(client time zone). in other word DateTime.ParseExact convert PurchaseDate to my client time zone! my question is how this method know my client TimeZone ? is it recommend to use this for global application and show user time zone at all ??

Update My question:
sometime for implement timezone management in my global website i google it for possible souloution and I find this Use ful link :
How to display dates and times in clients timezone
after month i found we can use TimeZoneInfo.Local for finding cliend TimeZone !
so should i say that link is useless? I want to know if there is a simple way to find client time zone in dotNet BackEnd code so why this complex way is Used ??

A:
... how this method know my client TimeZone?

It doesn't understand anything about a "client".  It just has the local time of wherever the code is running. If the code is running on a user's desktop computer or mobile device, then it's the time zone of that device.
If the code is running on a server, then it uses the time zone of the server.  You should avoid this in general, as the server's time zone is usually irrelevant to your application or users.  This applies to TimeZoneInfo.Local as well.
If you want to parse your string as UTC DateTime, then you'll need to pass an argument that tells the parser not to convert to local time:
string PurchaseDate = "2017-12-12T14:29:26Z";
DateTime dt = DateTime.ParseExact(PurchaseDate, "yyyy-MM-ddTHH:mm:ssK",
                               CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("...you'll need to decide...");
DateTime clientDateTime = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);

In the above, I use DateTimeStyles.RoundtripKind, which says to evaluate the string for it's offset (Z in this case) and decide whether to use Utc, Local, or Unspecified kind on the resulting DateTime.  Also note that you should use K in the format string, not Z.
A better approach would be to use DateTimeOffset instead of DateTime, in which case the Z will automatically set an offset of +00:00.
You'll still need to figure out what time zone to convert to, regardless of which approach you take.  If you happen to be writing code that runs on the user's device, then you get the benefit of having TimeZoneInfo.Local predetermined for you.  Otherwise you do not.


text:
Q: Bring UIimageView to front I have a ViewController in which there is a UIScrollView. On that i have a UIView and the UIView I have to add Label and Image. The image should be above my label  .
The Order is as Controller>>ScrollView>>UIView >> UILAbel >> UIImageView
but i am not able to add UIimageView to the view .
This is my code
 scrollView =[[UIScrollView alloc]init];
[scrollView setFrame:CGRectMake(0, 0, 320, 480)];
 [scrollView setContentSize:CGSizeMake(320,2820)];
[scrollView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
[scrollView setScrollEnabled:YES];
[scrollView setShowsHorizontalScrollIndicator:YES];
[scrollView setShowsVerticalScrollIndicator:NO];
[self.view addSubview:scrollView];

    UIView *firstView = [[UIView alloc]initWithFrame:CGRectMake(5, 5, 310, 300)];
firstView.backgroundColor = [UIColor whiteColor];
[scrollView addSubview:firstView];

UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(65, 3, 180, 50)];
label.text = @"ABC";
label.textAlignment =NSTextAlignmentCenter;
label.textColor = [UIColor colorWithRed:74.0/255.0 green:144.0/255.0 blue:226.0/255.0 alpha:1];
label.font=[UIFont fontWithName:@"Helvetica-Bold" size:18];
[firstView addSubview:label];

 imgView = [[UIImageView alloc]initWithFrame:CGRectMake(115, 0, 90, 90)];
imgView.image = [UIImage imageNamed:@"thumbs4.png"];
[self.view bringSubviewToFront:imgView];

[self.view bringSubviewToFront:imgView] This line does nothing

A: You should add image view to self.view before manipulate it. But it is not necessary to bring it to front if it will be the last added subview.
imgView = [[UIImageView alloc]initWithFrame:CGRectMake(115, 0, 90, 90)];
imgView.image = [UIImage imageNamed:@"thumbs4.png"];
[self.view addSubview:imgView] // added as subview
[self.view bringSubviewToFront:imgView]; // not really needed. imgView is actually in front

A: UIScrollView *scrollView =[[UIScrollView alloc]init];
[scrollView setFrame:CGRectMake(0, 0, 320, 480)];
[scrollView setContentSize:CGSizeMake(320,2820)];
[scrollView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
[scrollView setScrollEnabled:YES];
[scrollView setShowsHorizontalScrollIndicator:YES];
[scrollView setShowsVerticalScrollIndicator:NO];
[self.view addSubview:scrollView];

UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(115, 0, 90, 90)];
imgView.image = [UIImage imageNamed:@"dream.jpg"];
[self.view addSubview:imgView];

UIView *firstView = [[UIView alloc]initWithFrame:CGRectMake(5, 5, 310, 300)];
firstView.backgroundColor = [UIColor blueColor];
[scrollView addSubview:firstView];

UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(65, 3, 180, 50)];
label.text = @"ABC";
label.textAlignment =NSTextAlignmentCenter;
label.textColor = [UIColor colorWithRed:74.0/255.0 green:144.0/255.0 blue:226.0/255.0 alpha:1];
label.font=[UIFont fontWithName:@"Helvetica-Bold" size:18];
[firstView addSubview:label];

I got Output like


text:
Q: How can I get the average of two numbers represented as bytes? I'm dealing with numbers, each one represented by two bytes (a short value, in the programming sense).
I want to compute the average of these two numbers, and get once again two bytes back.
Can I just do the following?
result_byte_A = first_num_byte_A + second_num_byte_A / 2
result_byte_B = first_num_byte_B + second_num_byte_B / 2

Will this yield a correct result? Or is this more complex than that?

A: Apart from the fact that you accidentally multiply instead of adding, there are overflow and rounding problems. Your method suffers from these in more cases than necessary. Try
short result = ((int) A + (int)B)/2;

instead. (This suffers only from rounding problems, e.g., the average of $4$ and $7$ is returned as $5$ instead of $5.5$, which cannot be expressed as short.
Your method (with + in place of *) goes awfully wrong, e.g. for $A=256$, $B=0$.


text:
Q: I want to read call logs in the android
Possible Duplicate:
How can I retrieve recently used contacts in android?

I want to read recently used contacts.
Anyone know how to do this?

A: 1. Create observer:
class CustomContentObserver extends ContentObserver {

        public CustomContentObserver(Handler handler) {
            super(handler);

        }

        @Override public boolean deliverSelfNotifications() {
            return false;
        }

        public void logCallLog() {
            long dialed;
            String columns[]=new String[] {
                    CallLog.Calls._ID,
                    CallLog.Calls.NUMBER,
                    CallLog.Calls.DATE,
                    CallLog.Calls.DURATION,
                    CallLog.Calls.TYPE};
            Cursor c;
            c = getContentResolver().query(Uri.parse("content://call_log/calls"),
                    columns, null, null, "Calls._ID DESC"); //last record first
            while (c.moveToNext()) {
                dialed=c.getLong(c.getColumnIndex(CallLog.Calls.DATE));
                Log.i("CallLog","type: " + c.getString(4) + "Call to number: "+number+", registered at: "+new Date(dialed).toString());
            }
        }

        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            Log.d("PhoneService", "StringsContentObserver.onChange( " + selfChange + ")");
            logCallLog();
        }

}

2. Register observer:
 Uri mediaUri = android.provider.CallLog.Calls.CONTENT_URI;
        Log.d("PhoneService", "The Encoded path of the media Uri is "
                + mediaUri.getEncodedPath());
        CustomContentObserver custObser = new CustomContentObserver(handler);
        imageContentRsr.registerContentObserver(mediaUri, false, custObser);

EDIT:
As of Jellybean (4.1), you now need the permission:
    <uses-permission android:name="android.permission.READ_CALL_LOG" />

For this to work and not throw a Permission Denial exception


text:
Q: Kotlin Querydsl: cannot find javax.annotation.proceesing.Generated I am following this example https://felixzett.com/articles/minimal-maven-kotlin-querydsl-example/ to implement querydsl in a Springboot Kotlin Maven project. Using the pom mentioned, I managed to generate the q classes after running mvn compile and can run mvn clean install successfully as well, but when I try to run the project locally, I get error in all the q classes.
java: cannot find symbol
  symbol:   class Generated
  location: package javax.annotation.processing

I tried adding javax.annotation-api to the <annotationProcessPaths> element but it didn't work.
<annotationProcessorPath>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</annotationProcessorPath>

I also tried adding it as a dependency, within that <plugin> element or in the main <dependencies> element, but these didn't work as well.
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

May I know if anyone has any idea how to solve this?
Update:
I have both kotlin-maven-plugin and maven-compiler-plugin in my pom. I realise if I comment out the maven-compiler-plugin then the error is gone. But I am not sure if other parts of the app will be affected if it doesn't have this plugin.
Does anyone know if it is ok to just have the kotlin-maven-plugin, or how I should modify maven-compiler-plugin for the 2 plugins to work together?
<plugin>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-maven-plugin</artifactId>
    <version>${kotlin.version}</version>
    <executions>
        <execution>
            <id>compile</id>
            <phase>process-sources</phase>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
        <execution>
            <id>kapt</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>kapt</goal>
            </goals>
            <configuration>
                <sourceDirs>
                    <sourceDir>src/main/kotlin</sourceDir>
                </sourceDirs>
                <annotationProcessorPaths>
                    <annotationProcessorPath>
                        <groupId>com.querydsl</groupId>
                        <artifactId>querydsl-apt</artifactId>
                        <version>${querydsl.version}</version>
                        <classifier>jpa</classifier>
                    </annotationProcessorPath>
                </annotationProcessorPaths>
            </configuration>
        </execution>
        <execution>
            <id>test-compile</id>
            <phase>test-compile</phase>
            <goals>
                <goal>test-compile</goal>
            </goals>
            <configuration>
                <sourceDirs>
                    <sourceDir>src/test/kotlin</sourceDir>
                    <sourceDir>target/generated-sources/kapt/test</sourceDir>
                </sourceDirs>
            </configuration>
        </execution>
    </executions>

    <configuration>
        <args>
            <arg>-Xjsr305=strict</arg>
        </args>
        <compilerPlugins>
            <plugin>spring</plugin>
            <plugin>jpa</plugin>
            <plugin>all-open</plugin>
        </compilerPlugins>
        <pluginOptions>
            <option>all-open:annotation=javax.persistence.Entity</option>
            <option>all-open:annotation=javax.persistence.MappedSuperclass</option>
            <option>all-open:annotation=javax.persistence.Embeddable</option>
        </pluginOptions>
        <jvmTarget>1.8</jvmTarget>
    </configuration>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-allopen</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-noarg</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
    </dependencies>
</plugin>

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <groupId>org.apache.maven.plugins</groupId>
    <version>3.5.1</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
    <executions>
        <execution>
            <id>default-compile</id>
            <phase>none</phase>
        </execution>
        <execution>
            <id>default-testCompile</id>
            <phase>none</phase>
        </execution>
        <execution>
            <id>java-compile</id>
            <phase>process-sources</phase>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
        <execution>
            <id>java-test-compile</id>
            <phase>test-compile</phase>
            <goals>
                <goal>testCompile</goal>
            </goals>
        </execution>
    </executions>
</plugin>

A: It seems like it is due to the Java version in the maven-compiler-plugin. After I changed it from 1.8 to 11, I do not get the error even if I have both kotlin-maven-plugin and maven-compiler-plugin.
<configuration>
    <source>1.8</source>
    <target>1.8</target>
</configuration>

Also change the java version to 11 in the <properties> element.
<properties>
    <java.version>11</java.version>
</properties>


text:
Q: Align text to the right of an image using CSS? I'm attempting to align text to the right of an image;
css
.p1 {
position: absolute;
    width: 100px;
    height: 50px;
    top: 40%;
    left: 70%;;
}

html

This is a testtttttttttttttttttttttttttttttt

The code works for a short amount of text, but for a large amount of text it gets squished and forms a really long paragraph. Here is what I mean;
[image] [tes
         ttt
         ttt
         tt]

I want the text to appear as a normal paragraph block.
[image] [testttt
         ttttttt]

A: Hi @Eggy Please find fiddle
.container{
    width:100%;
    overflow:hidden;
}
.container img{
    display:inline-block;
    margin-right:20px;
    float:left;
}

A: A simple way is to remove the absolute positioning and give the img and text inline-block displays. You may also want to remove your width of the paragraph or increase it: JS Fiddle
CSS
img {
    display: inline-block;
}
.p1 {
    display: inline-block;
    height: 50px;
    width: 300px;
    top: 40%;
    left: 70%;
}


text:
Q: pagecontainerbeforeshow - jQuery Mobile 1.4 In jQuery Mobile 1.4.x, the way page events are handled were changed. As opposed to binding the data-role="page" div to specific page events like pagebeforeshow, etc. - we now bind to a delegate handler. E.g.
Old:
$('#pgOne').on('pagecontainerbeforeshow', function (e) {
    alert('I am now on page one!');
});

$('#pgTwo').on('pagecontainerbeforeshow', function (e) {
    alert('I am now on page two!');
});

New:
$(':mobile-pagecontainer').on('pagecontainerbeforeshow', function (e) {
    alert('...');
});

The new way is awful, since I have no way of defining the event for each page - e.g. I can no longer define the events for #pgOne vs. #pgTwo.
How do I achieve the behaviour in the old example, using the new methodology?

A: Have a look at the API Docs:  http://api.jquerymobile.com/pagecontainer/#event-beforeshow
You can use ui.toPage to get the page being shown:
$( ".selector" ).on( "pagecontainerbeforeshow", function( event, ui ) {
    alert(ui.toPage.prop("id"));
} );


text:
Q: What is the best way of making more than one object a delegate of another object? I'm creating an iOS app with 4 tabs (4 view controllers) that gets CoreLocation updates and displays the location along with some other data in various representations (table view, map view, etc)
I only want to use one CoreLocationManager, so I can only have one delegate, but 4 view controllers need to know about the updates so that the visible view can be updated
What is the best way to let my view controllers know that there has been a location update?

A: The simplest is to post a notification rather than using a delegate. Delegates are 1:1 where as notifications are 1:many. Problem is you still need at least one delegate which will post the notifications.
If you want, you can create an NSProxy object which you can set as the location manager delegate and which internally holds a list of other delegates and forwards all of the received method calls to all of the internally managed delegates.

A: The BEST method is probably to simply use the notification center.  Rather than a @protocol, put a NSString * const you're using for the notification:
NSString * const kMyNotificationString @"MyNotificationString"

Now, when the would-be delegates need to respond, it's as simple as:
[[NSNotificationCenter defaultCenter] postNotificationName:kMyNotificationString
                                                    object:nil];

Any object that needs to respond to this notification can #import this header file (so it gets the NSString * const-ed notification name and then and start listening to the notification as such:
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(myMethod)
                                             name:kMyNotificationString
                                           object:nil];

Just don't forget to remove observers when (or before) you dealloc.

Alternatively, there's this approach... but it's not really that great, and I'd actually recommend against it.
Rather than a single delegate property, you could have a NSArray property that handles the "delegates" (make sure you have an "addDelegate" method that only adds weak references to the array).  Then, when you need all of these objects to respond to a change:
for (id<MyProtocol> object in self.arrayOfDelegates) {
    if ([object respondsToSelector:@selector(myMethod)]) {
        [object myMethod];
    }
}

A: The easiest way is implement one delegate that forwards messages as notifications, this way any number of objects can subscribe as observers for those notifications.


text:
Q: If the graph isomorphism problem can't be solved in polynomial time, do spin-networks in loop quantum gravity violate the Church-Turing thesis? If the graph isomorphism problem can't be solved in polynomial time, do spin-networks in loop quantum gravity violate the Church-Turing thesis? To determine whether or not two graphs are isomorphic (labelled in the case of spin networks, but this doesn't change anything essential) is conjectured to be unsolvable in polynomial time in the worst case scenario. It may or may not be solvable in polynomial time using quantum computers. To compute using spin-networks, we have to determine whether or not two components describe the same network when summing up over quantum states and computing bra-ket norms.

A: The Church-Turing thesis concerns which functions are computable. There are many computable functions with nonpolynomial complexity, so I'm not seeing why you mention polynomial time in the question. For graphs with finitely many vertices and edges, graph isomorphism is definitely computable (just hard).
If your concern is computability, then you should be more worried about whether physics really needs the real numbers, since as far as Church-Turing is concerned, they don't exist.


text:
Q: rails routing; path changing for collection At the moment my route for other_notifications/chat_notificaitons is:
/users/:id/notifications/chat_notifications

but I 'd like to have it like:
/users/1/chat_notifications

How can I do that? Is there any issue to watch out for if I change the routes like this?
routes.rb
resources :users do
  resources :notifications, only: [:create, :index] do
    collection do
      get :other_notifications, :chat_notifications
    end
  end
end

A: Try this:
resources :users do
  resources :notifications, only: [:create, :index]
end
get 'users/:user_id/chat_notifications', to: 'controllerName#actionName', as: :custom_name


text:
Q: git - date at which commits were pulled into repository I know from my server logs that an error first starts appearing at a certain time many days ago.
To deploy, I issue a git pull on my server.
I want to find out what commits were pulled around the time the errors started to show up.
Looking at the logs, the <author date> and <committer date> both give the same date across all repositories (as you'd expect), and they relate to when the commit was committed to git (in the development repository), not when it appeared in the deployment repository.
Any idea if it's possible to tease out this info from git?

A: I too want to know a good answer for this, but one thing I can suggest is, get the hash of a commit, go to .git/objects/xx/remaininghash and see the date at which it was created?
I am not directly answering your question, but you can also use git bisect to narrow down which commit caused the problem.

A: Try this:
git reflog show master@{2.weeks.ago}


text:
Q: While loop try/else/except I need to do in loop, go from else to try and when try didnt found go to except.
while True:
    try:
        element = driver.find_element(By. ID, 'pdp_size-reminder-dialog_title')
        print("Monitoring sizes")
    except:
        print("END.")
        break
    else:
        webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
        print("Reselecting size...")
        driver.find_element(By. ID, 'picker-trigger').click()
        driver.find_element(By.XPATH, "//span[normalize-space()='"+random.choice(sizes)+"']").click()
        time.sleep(2)
        continue

A: For me it looks like that:
while True:
    res: Any | None = yields_elements()
    if res is None:
        break
    do_something()
    pause(2)

The yields_elements() might be critical for you, so it would need a try/finally block there instead.


text:
Q: Splitting audio segment by pitch I'm trying to use Pydub to split an audio segment by pitch. My idea is to find the timestamps when the pitch changes and split according to those timestamps.
The part I am stuck on is how to find the time when the pitch changes.
Is there any way to do that?
Thanks


text:
Q: What is paint32 in pyaudio i'm using pyaudio with a microphone.
I've got a problem with the meaning of :
FORMAT = pyaudio.paInt32.

I've been searching for a while but found nothing about it.
Can you help me ?

A: According to the official documentation found here, pyaudio.paInt32 is one of many types of PortAudio Sample Format.
When you are using a software library like PyAudio, I always recommend looking for official documentation, which can be done by going on the official repository page and looking for links to the documentation. For example, here is the path I took to find the answer:

*

*Google "PyAudio"

*Visit the PyPi repository: https://pypi.org/project/PyAudio/

*Go to the homepage of the library: http://people.csail.mit.edu/hubert/pyaudio/

*Go the linked official documentation: http://people.csail.mit.edu/hubert/pyaudio/docs/

*Search (Ctrl+f) for paInt32 and found http://people.csail.mit.edu/hubert/pyaudio/docs/


text:
Q: Is iter(subprocess.Popen_instance.stdout.readline, '') a busy loop? Lets consider following code construct:
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, ''):
    print(line)

Is this for loop a busy loop, or will it wait for output data from process lazily? How can I check this? Regardless of answer, is it part of language specification or implementation detail of CPython?
I'm interested in both Python 2.x and Python 3.x, on major OSes (Windows, macOS, Linux) and their respective kernels.

A: Since readline blocks, the loop is only as busy as there is output available to read.
Test from command line:
#!/usr/bin/env python

import subprocess
args = ('cat', '-')
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, ''):
    print(line.rstrip('\n'))

$ ./x.py
a
a
b
b
<Ctrl-D>


text:
Q: Fast method to find distance from point to closest edge of polygon Setup

*

*Function will need to provide the distance from a point to the closest edge of a polygon

*Point is known to be inside of the polygon

*Polygon can be convex or concave

*Many points (millions) will need to be tested

*Many separate polygons (dozens) will need to be ran through the function per point

*Precalculated and persistently stored data structures are an option.

*The final search function will be in C++

For the function implementation, I know a simple method would be to test the distance to all segments of the polygon using standard distance to line segment formulas. This option would be fairly slow at scale and I am confident there should be a better option.
My gut instinct is that there should be some very fast known algorithms for this type of function that would have been implemented in a game engine, but I'm not sure where to look.
I've found a reference for storing line segments in a quadtree, which would provide for very rapid searching and I think it could be used for my purpose to quickly narrow down which segment to look at as the closest segment and then would only need to calculate the distance to one line segment.
https://people.cs.vt.edu/~shaffer/Papers/SametCVPR85.pdf
I've not been able to locate any code examples for how this would work. I don't mind implementing algorithms from scratch, but don't see the point in doing so if a working, tested code base exists.
I've been looking at a couple quadtree implementations and I think the way it would work is to create a quadtree per polygon and insert each polygon's line segments with a bounding box into the quadtree for that polygon.
The "query" portion of the function I would be making would then consist of creating a point as a very small bounding box, which would then be used to search against the quadtree structure, which would then find only the very closest portions of the polygon.
http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C
and
https://github.com/Esri/geometry-api-java/blob/master/src/main/java/com/esri/core/geometry/QuadTree.java
My real question would be, does this seem like a sound approach for a fast search time function?
Is there something that would work faster?
EDIT:
I've been looking around and found some issues with using a quadtree. The way quadtrees work is good for collision detection, but isn't setup to allow for efficient nearest neighbor searching.
https://gamedev.stackexchange.com/questions/14373/in-2d-how-do-i-efficiently-find-the-nearest-object-to-a-point
R-Trees look to be a better option.
https://en.wikipedia.org/wiki/R-tree
and
efficient way to handle 2d line segments
Based on those posts, R-trees look like the winner. Also handy to see that C++ Boost already has them implemented. This looks close enough to what I was planning on doing that I'll go ahead and implement it and verify the results.

A: EDIT:
Since i have implemented an PMR quadtree, I see now, that the nearest neighbour search is a bit more complex than I described.
If the quad search result for the search point would be empty then it gets more complex.
I remeber a description somewhere in Hannan Sammets:Multidimensional search structure.
Giving the answer below I had in mind searching for all objects withing a specified distance. This is easy for the PMR quadtree, but just finding the closest is more complex.
Edit End
I would not use a R-Tree.
The weak point (and the strong point!) on R-trees is the separation of the space into rectangles.
There are three algorithms known to do that separation but none is well suited for all situations.
R-trees are really complex to implement.
Why then do it? Just because R-Trees can be twice fast than a quad tree when perfectly implemented. The speed difference between a quadtree and a R-Tree is not relevant. The monetary difference is. (If you have working code for both I would use the PMR quadtree, if you have only code for the R-Tree then use that, If you have none use the PMR Quadtree)
Quad trees (PMR) always work, and they are simple to implement.
Using the PMR quad tree, you just find all segments related to the search point. The result will be a few segments, then you just check them and ready you are.
People that tell quad trees are not suited or neighbour search, do not know that there are hundreds of different quad trees. The non suitability is just true for a point quad tree, not for the PMR one, which stores bounding boxes.
I once remebered the compelx description of finding the neighbour points in a POINT-Quadtree. For the PMR-quadtree I had nothing to do (for a search within a specified rectangular interval), no code change, Just iterate the result and find the closest.
I think that there are even better solutions than Quad tree or R-Tree for your spefic questions, but the point is that the PMR always work. Just implement it one time and use if for all spatial searches.

A: Since there are so many more points to test than polygons, you could consider doing some fairly extensive pre-processing of the polygons in order to accelerate the average number of tests to find the nearest line segment per point.
Consider an approach like this (assumes polygons have no holes):

*

*Walk the edges of the polygon and define line segments along each equidistant line

*Test which side of the line segment a point is to restrict the potential set of closest line segments

*Build an arithmetic coding tree with each test weighted by the amount of space that is culled by the half-space of the line segment.  this should give good average performance in determining the closest segment for a point and open up the possibility of parallel testing over multiple points at once.

This diagram should illustrate the concept. The blue lines define the polygon and the red lines are the equidistant lines.
Notice that needing to support concave polygons greatly increase the complexity, as illustrated by the 6-7-8 region.  Concave regions mean that the line segments that extend to infinity may be defined by vertices that are arbitrarily far apart.
You could decompose this problem by fitting a convex hull to the polygon and then doing a fast, convex test for most points and only doing additional work on points that are within the "region of influence" of the concave region, but I am not sure if there is a fast way to calculate that test.

A: I am not sure how great the quadtree algorithm you posed would be, so I will let someone else comment on that, but I had a thought on something that might be fast and robust.
My thought is you could represent a polygon by a KD-Tree (assuming the vertices are static in time) and then find the nearest two vertices, doing a nearest 2 neighbor search, to whatever the point is that lies in this polygon. These two vertices should be the ones that create the nearest line segment, regardless of convexity, if my thinking is correct.


text:
Q: Não está inserindo dados no BD MyPhpAdmin localhost Olá. Estou realizando um exemplo passo a passo de um mini curso pelo YouTube.
Fiz a tela de setup em php com framework PHP: nome, email, senha, clico em Salvar dados e a validação funciona corretamente. Validação seria printar a mensagem de alerta se a pessoa não está digitando correntamente.
Deu validação ok e na hora de verificar lá no BD (localhost) se deu tudo certo, não tem nenhum registro.
Poderia me ajudar?
Banco: localhost
username: root
Sem senha
database: cursoci
Tabela: options
colunas: id (int:11)PK, option_name (varchar:255) e option_value (text)
Controller: setup.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Setup extends CI_Controller {

function __construct(){
    parent::__construct();
    $this->load->helper('form');
    $this->load->library('form_validation');
    $this->load->model('option_model', 'option');
}

public function index(){

    if($this->option->get_option('setup_executado') == 1):
        // setup ok, mostrar tela para editar dados de setup
        redirect('setup/alterar','refresh');
    else:
        //não instalado, mostra tela de setup
        redirect('setup/instalar','refresh');
    endif;
}

public function instalar(){
    //O começo é igual a função index
    if($this->option->get_option('setup_executado')==1):
        redirect('setup/alterar','refresh');
    endif;

    // regras de validação
    $this->form_validation->set_rules('login', 'NOME', 'trim|required|min_length[5]');
    $this->form_validation->set_rules('email', 'EMAIL', 'trim|required|valid_email');
    $this->form_validation->set_rules('senha', 'SENHA', 'trim|required|min_length[6]');
    $this->form_validation->set_rules('senha2', 'REPITA A SENHA', 'trim|required|min_length[6]|matches[senha]');

    //verifica a validação
    if($this->form_validation->run() == FALSE):
        if(validation_errors()):
            set_msg(validation_errors());
        endif;
    else:
        set_msg('
validação okk</php>');
    endif;
    //carrega view
    $dados['titulo'] = 'RBernardi - Setup do Sistema';
    $dados['h2'] = 'Setup do Sistema';
    $this->load->view('painel/setup', $dados);
}
}

View: painel/setup.php
<!DOCTYPE html>

<meta charset="UTF-8" />
<title> <?php echo $titulo; ?></title>  <!–  DEU CERTO O TÍTULO ->
<link href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700' rel='stylesheet' type='text/css' />
<link rel="stylesheet" href="<?php echo base_url('assets/css/estilo.css') ?>" />
<link rel="stylesheet" href="<?php echo base_url('assets/css/painel.css') ?>" />

<?php echo $h2; ?>

        <?php
            if($msg = get_msg()):
               echo '
'.$msg.'
';
            endif;
            echo form_open();
            echo form_label('Nome para login:', 'login');
            echo form_input('login', set_value('login'), array('autofocus' => 'autofocus'));
            echo form_label('Email do Administrador do site:', 'email');
            echo form_input('email', set_value('email'));
            echo form_label('Senha:', 'senha');
            echo form_password('senha', set_value('senha'));
            echo form_label('Repita a Senha:', 'senha2');
            echo form_password('senha2', set_value('senha2'));
            echo form_submit('envia', 'Salvar dados', array('class' => 'botao'));
            echo form_close();
        ?>

Model: option_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Option_model extends CI_Model {

function __construct(){
    parent::__construct();
}

public function get_option($option_name){
    $this->db->where('option_name', $option_name);
    $query = $this->db->get('options', 1);
    if($query->num_rows() == 1):
        $row = $query->row();
        return $row->option_value;
    else:
        return NULL;
    endif;
}

Helper: funcoes_helper.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

if(!function_exists('set_msg')):
function set_msg($msg=NULL){
    $ci = & get_instance();
    $ci->session->set_userdata('aviso', $msg);
}
endif;

if(!function_exists('get_msg')):
function get_msg($destroy=TRUE){
    $ci = & get_instance();
    $retorno = $ci->session->userdata('aviso');
    if($destroy) $ci->session->unset_userdata('aviso');
    return $retorno;
}
endif;

routes.php
$route['login'] = 'setup/login';
$route['painel'] = 'setup/login';

autoload.php
$autoload['libraries'] = array('database', 'session');
$autoload['helper'] = array('url', 'funcoes');

assets/css/painel.css
label{
display: block;
font-size: 13px;
font-weight: 300;
}
input, textarea{
display: block;
margin-bottom: 15px;
padding: 5px 2%;
width: 96%;
}
input[type="file"]{
padding-left: 0;
}
textarea{
height: 150px;
}
input.botao{
width: auto;
}
.msg-box{
background: #f1f2ea;
border: 1px solid #c7cbab;
padding: 5px 10px;
margin-bottom: 15px;
color: #727272;
}

.msg-box p{
margin: 0;
padding: 2px 0;
}

A: Não conheço o framework mas em nenhum momento do código vc mostrou algo que altera dados do banco. Acredito que seu curso ainda não tenha feito a função de insert.
Achei seu curso na web e foi isso mesmo. Faltou  a lógica de inserção.
}else{
            //set_msg('
validação ok
');
            $dados_form = $this->input->post();
            $this->option->update_option('user_login',$dados_form['login']);
            $this->option->update_option('user_email',$dados_form['email']);
            $this->option->update_option('user_pass',password_hash($dados_form['senha'],PASSWORD_DEFAULT));

            $inserido = $this->option->update_option('setup_executado',1);
            if($inserido){
                set_msg('
Sistema INSTALADO
');
                redirect('setup/login','refresh');
            }

        }


text:
Q: Need explanation of option ethtool -K I did

rsync -av --rsh=ssh ...

and catch error

Corrupted MAC on input. Packet Corrupt

I found solution here

ethtool -K eth0 tx off rx off

This option disabled TCP checksum of ethernet adapter. But what does it mean, processor is responsible of TCP checksum now?
If I off TCP checksum permanently for ethernet adapter, it is normal or I will have bad consequences?

A: If you disable TCP checksum offloading, it will need to be carried out at a higher level. This will put put additional load on the higher level processor. As to it's consequence, that depends upon the spec of the system and the work it it doing, I don't think we can give any reasonable assurances here.

*

*I would make the change and attempt to test it in a lab.

*I would also check to see if there are driver/firmware updates for the NIC which I could apply and test.

*Changing the NIC may be a solution too.


text:
Q: Finding a good cover such that its lifting is still a good cover Let $Y$ be a compact manifold, $X$ a topological space and $f: X \to Y$ a surjective map. Suppose further that every point in $Y$ has arbitrarily small open neighbourhoods such that their preimages in $X$ are contractible.
Under these conditions, can we find a good cover for $Y$ such that its preimage is also a good cover for $X$ (i.e. such that any finite intersections of open sets in the cover is contractible)?
This would follow easily if the preimage of a contractible subspace in $Y$ was still contractible, but I have been unable to prove this or to find a counterexample.