text:
Q: NoClassDefFoundError after refactoring name I am using the Eclipse IDE to create an Android application compliant with Android 2.2 and higher.  I refactored the name of one of my main activities.  My basic structure is that I have a pseudo home page activity in which other "apps" (actually activities) inside this one app have icons that lead to their respective activity.  I had a class that was originally the head activity for one of these branches in the app, call it Activity.java.  Activity.java ended up just pointing to Activity_Home.java and no longer did anything so I decided to get rid of it.  I deleted Activity.java, rebuilt, then refactored Activity_Home.java to Activity.java, rebuilt.  Got a NoClassDefFoundError:
05-01 10:13:12.609: E/AndroidRuntime(15635): FATAL EXCEPTION: main
05-01 10:13:12.609: E/AndroidRuntime(15635): java.lang.NoClassDefFoundError: Activity.java

so then I renamed it back to Activity_Home.java after fiddling for a bit thinking that might help something.  Completely cleaning and rebuilding before every attempt to launch.  Kept getting the error even though I checked the CLASSPATH and that the .class file was being named correctly.  Eventually I read that someone, though they don't know why this worked, fixed a similar problem by deleting and remaking the file.  I did that.
That seems to have worked, but I don't know why and now every file deeper then Activity_Home.java (eg. there is an activity called by it Activity_Camera.java) is having the same issue.
I obviously do not want to have to delete and remake all of the .java files and even if that fixes the issue I would still like to know WHY this is happening not just HOW TO FIX it.
EDIT 1: Forgot to mention that I already checked the Manifest file for inconsistencies.  The issue is now happening on a class that I did not even rename. Could be part of the automated refactor renaming? (pure speculation)
EDIT 2: Issue with SherlockListActivity. Says it can't find the APK after whatever refactoring I did. When I remove SherlockListActivity it fixes my issues.

A: Refactoring name will change the class name in the java classess, but not in manifest file.
Try to change the class name in AndroidManifest.xml also, that will fix the issue

A: *

*You initially had a file Activity.java which did nothing but pointed to Activity_home.java.
From pointing , I assume it opens the Activity_home.java . Whenever you create an Activity , its entry is added in the AndroidManifest.xml file. However, when you delete an activity , I think it is not removed from the manifest file. So Change your main file to MainActivity.java and change its corresponding entry in the manifest like this.

Just check the other activities whether their names and packages are correct in manifest and you are good to go .
 <activity android:name="com.raman.MainActivity">
      <intent-filter>
           <action android:name="android.intent.action.MAIN"/>
           <category android:name="android.intent.category.LAUNCHER">
        </intent-filter>
  </activity>

A: Some things you have to check. Those are :

*

*Check Package name of your app from menifest.xml and build.gradle both file.

*Check manifest activity name with full path. If activity path is incorrect then correct it.

*If problem not solved then execute File--> Invalidate Cache / Restart . Hope problem will solved.

*If problem not solved then delete build folder and rebuild the project. Now your problem will solved.
Thanks :)


text:
Q: VLAN over VPN (ASA 5520)? if not any other options available? Is it possible to extend the local VLANs to a Remote site connected by IPSEC VPN using ASA 5520 / Cisco 1841 DSL router.
can we have many VPN tunnels between the ASAs? (from every VLAN one vpn each?)
if not any other options/combinations available?

A:
Is it possible to extend the local VLANs to a Remote site connected by IPSEC VPN

No, per definition. IpSec is an IP level security tunnel. Vlans are ethernet level.

can we have many VPN tunnels between the ASAs

Yes. This is a maintenance nightmare if it gets too much and is not automated in management, but it is possible.

if not any other options/combinations available?

If you put up an ethernet tunnel between them - not sure this is possible - you can then use the "normal" VLAN packets.
http://www.cisco.com/en/US/docs/ios-xml/ios/interface/configuration/xe-3s/ir-eogre.html
has some information, though I am not sure this works on the 1841. But this would allow you to basically send ethernet frames with VLAN information embedded.
Alternatively a multi routing table setup may work - depends on WHY you have VLANS in the first place. or something based on MPLS - VPLS. The 1841 does not talk that one though.
More professional routers may allow something like NVGRE for that purpose. Well, not exactly professional - but the 1841 is more an edge level router not something to use in the core.
It seems that the 1841 can do VPLS - that would work best then. Requires you to configure a MPLS setup.
Main problem answering is that a lot of the choices depends on what you actually try to do from a  business point of view and how much control you have over the routers at each endpoint.

A: Normally you can extend your local LAN to a remote site using common IPsec / Layer 3. Search for Site-to-site, lan-to-lan ipsec VPN.
There are a lot of options, my favorite one is to use GRE over IPsec, but you need routers on both ends. If you can tell us what devices you have available on hub/spoke sites it would help in order to give you a more specific answer.
If you want to extend your layer 2 network, which is not a very good idea for many reasons, I believe that the best option is to use L2TPv3 over IPsec. Again you need routers on both ends.
You have to take care of many issues though, such as MTU sizes which could overload your router if you don't pay attention to details, broadcast, multicast, spanning-tree, redundancy etc which are handled easier on Layer3 VPN.

A: You can use NAT on the ASA and router IPSec tunnel to connect the overlapping subnets.  You can put additional subnets in the IPSec tunnel by adding them to the IPSec tunnel protected networks (the ACL referenced by the tunnel configuration), instead of creating a tunnel for each subnet to subnet connection.  If the devices at each site have to communicate with each other at layer 2, you will need to extend the LAN with a layer 2 wan link or layer 2 tunneling protocol.  If you use NAT on an IPSec tunnel, the devices at each site will not be able to communicate with each other at layer 2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Executing "ps" via Runtime exec outputs a lot of data As far as I know running
ps

with no args in a shell would give me all other processes's started by that shell. However If I run a java jar with a
Runtime.getRuntime.exec("ps");

The output of the command is almost evry process in my system. How do I get only processes's started by the shell that started the jar?


text:
Q: Useful ASP.NET modules? I recently discovered ELMAH as a drop-in module for error logging for ASP.NET and am now wondering: what other killer modules do I not know about? What's your favourite/indispensible ASP.NET module/handler/whatever? (I work in ASP.NET 2.0 so please specify version compatibility!)

A: There's a good selection of modules at:http://www.iis.net/downloads (mostly IIS7 modules)
My favourite is probably the streaming module that limits bandwidth after an intial burst of data, optimizing the transfer of progressive downloads: http://www.iis.net/media.
As for IIS6, SAFileup was useful for allowing large file transfers by chunking files to disk rather than loading the data into memory (ISAPI Plugin + .net Module). This is a commercial product however and I think they're may be some free or cheaper alternatives now days.
There's also several dynamic image resizing modules that are extremely useful.


text:
Q: Apache2 .htaccess redirect to https not working I realize this is a question that was answered a lot but the other solutions are not working for me for some reason. I am trying to rewrite http as https but I am still getting 'Bad Request' when I try to browse my website using http.
Here is the code in my .htaccess:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

I have AllowOverride All in the VirtualHost config and I made sure mod_rewrite is enabled.
Any help is appreciated. Let me know if you need more information.
Edit:
Here is my complete .htaccess file:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RemoveHandler .html .htm
AddType application/x-httpd-php .php .htm .html

POSSIBLE Solution:
I was using Apache 2.2. This may be a bug with the older version of Apache. I am going to update and I will post again when I know more.

A: First of all you should be sure of enable mod_rewrite and ssl on your apache, by this codes
sudo a2enmod rewrite
sudo a2enmod ssl

and then restart your apache
 sudo service apache2 restart

now follow this steps
sudo nano /etc/apache2/sites-enabled/000-default.conf

and add this codes
<VirtualHost *:80>
    ServerName my.site.com
    ServerAlias my.site.com
    DocumentRoot /var/www/SITE-PATH
    <Directory /var/www/SITE-PATH>
        AllowOverride All
        Order Allow,Deny
        Allow from All
    </Directory>
    ErrorLog /var/log/apache2/project_error.log
    CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>

then go to your website directory /var/www/SITE-PATH and add this code to your .htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

and for your ssl credit on path /etc/apache2/sites-enabled/default-ssl.conf
you should have something like this
<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerAdmin webmaster@localhost
        ServerAdmin admin@example.com
        ServerName my.site.com #important
        ServerAlias my.site.com #important
        DocumentRoot /var/www/SITE-PATH #important
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        SSLEngine on
        SSLCertificateFile /etc/apache2/ssl/apache.crt #important
        SSLCertificateKeyFile /etc/apache2/ssl/apache.key #important
        SSLCertificateFile  /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>
        BrowserMatch "MSIE [2-6]" \
                nokeepalive ssl-unclean-shutdown \
                downgrade-1.0 force-response-1.0
        BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    </VirtualHost>
</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

if you go all steps right, you should have this at end

http://my.site.com => redirect to => https://my.site.com
EDIT:
for more detail on SSL please follow How To Create a SSL Certificate on Apache for Ubuntu 14.04 and this post

A: Try:
 RewriteEngine On
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


text:
Q: PROCEDURE test_multi_sets in mysql can someone explain me what does this chunk of code means?
DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`username`@`localhost` PROCEDURE `test_multi_sets`()
    DETERMINISTIC
begin
        select user() as first_col;
        select user() as first_col, now() as second_col;
        select user() as first_col, now() as second_col, now() as third_col;
        end$$

DELIMITER ;

Because my database exports only with this, and it seems to cause troubles for me to import it to another server.

A: This
DEFINER=`username`@`localhost`

tells MySQL that the procedure is executed with the rights that the user username@localhost has. If it causes problems to import, you most likely haven't created that user on the destination server yet.
The procedure is just a test someone wrote. It does nothing important, it simply selects the current user and the current time.
I bet you can delete it.


text:
Q: Failed to load url in Dom Document? I'm trying to get latitude and longtitude from google map by giving address. But it's giving error. When I directly copy url to browser url bar. it's giving correct result. If anybody know the answer.
Here is my code.
<?php
$key = '[AIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0]';

$opt = array (
'address'   => urlencode('Kolkata,India, ON') ,
'output'    => 'xml'
);

$url = 'http://maps.google.com/maps/geo?q='.$opt['address'].'&output='.$opt['output'].'&oe=utf8&key='.$key;

$dom = new DOMDocument();
$dom->load($url);

$xpath = new DomXPath($dom);
$xpath->registerNamespace('ge', 'http://earth.google.com/kml/2.0');

$statusCode = $xpath->query('//ge:Status/ge:code');

if ($statusCode->item(0)->nodeValue == '200') {

$pointStr = $xpath->query('//ge:coordinates');
$point = explode(",", $pointStr->item(0)->nodeValue);

$lat = $point[1];
$lon = $point[0];

echo '<pre>';
echo 'Lat: '.$lat.', Lon: '.$lon;
echo '</pre>';
}

?>

Following error has occured:
Warning: DOMDocument::load(http://maps.google.com/maps/geo?      q=Kolkata%252CIndia%252C%2BON&output=xml&oe=utf8&key=%5BAIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0%5D) [domdocument.load]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\xampp\htdocs\draw\draw.php on line 19

Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "http://maps.google.com/maps/geo?q=Kolkata%252CIndia%252C%2BON&output=xml&oe=utf8&key=%5BAIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0%5D" in C:\xampp\htdocs\draw\draw.php on line 19

Notice: Trying to get property of non-object in C:\xampp\htdocs\draw\draw.php on line 26

A: DOMDocument::load() requires allow_url_fopen to be true.
Check your php.ini-settings and switch it to 1.
See also:
http://php.net/filesystem.configuration.php#ini.allow-url-fopen
What would cause DOMDocument.load to fail loading XML from a URL that is accessible?


text:
Q: event SOCKET_DATA does not receive all messages in AS3 My AS3 client program does not receive all the data that was sent to it when sending a lot of messages. I do know its not my server causing this problem because all the messages are received and send correctly. My as3 client just does not receive all the data send.
    private function socketData(event:ProgressEvent):void {
       while(this.socket.bytesAvailable}
          var str:String = this.socket.readUTFBytes(this.socket.bytesAvailable);
          trace(str);
       }
    }

Does any of you know a solution?

A: I had the same issue this afternoon. Finally i came with a solution:
In fact, you have to read the message byte by byte like so:
private function socketData (evt:ProgressEvent):void {
    var msg:String = ""; // create a buffer
    while (socket.bytesAvailable) { // while there is byte to read
        var byte:int = socket.readByte();
        if (byte==0) { // if we read the end byte
            trace(msg); // treat your message
            msg = ""; // free the buffer
        } else {
            msg += String.fromCharCode(byte); // else, we add the byte to our buffer
        }
    }
}

I hope this will help you :)

A: Problem solved, I just had to open the port on my router.


text:
Q: What's "preauthorization" in a Cocoa app? What's "preauthorization" in a Cocoa app? And why it always succeeds even when using a random auth right name? That is, why the following code never throws an error?
let rightName = ("some-random-string" as NSString).UTF8String
let flags = [.PreAuthorize, .ExtendRights, .InteractionAllowed]
SFAuthorization().obtainWithRight(rightName, flags: flags)


text:
Q: Not able to match input with expected result I'm making a Visual Basic program for a game called Mastermind, where there are a certain number of pins (defined by the user) and a number of color options for each pin (also defined by the user). The user tries to guess a randomly generated "code" by selecting the color for each pin, and the system tells you how many pins you got correct, and how many colors you got correct, but on the wrong pin.
The issue is, when I search my array and tell it to display the number of correct pins, it always displays either 1 or 0, even when I set it to only one color option (meaning I should get all of them right by default). Here is my code (yes I know the ColorsCorrect function is empty, but that one isn't concerned here):
 Imports System.Drawing.Color
Public Class Form1
    Dim intNumbOfPegs As Integer = 0
    Dim intNumbOfColors As Integer = 0
    Dim intPegsGenned As Integer = 0
    Dim intColorsGenned As Integer = 0
    Dim intColorsToGuess(-1) As Integer
    Dim intColorsGuessed(-1) As Integer
    Dim GroupBox(-1) As GroupBox
    Dim RadioButton(-1, -1) As RadioButton
    Dim blnGenNewNumbs As Boolean = True

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Do
            intNumbOfPegs = InputBox("Enter The Number of Pegs (1 - 10):", "Number of Pegs")
            intNumbOfColors = InputBox("Enter The Number of Colors (1 - 9):", "Number of Colors")
            If intNumbOfColors = 0 Or intNumbOfColors > 9 Or intNumbOfPegs = 0 Or intNumbOfPegs > 10 Then
                MessageBox.Show("Invalid Input. Please Try Again", "Error")
            Else
                MessageBox.Show("You Have Selected " & intNumbOfPegs & " Pegs and " & intNumbOfColors & " Colors")
            End If
        Loop While intNumbOfColors = 0 Or intNumbOfColors > 9 Or intNumbOfPegs = 0 Or intNumbOfPegs > 10
        ReDim intColorsGuessed(intNumbOfPegs - 1)
        ReDim intColorsToGuess(intNumbOfPegs - 1)
        ReDim GroupBox(intNumbOfPegs - 1)
        ReDim RadioButton(intNumbOfColors - 1, intNumbOfPegs - 1)
        Do While intPegsGenned < intNumbOfPegs
            intPegsGenned = intPegsGenned + 1
            GroupBox(intPegsGenned - 1) = New GroupBox
            GroupBox(intPegsGenned - 1).Name = "grpPeg" & intPegsGenned
            GroupBox(intPegsGenned - 1).Text = "Peg " & intPegsGenned
            GroupBox(intPegsGenned - 1).Size = New System.Drawing.Size(64, 238)
            GroupBox(intPegsGenned - 1).Location = New System.Drawing.Point(59 + (70 * intPegsGenned), 12)
            Do While intColorsGenned < intNumbOfColors
                intColorsGenned = intColorsGenned + 1
                RadioButton(intColorsGenned - 1, intPegsGenned - 1) = New RadioButton
                RadioButton(intColorsGenned - 1, intPegsGenned - 1).Size = New System.Drawing.Size(31, 17)
                RadioButton(intColorsGenned - 1, intPegsGenned - 1).Name = "radPeg" & intPegsGenned & "Color" & intColorsGenned
                RadioButton(intColorsGenned - 1, intPegsGenned - 1).Text = intColorsGenned
                RadioButton(intColorsGenned - 1, intPegsGenned - 1).Location = New System.Drawing.Point(17, 6 + (23 * intColorsGenned))
                'AddHandler RadioButton(intColorsGenned - 1).CheckedChanged, AddressOf AllRadButtons_CheckedChanged
                GroupBox(intPegsGenned - 1).Controls.Add(RadioButton(intColorsGenned - 1, intPegsGenned - 1))
            Loop
            intColorsGenned = 0
            Controls.Add(GroupBox(intPegsGenned - 1))
        Loop
    End Sub

    Private Sub btnCheckGuess_Click(sender As Object, e As EventArgs) Handles btnCheckGuess.Click
        Dim intColorToCheck As Integer = 0
        Dim intPegToCheck As Integer = 0

        If blnGenNewNumbs = True Then
            ChooseColors()
            blnGenNewNumbs = False
        End If

        Do While intPegToCheck < intNumbOfPegs
            Do While intColorToCheck < intNumbOfColors
                If RadioButton(intColorToCheck, intPegToCheck).Checked = True Then
                    intColorsGuessed(intPegToCheck) = intColorToCheck + 1
                End If
                intColorToCheck = intColorToCheck + 1
            Loop
            intPegToCheck = intPegToCheck + 1
        Loop

        lblGuessDisplay.Text = lblGuessDisplay.Text & " Correct Pegs: " & PegsCorrect() & " Correct Colors: " & ColorsCorrect()

    End Sub

    Sub ChooseColors()
        Dim intNumbsFilled As Integer = 0
        Do While intNumbsFilled < intNumbOfPegs
            intColorsToGuess(intNumbsFilled) = RndInt()
            intNumbsFilled = intNumbsFilled + 1
        Loop
    End Sub
    Function RndInt()
        Dim intNumbToSend As Integer = 0
        Randomize()
        intNumbToSend = (Int(intNumbOfColors * Rnd()) + 1)
        Return intNumbToSend
    End Function

    Function PegsCorrect() As Integer
        Dim intPegsCorrect As Integer = 0
        Dim intPegCorrectToCheck As Integer = 0

        Do While intPegCorrectToCheck <= (intNumbOfPegs - 1)
            If intColorsToGuess(intPegCorrectToCheck) = intColorsGuessed(intPegCorrectToCheck) Then
                intPegsCorrect = intPegsCorrect + 1
            End If
            intPegCorrectToCheck = intPegCorrectToCheck + 1
        Loop
        Return intPegsCorrect
    End Function

    Function ColorsCorrect() As Integer
        Dim intColorsCorrect As Integer = 0

        Return intColorsCorrect
    End Function

End Class

Why is it not working as intended?

A: First, you need to enable Option Strict On. That will point out some problems, but not enough to make it work.
Next, those While loops are begging to be changed to For..Next loops. I may or may not have corrected an off-by-one error or two when I did that to see if I could fix it. Some variable renaming was in order - there is no point having nigh on everything preceded by "int". Some variables had too wide a scope too.
With the code cleaned up a bit, it is now easier to debug it and discover that the RndInt() function isn't behaving as you might hope - banker's rounding is not what is needed there; instead you need:
Function RndInt() As Integer
    Return CInt(Math.Truncate(nColours * Rnd())) + 1

End Function

For what it's worth, this is where I ended up getting it to work:
Public Class Form1

    Dim nPegs As Integer = 0
    Dim nColours As Integer = 0

    Dim hiddenColours(-1) As Integer
    Dim userGuesses(-1) As Integer

    Dim GroupBox(-1) As GroupBox
    Dim RadioButton(-1, -1) As RadioButton

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim inputsValid As Boolean
        Do
            nPegs = CInt(InputBox("Enter The Number of Pegs (1 - 10):", "Number of Pegs"))
            nColours = CInt(InputBox("Enter The Number of Colors (1 - 9):", "Number of Colors"))
            inputsValid = nColours >= 1 AndAlso nColours <= 9 AndAlso nPegs >= 1 AndAlso nPegs <= 9

            If inputsValid Then
                MessageBox.Show("You Have Selected " & nPegs & " Pegs and " & nColours & " Colors")
            Else
                MessageBox.Show("Invalid Input. Please Try Again", "Error")
            End If

        Loop While Not inputsValid

        ReDim userGuesses(nPegs - 1)
        ReDim hiddenColours(nPegs - 1)
        ReDim GroupBox(nPegs - 1)
        ReDim RadioButton(nColours - 1, nPegs - 1)

        Randomize()
        ChooseColors()

        For pegNumber = 0 To nPegs - 1
            GroupBox(pegNumber) = New GroupBox
            GroupBox(pegNumber).Name = "grpPeg" & pegNumber
            GroupBox(pegNumber).Text = "Peg " & (pegNumber + 1)
            GroupBox(pegNumber).Size = New System.Drawing.Size(64, 238)
            GroupBox(pegNumber).Location = New System.Drawing.Point(59 + (70 * pegNumber), 12)

            For colourNumber = 0 To nColours - 1
                Dim rb As New RadioButton
                rb.Size = New System.Drawing.Size(31, 17)
                rb.Name = "radPeg" & pegNumber & "Color" & colourNumber
                rb.Text = (colourNumber + 1).ToString()
                rb.Location = New System.Drawing.Point(17, 29 + 23 * colourNumber)

                RadioButton(colourNumber, pegNumber) = rb
                GroupBox(pegNumber).Controls.Add(RadioButton(colourNumber, pegNumber))

            Next

            Me.Controls.Add(GroupBox(pegNumber))

        Next

    End Sub

    Private Sub btnCheckGuess_Click(sender As Object, e As EventArgs) Handles btnCheckGuess.Click
        For peg = 0 To nPegs - 1
            For colourNum = 0 To nColours - 1
                If RadioButton(colourNum, peg).Checked Then
                    userGuesses(peg) = colourNum + 1
                End If
            Next
        Next

        lblGuessDisplay.Text = " Correct Pegs: " & PegsCorrect() & " Correct Colors: " & ColorsCorrect()

    End Sub

    Sub ChooseColors()
        For i = 0 To nPegs - 1
            hiddenColours(i) = RndInt()
        Next

    End Sub

    Function RndInt() As Integer
        Return CInt(Math.Truncate(nColours * Rnd())) + 1

    End Function

    Function PegsCorrect() As Integer
        Dim nCorrect As Integer = 0

        For i = 0 To nPegs - 1
            If hiddenColours(i) = userGuesses(i) Then
                nCorrect += 1
            End If
        Next

        Return nCorrect

    End Function

    Function ColorsCorrect() As Integer
        Dim intColorsCorrect As Integer = 0

        Return intColorsCorrect

    End Function

End Class


text:
Q: Is there any kubectl command to poll until all the pod roll to new code? I am building deploy pipeline. I Need a "kubectl" command that would tell me that rollout is completed to all the pods then I can deploy to next stage.

A: The Deployment documentation suggests kubectl rollout status, which among other things will return a non-zero exit code if the deployment isn't complete.  kubectl get deployment will print out similar information (how many replicas are expected, available, and up-to-date), and you can add a -w option to watch it.
For this purpose you can also consider using one of the Kubernetes APIs.  You can "get" or "watch" the deployment object, and get back something matching the structure of a Deployment object.  Using that you can again monitor the replica count, or the embedded condition list, and decide if it's ready or not.  If you're using the "watch" API you'll continue to get updates as the object status changes.
The one trick here is detecting failed deployments.  Say you're deploying a pod that depends on a database; usual practice is to configure the pod with the hostname you expect the database to have, and just crash (and get restarted) if it's not there yet.  You can briefly wind up in CrashLoopBackOff state when this happens.  If your application or deployment is totally wrong, of course, you'll also wind up in CrashLoopBackOff state, and your deployment will stop progressing.  There's not an easy way to tell these two cases apart; consider an absolute timeout.


text:
Q: console println in eclipse not printed I have made a simple spring application followin a tutorial.
Running the application gives me no errors in the console.
Problem: But unfortunately I do not get any prints by the program in the console.
I am also not able to debug because Eclipse does not stop at the break point.
Note: I have also found a post about the eclipse console but the solutions do not really seem to work for me. I think it is a problem in my project.
Question: Do I have to open a special perspective to see the prinln output in the console?
Main Class:
public class SpringDataDemo {
    public static void main(String[] args) {
        try {
            ApplicationContext context = new ClassPathXmlApplicationContext("resources\\spring-configuration.xml");

            // Fetch the DAO from Spring Bean Factory
            EmployeeDao employeeDao = (EmployeeDao) context.getBean("EmployeeDaoImpl");
            Employee employee = new Employee("Employee123");
            // employee.setEmployeeId("1");

            // Save an employee Object using the configured Data source
            employeeDao.save(employee);
            System.out.println("Employee Saved with EmployeeId " + employee.getEmployeeId());

            // find an object using Primary Key
            Employee emp = employeeDao.findByPrimaryKey(employee.getEmployeeId());
            System.out.println(emp);

            // Close the ApplicationContext
            ((ConfigurableApplicationContext) context).close();
        } catch (BeansException | SQLException e) {
            e.printStackTrace();
        }
    }
}

A: I got the Eclipse console broken once in a while too. You might have multiple threads running the same instance, just looking at the wrong console tab.
Anyway easiest fix would be to completely restart your system.


text:
Q: Playing video file in Android I want to play the video file and it's like
http://test.XXXX.com/myfile.wmv

am using Video view for that but it saying unable to play video error
I tried using WebView also but it showing only blank page.
Just i want to play that video link file in device online.
How to do that ?
Note : The links are working i tested on Windows browser.
Thanks

A: You will have to transcode the video to an android supported format and make the result available on your server as well.
http://developer.android.com/guide/appendix/media-formats.html provides an official overview of supported forms, but you may have more practical look googling for instructions on transcoding for android devices.


text:
Q: When adding CSS to a CMS dynamically should I write it to the DB or to file I a working on a CMS and I want to be able to add CSS via the administrative control panel.
When I add css should I just append it to the bottom of the stylesheet I have or is it best to add the data to a DB and then get it using a handler.
The way I see it they both seem to have advantages.
writing to file:
It is simple and requires very little code
The file is portable and can be copied like any other css file
writing to a DB:
I have more control
I can load only the classes I need for each document

A: I would amend the CSS file itself. Having dynamic CSS across the site will cause you issues as the style sheet will get cached, so it's better to put all of the style into the file and allow local caching to speed up the page than try to make lots of small CSS files.
There would be no harm in storing each rule in a database and using that information to create the .css file - it would be easier than parsing the string in the CSS file and finding an insert point, but make sure you just write the CSS file when there is a change. If you do it on demand, you'll be needlessly hitting your database constantly.

A: Having done both in previous lives, I think the answer depends on who is maintaining the CSS.
If it is a simple-interface for a non-technical user to manage a few simple styles, I would store this in the database, but as structured data, not raw CSS, and generate the CSS itself at run time. However as Sohnee mentions, you need to ensure it is not generated for every request, as this would be an unnecessary overhead - you should generate to a flat file, or cache effectively.
If it is an interface for a web-developer type person, who understands the concepts of files, and you want to give them full access to write any css they like (and you trust them!) then I would store it as a file (if I were the developer, I would want it to be using my raw CSS). However, I would not append it to the existing stylesheet (assuming that is the default base set of styles for the site)
  I would have a separate stylesheet for user-defined styles, called in the page with a separate link tag. This will keep the site 'code' separate from its 'content'. Note also what Zhaph - Ben Duguid says here about ensuring the browser does not cache old versions by adding some sort of version parameter to the URL.

writing to a DB: I have more control I
  can load only the classes I need for
  each document

I'd say only loading the classes per document would generally be a bad idea. Browsers are tuned for CSS caching, so you nearly always will be better off calling all your CSS from external files, with the appropriate caching headers.

A: The biggest danger with appending the styles to the existing CSS is that if a browser has cached a version of the file, they will not see the updated styles untill the browser refreshes it's cache.
One way around that is to include a version string somewhere in call to the style sheet (for example (from SO)):
<link rel="stylesheet" href="/Content/all.min.css?v=2644">

However, this means that you'll also have to update the calls to the file each time you make the change, which may not possible.
That said, this is probably the route I'd take if I was going to be adding styles that often that uploading a new version of the stylesheet wasn't an option.


text:
Q: Minimization of known cost function without knowing original function I am trying to fit one function to another function by adjusting two parameters. But I dont know the form of this function. I have only cost function because for computation of this function is used LAMMPS (molecular dynamics). I need some tool which i can give only cost function and my guess and then it would minimize it.
I was looking on SciPy optimization but it looks like it needs the original function which i dont have.

A: A function approximation algorithm needs you to make a few assumptions about how your mathematical model behaves.
If you see things from a black box point of view, three scenarios can occur -
X -> MODEL -> Y

*

*You have the X and MODEL, but you dont have the Y; This is simulation

*You have the MODEL and Y, but you dont have the X; This is Optimization

*You have the X and Y, but you dont have the MODEL; This is mathematical modelling

However there is a catch. You can NEVER do 3. directly. Instead you use a trick to reframe the 3. as a 2. (optimization problem). The trick is to say that you assume your model to be something like y=mx+c, and then instead of finding the model you find new inputs m and c. Thus, we can instead say -

*You have the (MODEL, X) and Y but you dont have M,C (New inputs); This is optimization as well.

(M,C) -> (MODEL + X) -> Y
This means, that even if you dont know the input function, you have to assume some model and then estimate the parameters which when tuned, let the model behave as the close to the input function as possible.
Basically, what you need is machine learning. You have the inputs, you have the outputs (or you can get them but running your first function with a large sample of outputs), you have the cost function. Assume a model, and train it to approximate your input function.
If you are not sure what to use, then use a generalized function approximator AKA neural networks. But beware, it needs a lot more data to train.


text:
Q: When does lexical scoping binding take place - in runtime or compile time? C language take scope binding during compile time (variable reference get fixed address - doesn't change at all), that is example of static scoping.
Elisp language take scope binding during run time (variable point to top of own personal reference stack, let/defun/... special forms add to the top of stack on entry from top on the leave - in that time capture modified), that is example of dynamic scoping.
What type of binding used in lexical scoping?
Such language as Common Lisp, Python, R, JavaScript state that they implement lexical scoping.
What technics are used in implementation for that languages?
I hear about environments that carried with function appearance. If I right - when was environments created?
Is it possible or usual to construct and bind environment to function by developer manually? Some thing like call( bind_env(make_env({buf: [...], len: 5}), myfunc) )

A: In short, lexical scoping takes place at compile time (or more precisely, at the time when the function definition is evaluated). Also, lexical scoping can be static scoping: this is how ML-languages (SML, OCaml, Haskell) do it.
Environments
Every function is defined in some environment. Also, each function creates its own local environment nested in enclosing environment. Top level environment is where all usual variables, functions (+, -, sin, map, etc.) and syntax (relevant for languages that can extend syntax, like Common Lisp, Scheme, Clojure) are defined.
Each function creates its own local environment nested in enclosing environment (e.g., top level or of other function). Function arguments and all local variables live in this environment. If function reference a variable or a function that is not defined in the local environment (called free in this environment) it is found in enclosing environment of the function definition (or higher in enclosing env of enclosing environment if it is not found there and so on). This is different from dynamic scoping where the value would be found in the environment from where the function is called.
I am going to illustrate this using Scheme:
y is free in this definition
(define (foo x)
    (+ x y))

Here is y defined in top-level environment
(define y 1)

Introduce local 'y', but foo will use y from enclosing (top-level) environment of the definition. Hence, the result is 2 and not 11.
(let ((y 10))
     (foo 1))
 => 2

You can also define a function (or a procedure in Scheme's terms) with a local environment enclosing it:
 (define bar
     (let ((y 100))
          (lambda (x) (+ x y))))

(bar 1)
=> 101

Here procedure value bar is defined to be a procedure. Variable y is again free in the procedure body. But enclosing environment is created by let form in which y is defined to be 100. So, when bar is called, it is that value of y which is fetched and not top-level (in a dynamically scoped language it would have returned 2).
Answering your last question, it is possible to create your own environment manually, but it would be too much work and probably wouldn't be very efficient. When the language is implemented (for example, Scheme interpreter), that is exactly what the language developer is doing.
Good explanation of environments is shown in SICP, Chapter 3
Other comments
AFAIK, from Emacs 23, ELisp is using lexical scoping as well as dynamic scoping (similarly to Common Lisp, see below).
Common Lisp uses lexical scoping for local variables (introduced by let form) and dynamic scoping for global variables (they are also called special; it is possible to declare a local variable special, but it is rarely used) defined with defvar and defparameter. To distinguish them from lexically scoped variables, their names usually have "ear muffs", for example *standard-input*. Top-level functions are also special in CL, which can be rather dangerous: one can unknowingly alter behavior by shadowing top-level function. This why CL standard specifies the locks on standard library function to prevent their re-definition.
Scheme, in contrast, always uses lexical scoping. Dynamic scoping, however, is useful sometimes (Richard Stallman makes a good point on it). To overcome this, many Scheme implementations introduced so-called parameters (implemented using lexical scoping).
Languages like Common Lisp, Scheme, Clojure, Python keep a dynamic reference to a variable: you can construct the variable name from a string (intern a symbol in Lisp's terms) and find its value. More static languages, like C, OCaml or Haskell, cannot do that (unless some form of reflection is used). But this has a weak connection to what kind of scoping they use.


text:
Q: Moved ASP .Net Core 1.1 App to 2.0 Preview Upgraded to .Net Core 2.0 Preview 2 --> upgraded from 0 error to ~1000.
Basically the error says: "You must add a reference to assembly 'netstandard, Version=2.0.0.0". I click add reference and nothing changes. Re-install SDK, rebooted, etc. Nothing. Any suggestions?

A: Removing <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion> from .csproj file solved the problem. Before Microsoft.NETCore.App was blocked by project and did not allow update from 1.1 to 2.0.


text:
Q: Creating Orchard Module with aspx View Engine i have an existing MVC3 Application.
This application uses the Razor view engine AND the aspx Viewengine (for rendering telerik reports).
I want to integrate this MVC Application to Orchard (never used Orchard before).
My question is:
is this possible?
can orchard render views with a aspx viewengine?
thanks for your answers!

A: Orchard can render aspx, yes, but to make this application work inside of Orchard you'll have to transform it into an Orchard module. if those aspx reports are not MVC but use Webforms postbacks you probably won't be able to use them unless you isolate them into a separate application.
The question to ask would be why do you want to integrate this MVC app to Orchard?


text:
Q: Stuck ghost cleanup Looking for a little advice. This is all on 2008 R2 SP1.
I have a large table (around half a terabyte) that a ghost cleanup is holding locks on, more specifically exclusive locks on two pages, which I believe are then causing intent exclusive and intent shared on the table. It seemingly won't move away from these pages.
The table is in its own filegroup which contains four files. Data is added to the table each day, the only deletes are due to an archiving process. The archive has been run daily since easter, removing a small amount of data each day.
What seems to have caused this is one of the files in the filegroup has been moved to another disk using the usual take offline - modify the file details and bringing the db back online.
The cleanup process blocks other operations, including backup. DBCC commands like checkdb / checkalloc etc also get blocked.
I have a query running on sys.dm_db_index_physical_stats to investigate, this appears to be working, albeit slowly, activity monitor shows it having wait type PAGEIOLATCH_SH for a short period (a few milliseconds) for different page numbers on each refresh. This has been running for in excess of 3 hours.
I've attempted to disable ghost cleanup temporarily by switching on trace flag 661 globally - dbcc tracestatus reports status as 1.
Yet the ghost cleanup process persists, even after a restart of the server. sp_who2 shows that the CPU time is increasing, but the DiskIO is not. There is no significant disk access (~2mb/sec).
As I mentioned, the server is running R2 SP1 so the known issue with sql server taking 100% CPU (https://support.microsoft.com/en-us/help/978430/fix-the-ghost-cleanup-task-uses-100-of-the-cpu-on-an-idle-system-in-sql-server-2008-or-in-sql-server-2005) should not apply, in any case sql is only taking a steady 25% CPU.
It could be the issue listed here: https://support.microsoft.com/en-us/help/2622823/fix-ghost-record-count-values-keep-increasing-in-sql-server-2008-r2-or-in-sql-server-2008 but as I am yet to receive a result from the query in the symptoms section I can't confirm.
Is there anything else I can look at to diagnose further ?
Thanks.


text:
Q: ASP.NET web application - having problems with my database connectivity since switching fro mysql to access db I have created an ASP.NET web app for a university project and I had it all working as intended with full functionality using local mysql db. Due to reasons out of my control, I have been instructed to change the database to an access one. So I have done this, changed out the 'sql' statements for 'Oledb' ones and one half of my app works fine with the new changes, but I am having issues with the other half. I will add my connection string from my web.config page, followed by the issues i'm having. Can someone see where i'm going wrong?
  <add name="newregDBConnectionString"  connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Alex\Documents\Database1.accdb"
  providerName="System.Data.OleDb" />

I have two issues, the first is that I have a registration page, you fill out a form and the details are stored in the database. When I click submit to send the details to the DB, I get an error;

The second issue is that I have a gridview, which using a datasource, displays the people registered, but when I click the view button, I get the following error;

I added

"throw new
  Exception(ConfigurationManager.ConnectionStrings["newregDBConnectionString"].ConnectionString);"
  to my global.aspx page to see the error and it showed the following;

It makes it seem as though my connection string is incorrect in my web.config page but the other half of my app is working with database connectivity (my login page), so I can't see the problem. Apologies for the long post, I would greatly appreciate someone pointing out where i'm being stupid! Thanks in advance.
UPDATED:
protected void submitBtn_Click(object sender, EventArgs e)
    {
        OleDbConnection connect = new OleDbConnection(ConfigurationManager.ConnectionStrings["newregDBConnectionString"].ConnectionString);
        {
            if (parentRadBtn.Checked)
            {
                if (firstNameBox.Text == "" || surnameBox.Text == "" || postcodeBox.Text == "" || teleBox.Text == "" || emailBox.Text == "" || userBox.Text == "" || passwordBox.Text == "")
                {
                    Response.Write("<script>alert('Please ensure all fields have an entry');</script>");
                    successLabel.Text = ("");
                    userBox.Text = "";
                    firstNameBox.Text = "";
                    surnameBox.Text = "";
                    postcodeBox.Text = "";
                    teleBox.Text = "";
                    emailBox.Text = "";
                    passwordBox.Text = "";
                }
                else
                {
                    OleDbCommand pa = new OleDbCommand("INSERT INTO parent(parentID, firstname, surname, postcode, telephone, email, password) VALUES (@parentID, @firstname, @surname, @postcode, @telephone, @email, @password)", connect);
                    pa.Parameters.AddWithValue("@parentID", userBox.Text);
                    pa.Parameters.AddWithValue("@firstname", firstNameBox.Text);
                    pa.Parameters.AddWithValue("@surname", surnameBox.Text);
                    pa.Parameters.AddWithValue("@postcode", postcodeBox.Text);
                    pa.Parameters.AddWithValue("@telephone", teleBox.Text);
                    pa.Parameters.AddWithValue("@email", emailBox.Text);
                    pa.Parameters.AddWithValue("@password", passwordBox.Text);

                    connect.Open();
                    pa.ExecuteNonQuery();
                    connect.Close();
                }

                if (IsPostBack)
                {
                    userBox.Text = "";
                    firstNameBox.Text = "";
                    surnameBox.Text = "";
                    postcodeBox.Text = "";
                    teleBox.Text = "";
                    emailBox.Text = "";
                    passwordBox.Text = "";
                }

            }
            else if (childRadBtn.Checked)
            {
                if (firstNameBox.Text == "" || dayDobList.Text == "" || monthDobList.Text == "" || yearDobList.Text == "" || genderList.Text == "" || userBox.Text == "" || passwordBox.Text == "")
                {
                    Response.Write("<script>alert('Please ensure all fields have an entry');</script>");
                    successLabel.Text = ("");
                    userBox.Text = "";
                    firstNameBox.Text = "";
                    dayDobList.Text = "";
                    monthDobList.Text = "";
                    yearDobList.Text = "";
                    genderList.Text = "";
                    passwordBox.Text = "";
                }
                else
                {
                    OleDbParameter dob = new OleDbParameter("@dob", System.Data.SqlDbType.DateTime);
                    dob.Value = new DateTime(Int32.Parse(yearDobList.Text), Int32.Parse(monthDobList.Text), Int32.Parse(dayDobList.Text));

                    OleDbCommand ca = new OleDbCommand("INSERT INTO children(childID, firstname, dob, gender, password) VALUES (@childID, @firstname, @dob, @gender, @password)", connect);
                    ca.Parameters.AddWithValue("@childID", userBox.Text);
                    ca.Parameters.AddWithValue("@firstname", firstNameBox.Text);
                    ca.Parameters.Add(dob);
                    ca.Parameters.AddWithValue("@gender", genderList.Text);
                    ca.Parameters.AddWithValue("@password", passwordBox.Text);

                    connect.Open();
                    ca.ExecuteNonQuery();
                    connect.Close();
                }
                if (IsPostBack)
                {
                    userBox.Text = "";
                    firstNameBox.Text = "";
                    dayDobList.Text = "";
                    monthDobList.Text = "";
                    yearDobList.Text = "";
                    genderList.Text = "";
                    passwordBox.Text = "";
                }
            }
        }
    }

A: Look at this:
OleDbConnection connect = new OleDbConnection("newregDBConnectionString");

Notice that newregDBConnectionString is in quotes there? It looks like that's the name of a variable holding your connection string. By putting it in quotes, you're passing the text "newregDBConnectionString" as the connection string itself, instead of whatever string is inside that variable.
You need to get this connection string value from the configuration manager like you do in the second and third images.
Additionally, in the second image, you have this:
SqlDataSource source = new SqlDataSource();

This needs to be changed to OleDbDataSource.

A: your login page has this
  OleDbConnection connect = new OleDbConnection(ConfigurationManager.ConnectionStrings["newregDBConnectionString"].ConnectionString);

while your registration form page is I think you're just passing a string
make it the same as your login page


text:
Q: how do i use sscanf() method in C i use sscanf in this code
while(totalByte < sizeof(rdata))
{
    read(client_sockfd, &buffer[totalByte],1);
    printf("bytes[%d] : %x \n", totalByte, buffer[++totalByte]);
}

use this code and i got a result like this
client send 1 1 +
bytes[0] : 0
bytes[1] : 0
bytes[2] : 0
bytes[3] : 1
bytes[4] : 0
bytes[5] : 0
bytes[6] : 0
bytes[7] : 1
bytes[8] : 2b
bytes[9] : 0
bytes[10] : 0
bytes[11] : 0
bytes[12] : 0
bytes[13] : 0
bytes[14] : 0
bytes[15] : 0
bytes[16] : 0
bytes[17] : 0
bytes[18] : 0
bytes[19] : 0

got a result
then i use sscanf method
sscanf(buffer,"%d%d%c" ,&rdata.left_num, &rdata.right_num, rdata.op);
printf("%d %c %d \n", ntohl(rdata.left_num),rdata.op,ntohl(rdata.right_num));

but when print rdata(structure)'s value , get a 0 value(init value).
0 0
i know sscanf method split a string and insert a value
Is there a any misunderstood for me?
this is what i used structure
struct cal_data
{
    int left_num;
    int right_num;
    char op;
    int result;
    int error;
};

A: I don't think this is doing what you want it to:
printf("bytes[%d] : %x \n",totalByte, buffer[++totalByte]);

If that is working, then it's working by coincidence. You don't want to rely on coincidence, rather than logic, do you? Read this question for more information on the undefined behaviour here. Change it to this, and avoid omitting sequence points in order to cram logic together in the future:
printf("bytes[%d] : %x \n",totalByte, (unsigned int) buffer[totalByte]);
totalByte++;

then i use sscanf method
  sscanf(buffer,"%d%d%c" ,&rdata.left_num, &rdata.right_num, rdata.op);

Where is your error checking? Like most standard C functions, your code should be checking the return value of sscanf to ensure that it extracted the amount of information you want. How can you be sure sscanf successfully processed two decimal digit sequences and a character? Use this:
int n = sscanf(buffer,"%d%d%c" ,&rdata.left_num, &rdata.right_num, rdata.op);
if (n == 3) {
    /* sscanf extracted and assigned three values;
     * One for each of the format specifiers,
     * and variables you passed in. Success! */
    printf("%d %c %d \n", ntohl(rdata.left_num),rdata.op,ntohl(rdata.right_num));
}
else {
    /* sscanf failed to extract some values from the string,
     * because the string wasn't correctly formatted */
    puts("Invalid input to sscanf");
}

... and now you'll see the problem! sscanf failed!
As others have indicated, a string terminates at the first '\0' (or 0) byte. The pointer you're passing to sscanf points to an empty string. sscanf can't extract any of the information you want from an empty string.

A: sscanf like many other C library functions stops iterating a string when it reaches a 0 (same as '\0'). The first element of your bytes array is 0. Hence as far as sscanf is concerned, your input string used for sscanf is "". To see another example of this behaviour, add the following code after your while loop.
printf("%s\n", bytes);

This will not print anything (will print an empty string), because printf like sscanf will consider byte[0] to be the end of the string.
You should probably use something like this to read data into your structure - http://c-faq.com/stdio/extconform.html

A: According to function description (http://www.cplusplus.com/reference/cstdio/sscanf/):
int sscanf ( const char * s, const char * format, ...);

The first argument should be:

C string that the function processes as its source to retrieve the data.

But as you print out each byte as "hexadecimal integer":
printf("bytes[%d] : %x \n", totalByte, buffer[++totalByte]);

The value of the first byte is 0. So if you treat it as a string, it is an empty string.


text:
Q: Azure resize VM from A2/3 to DS2 v2 I'm trying to resize a couple of Azure VMs created some time ago from basic A3 and standard A3 to standard DS2v2.
I don't seem to have the ability to resize to that size of VM. It would be a bit of a pain to have to rebuild the servers from scratch.
If it makes any difference I am running CentOS in the VMs, each with a single disk with the apps and OS on it.
Can anyone advise me if it's possible to remove the VM without deleting the disks, create a new VM and then attach the disk to the new VM? I can't seem to find a way of doing it.
Thanks.....

A:
Can anyone advise me if it's possible to remove the VM without
  deleting the disks, create a new VM and then attach the disk to the
  new VM?

Which module are the VMs deploy in? (ARM or ASM)
If your VMs deploy in ASM(classic), we can delete your VM and select keep the attached disks, and copy the VHD to another storage account(premium), then use classic portal to create new VM with MY DISKS, after the VM created, select the data disk and attach it:

If your VMs deploy in ARM, we can delete your VM(just VM),keep the VHD,and copy the VHD to another storage account(premium) and use template to create new VMs with VHD. After VMs created, select data disk and attach it.
Here is the template, Create a VM from existing VHDs (OS + data disk) and connect it to an existing VNET.

Note:
We should copy the VHD to a premium storage account, then we can use the VHD to create a new VM.

A: Deleting the VM will not delete the disks. You can recreate the VMs using PowerShell/CLI or ARM template deployment. Here are the steps:
Migrating to Azure Premium Storage (Unmanaged Disks)
The reason you can't resize is that DS VMs utilizes a different hardware cluster because of SSD disk support. If you have no intention of using SSD disks, look for the same D-sized VM without the "S" and you won't need to redeploy. If you can't see regular D VMs, then your VM is running in a very old cluster and a redeploy is necessary no matter what.

A: VMs of "DS" category use premium storage, while VMs of "A" category use standard storage; you can't move those VMs between different categories, because they are physically stored in different and incompatible places.
You need to delete the existing VMs (which will not delete their disks), copy their disks to a premium storage account, and then create new VMs using the copied disks.


text:
Q: Which SCM to choose in this situation ? Redmine+git or Fossil or? We are a small computer science laboratory. We handle projects from very small (1 engineer) to average (10 engineers).
We need a version control tool, associated with a wiki and a bug-tracker.
We have very few time and resources to spend in our system administration, but we want to have the control over it.
Until now we used Redmine with SVN and it works well, except we can't access our SVN repo from outside the laboratory for security reasons, so we would like to use a distributed version control tool to be able to keep working outside the lab.
By searching about how to set up Redmine and Git, I have heard about the Fossil project that seems to answers all our needs (sources, wiki and bug-tracker under distributed control) and seems to be easier to configure and administrate than Redmine+Git.
So I would like to have some advice from people that have administrated or used both redmine+git and fossil.
Thank you.

A: Fossil is the exact SCM for you, as described in the question. It needs close to zero administration and have all features you described you need for the work.
It has additional bonuses as well:

*

*Very lightweight and need almost none of server resources (if at all - because it can work without a central server at all).

*Extremely robust storage of the sources. Nothing can ruin the database even the power fail during the write operations.

A: The short answer is Fossil... or whatever feels good to you :-).  The longer answer...
I've used both Redmine/Git and Fossil in commercial environments to manage projects internally.  I'm also using Fossil exclusively to manage my student projects in the university at which I teach.  Redmine, like many such products is OK, but it really is just a bit glue holding other disjoint projects together for you.  Managing it is NOT difficult, but you MUST manage it as a part of your ongoing process.  Fossil, on the other hand, requires virtually no management (at the server level) once you get it going.  To be clearer, when I administered Redmine, we had a regularly updated repository of scripts, configuration files, and other assets we used to administer our Redmine installation (all under Redmine control, of course).  When I started using Fossil, my experience guided me to create a similar project.  The difference is that instead of regularly updating this project as things changed (as I had with my Redmine admin repo), I have made only 5 commits to the equivalent Fossil project over the last two years, even though I update the Fossil executable itself with greater regularity.  Because Fossil is a single source/executable with all the features you mentioned integrated (not even "integrated" so much as "architecturally intimate"), my administration overhead has been effectively zero.
Also, I just LOVE using fossil from the command line in a way I never did with Git or Mercurial or Subversion (all of which are good tools).  From my perspective as an engineer, Fossil's focus appears to be on the things you will do approximately 99% of the time, and many other things (reasonable things, that is) are possible without difficulty.  That is a focus I greatly appreciate.
I should note I don't think Fossil is close to perfect, but it IS a great tool and has shifted my perspective on source code management, and that is a big deal to me.

A: If you guys have been using Redmine for some time, I don't really see any reason to change this. I would just stick with Redmine. Fossil is easy to setup and easy to work with, but so is Redmine. You can't access Redmine from home, can you? If you really can't access Redmine from home because of security reasons, then Fossil might be worth considering. Since I don't really know the context of your problems, I can't really say much more than recommend you to install Fossil :). It's pretty straightforward. Why don't you guys give it a try for a couple weeks and see if it works? You guys are gonna be the ones that can really evaluate whether it works well for you or not.
Sorry I can't say much more


text:
Q: How to link my Login screen to my Home screen SwiftUI I am stuck on linking my login screen to my Main screen. Both have been created separately and I have used the Button function to create the login button and it goes to another screen with the email I have logged in with but that's not what I want as I want my home screen to open up instead.
             Button(action: model.login) {
                     Text("LOGIN")
                    .fontWeight(.bold)
                    .foregroundColor(Color("Color1"))
                    .padding(.vertical)
                    .frame(width: UIScreen.main.bounds.width - 30)
                    .background(Color.white)
                    .clipShape(Capsule())
            }
            .padding(.top, 22)

My MainView code starting
     struct MainView: View {
     @State private var isShowing = false

     var body: some View {

     NavigationView {

     ZStack {

A: In your App struct add a State var isLoggedin passing it to the loginView and toggling it from there.
This is how I implemented.
struct TestApp: App {

    @State var isLoggedin: Bool = false

    var body: some Scene {

        WindowGroup {
            if isLoggedin {
                ContentView()
            } else {
                LoginView(isLoggedin: $isLoggedin)
            }
        }
    }
}

struct LoginView: View {

    @Binding var isLoggedin: Bool

    var body: some View {

        Button(action: {
            isLoggedin = true
        }, label: {
            Text("Login")
        })
    }
}

This way you can pick which view to show. ContentView to LoginView.


text:
Q: UIViewPropertyAnimator repeat not working I am using UIViewPropertyAnimator to animate fade in and fade out. Passing repeat option won't repeat the animation and work for only one second.
Am I doing anything wrong?
Code With Issue:
private func faceFadeAnimator() {
            faceAnimator = UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 1, delay: 0, options: [.curveLinear, .repeat], animations: {
                self.animatorImageView.alpha = self.animatorImageView.alpha == 1 ? 0 : 1
            }, completion: { (position) in
            })
        }

WORKAROUND:
private func faceFadeAnimator() {
        faceAnimator = UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 1, delay: 0, options: [.curveLinear], animations: {
            UIView.setAnimationRepeatCount(1000)
            self.animatorImageView.alpha = self.animatorImageView.alpha == 1 ? 0 : 1
        }, completion: { (position) in
        })
    }

A: This repeat bug has been around for years. Looking at the state of UI frameworks, they will probably continue to overlook this.
These will NOT work: repeat option and setAnimationRepeatCount() (also deprecated)
A workaround solution is to fallback using Timer to repeatedly start the animation.


text:
Q: image_number error in matlab loop can anyone help me? I have a loop as follows:
global im2
axes(handles.axes4);

for i= 1:40

cd(strcat('C:\Users\JerryFarla\Desktop\images test\yale faces\ImageZ\',num2str(i)));
c = imread('1 (1).jpg');

%subplot(222)
axes(handles.axes4)
imshow(c);

set(handles.image_number,'String',strcat('Processed now --->',num2str(i)))

end
img=imread('C:\Users\JerryFarla\Desktop\images test\yale faces\ImageZ\1 (*).jpg');
a=img;
axes(handles.axes5)
imshow(img)

my issue is that it gives  me the error

??? Reference to non-existent field 'image_number'.
Error in ==> testgui1>pushbutton2_Callback at 270
      set(handles.image_number,'String',strcat('Processed now --->',num2str(i)))

Is the error due to my version of matlab (i'm using the R2011a version)?
If yes, is there any function with the same purpose in this version of matlab?

A: Your GUI need to have a uicontrol or a member of name "image_number". You probably don't have this control as part of GUI.
If your intention is to create a control named "image_number" dynamically, use function "uicontrol" to do so.
The issue is not due to MATLAB version R2011A.


text:
Q: Size of file which we get through AssetManager function getAssets in Android AssetManager mngr = getAssets();
test_file = mngr.open("sample.txt");

above test_file variable is of InputStream type. Any way to calculate the file size of sample.txt from it?

A: I have an alternative to get size of a file in assets using AssetFileDescriptor:
AssetFileDescriptor fd = getAssets().openFd("test.png");
Long size = fd.getLength();

Hope it helps.

A: test_file.available();

Is not a very reliable method to get the file length as is stated in the docs.
size = fd.getLength();

Using the FileDescriptor as shown by Ayublin is!
His answer should be promoted to the correct answer.

A: inputStream.available() might match the file size if the file is very small, but for larger files it isn't expected to match.
For a compressed asset, the only way to get the size reliably is to copy it to the filesystem, ex: context.getCacheDir() then read the length of the file from there. Here's some sample code that does this. It probably then also makes sense to use the file from the cache dir as opposed to the assets after this.
String filename = "sample.txt";
InputStream in = context.getAssets().open(filename);
File outFile = new File(context.getCacheDir(), filename);
OutputStream out = new FileOutputStream(outFile);

try {
    int len;
    byte[] buff = new byte[1024];
    while ((len = in.read(buff)) > 0) {
        out.write(buff, 0, len);
    }
} finally {
    // close in & out
}
long theRealFileSizeInBytes = outFile.length();

You should also delete the file from the cache dir when you are done with it (and the entire cache dir will also be deleted automatically when uninstalling the app).


text:
Q: How can I create build and deployment automation package which can include PowerApp, MS Flow and SharePoint list? We have created a application on PowerApp and Microsoft flow by using the SharePoint list and, want to build and deployment automation package as specified in the link for Dynamics CRM:
https://devkeydet.blog/2018/04/10/build-and-deployment-automation-of-a-model-driven-powerapp-using-vsts/comment-page-1/?unapproved=55&moderation-hash=45c2ce1b950351e67c315e1abf1a6877#comment-55


text:
Q: Calculate median of aggregated values for a category using pivot table I have hourly data about sales $ of certain categories (Fruits, snacks etc). I'd like to display the median of daily sales values over a month or an year using the hourly data in the table. So, for each category it needs to sum the hourly values and create a daily value first and then calculate the median
regular pivot does not provide median function. I am familiar with Power pivots but have not used Measures. i tried to create a measure using medianX function, but could not make it work

A: Ali,
When you create your measure you will want to use the MEDIAN funciton not MEDIANX
The MedianX would be if you were trying to calculate the median value for a column in your table that did not already exist.
For Example, lets say we have Table1 which has two columns Net Revenue and Net Expense. And the following 3 data points exist for each row in the column.
Net Revenue:
Jan-2019 100
Feb-2019 300
Mar-2019 300
Net Expense:
Jan-2019 50
Feb-2019 100
Mar-2019 50
Since we do not have a Net Profit column in the table we could use MEDIANX to specify the table we would like to use then write our expression for the column that doensn't exist. In the example above it would go =MEDIANX(Table1, [Net Revenue] - [Net Expense]. This would create a median measure for NetProfit even though the column itself doesn't exist in our table.
In your case, since you are aggregating a column that already exists you can just stick with =MEDIAN.
If you need more clarification let me know!
Best,
Brett

A: First, you will need to add a Calendar table to your data model:
Calendar Table Explained
The Calendar table must have fields you want to group your sales by, such as "Year-Month" and "Year-Quarter".
Then, connect the Calendar table to your Sales table via date fields, to get a structure like this:

With this data model in place, create 2 measures ( I will assume your sales table is called "Sales", and calendar table is called "Date"):
Measure 1:
Total Sale = SUM(Sales[Amount])

It will simply calculate sum of sale amounts.
Measure 2:
Median Monthly Sale = MEDIANX( VALUES(Date[Year-Month]), [Total Sale])

This measure will first sum up sales by Year-Month, and then calculate the median of the sums.
To get median sales by a different period, just replace Year-Month with the desired grouping level, for example:
Median Yearly Sale = MEDIANX( VALUES(Date[Year]), [Total Sale])


text:
Q: Adding a polynomial term to a linear model My model is
lm(formula = medv ~ crim + indus + rm + dis + crim * indus)
I have to add the polynomial term rm*rm of order 2 to the above model. How do we do this in R?

A: Here's two options.
lm(formula = medv ~ crim + indus + poly(rm, 2, raw = TRUE) + dis + crim * indus)
lm(formula = medv ~ crim + indus + rm + dis + crim * indus + I(rm^2))

The first uses poly(..., raw = TRUE) where raw = TRUE ensures the coefficients can be intepreted as usual. The latter uses the as is operator I(...) which evaluates whats within it before using it in a the formula context. Note that x^2 isn't translated into the normal polynomial in R within a formula context.


text:
Q: sorting a file? I need to read a existing file that i wrote using a empty list for users raw_input. Not exactly sure on how I sort the file after reading. After sorting, i need to save it under a different file name and print.
This is what I have so far:
Names=[]

while 1:

    Input = raw_input("Enter a name or press 'v' to quit:")
    if Input == "v":
        break
    Names.append(Input)

raw_input ('Press Enter to write each of the names to a file named NAMES.')
text_file= open ("NAMES.txt", "w")
text_file.writelines(Names)
text_file.close()

raw_input('Press Enter to Read file into a sorted list.')

text_file = open("NAMES.txt", "r")
names = text_file.readlines()
text_file.close()

^This is where I need to sort and save under different file name and print. STUCK!

A: you can just sort the list of names .... names.sort()
>>> names=["John","Angel","Luis"]
>>> names.sort()
>>> names
['Angel', 'John', 'Luis']

Edit: comment answer
writelines doesn't add line separators therefore
when you do text_file.writelines(Names) you are writing just one line.
To write line separators you can do ...
text_file.writelines(map(lambda x: x+'\n',Names))
or simply append \n at the end of each name ...
Names.append(Input+'\n')

A: names.sort()

http://wiki.python.org/moin/HowTo/Sorting/

A: This is probably homework, so i'll give you some hints.
You should take a look at the python docs for sorting.
Using the .sort() method for a list will alter the list and give no return value.
>>> a = ['2','1']
>>> a
['2', '1']
>>> a.sort()
>>> a
['1', '2']

Using sorted() on a list, will return the list sorted, and not alter the original list:
>>> a = ['2','1']
>>> sorted(a)
['1', '2']
>>> a
['2', '1']
>>>

As far as reading in the file that you wrote, you probably want to strip the endline characters:
names = [ line.strip() for line in text_file.readlines() ]

Sort the list of names using either of the methods above, and then write to a new file.
Based on this comment:

yes, but when i try to sort it comes
  back the same. Here, if I input
  a,c,d,b in the raw_input it comes back
  as ['acdb']

The reason why you are unable to read the names back correctly is because you are using writelines.

file.writelines(sequence)
Write a sequence of strings to the file. The sequence can be any iterable
  object producing strings, typically a
  list of strings. There is no return
  value. (The name is intended to match
  readlines(); writelines() does not add
  line separators.)

You could either write the lines to your file as you ask for them:
text_file= open ("NAMES.txt", "w")

while True:
    Input = raw_input("Enter a name or press 'v' to quit:")
    if Input == "v":
        break
    text_file.write(Input)

text_file.close()

or you could append an endline character to your inputs:
Names.append(Input+"\n")

Since you aren't using the Names list anyways the first option allows you to forgo creating an unnecessary variable.


text:
Q: Escaping characters on Twig's localized date filter When using the default date filter, we can escape characters by using \\ in front of each character.
The same does not seem to apply when using the localizeddate filter (example).
Anyone knows a way of escaping characters when using the Intl filter?

A: Accoring to official ICU docs, you can escape any letter using single-quote (').
Example format:
hh 'o''clock' a, zzzz

should produce:
12 o'clock PM, Pacific Daylight Time

Notice the 'o''clock' which does not get tokenized...
Hope this helps.

A: Simply use the format argument. In the last parameter you can escape text with '. '' will produce a real '.
{{ date|localizeddate('short', 'none', locale, null, 'd/m/y HH:mm') }}


text:
Q: Making Line ActionScript using lineTo I'm extremely new to flash programming, and suddenly my teacher give me assignment to make a flash about mirror reflection line.
Here is my as code to draw a simple line after following some tutorial online.
_root.createEmptyMovieClip("holder",1);
holder.clear();
holder.lineStyle(1,0,100);
holder.moveTo(benda._x, benda._y);
holder.lineTo(289.95, 199.9);

Now i got a problem, "benda" is a motion tween object, when i test it, the as created line don't move, but "benda" move. what should i do to make it move ?
Thanks, sorry for my bad english

A: zeulb,
It's not entirely clear what you're trying to do, or how much you already know about drawing in Flash.
But, here's a breakdown of what your current code is doing...
_root.createEmptyMovieClip("holder",1);

This line will create a new movie clip named "holder" in your movie, at level 1.
holder.clear();

This line will clear the "drawing surface" in your "holder" movie clip. However, since you've JUST created "holder", it's already empty/clear. So, this line technically isn't necessary, and won't do anything.
holder.lineStyle(1,0,100);

This line sets the drawing style in your "holder" movie clip. The first parameter is the thickness of the line (1 pixel). The second parameter is the color ("0" = black). The third parameter is the alpha (transparency) of the line ("100" = fully opaque). So - long story short - the style is a 1-pixel thick black line.
holder.moveTo(benda._x, benda._y);

This line tells Flash to "move" the invisible starting point of your drawing to these coordinates:
    x: the current X coordinate of "benda" (whatever that is...)
    y: the current Y coordinate of "benda"
In other words - from the snippet of code you posted, it's not possible to tell what "benda" is. But, I'm guessing it's another movie clip you created elsewhere. So - long story short - you're telling Flash to begin a line in your "holder" movie clip that starts at the same coordinates as "benda".
holder.lineTo(289.95, 199.9);

This line of code says, "from the starting point you just set with the previous "moveTo" command, draw a line to "289.95,199.9".
So - ultimately, your code will create a movie clip named "holder", then in that clip's drawing surface, draw a line from (benda._x, benda._y) to (289.95, 199.9).
With a little more clarification, I'd be happy to help you with whatever you're trying to do.


text:
Q: Why does bash clear OLDPWD when a child script is started? OLDPWD is exported and passed to any children, but bash apparently clears OLDPWD whenever a child script is started:
$ cd /etc
$ cd
$ perl -e 'print "<$ENV{OLDPWD}>\n"'
</etc>
$ ksh  -c 'echo "<$OLDPWD>"'
</etc>
$ bash -c 'echo "<$OLDPWD>"'
<>

Any way to work around that other than creating an alias or dotting the child script or exporting some other variable with the same value, whenever I want to use $OLDPWD in a child script?
** UPDATE 2015/11/26 **
I filed a bash bug report and got this reply from Chet Ramey, the bash maintainer:

Why does bash clear OLDPWD when a child script is started?

Because a new shell does not have a `previous working directory'.
It's supposed to be set by cd, and if you haven't executed cd, you
don't have one.
It seems reasonable to inherit OLDPWD if it names a directory, in
the same way that the shell inherits PWD if it names the current
directory, so we'll try that for the next bash version.

A: Probably this is leftover behavior from long ago when bash first implemented OLDPWD.  The release notes for bash 2.03 alpha (in 1999) indicate that OLDPWD was previously not an exported variable.  If it was not exported, it would not be inherited by a child process.
Judging by the comment on this chunk from bash's source, the behavior is intentional:

  /* According to the Single Unix Specification, v2, $OLDPWD is an
     `environment variable' and therefore should be auto-exported.
     Make a dummy invisible variable for OLDPWD, and mark it as exported. */
  temp_var = bind_variable ("OLDPWD", (char *)NULL, 0);
  VSETATTR (temp_var, (att_exported | att_invisible));

Though the release note indicates that making it exported was done to follow POSIX.2, OLDPWD does not appear in the list of shell variables for POSIX shell.  It does appear in the description of cd.  That does not mention if an initial value should be obtained from a parent process; there is no specific behavior which is required.
It does not appear to be a documented feature of bash; there are few comments to be found:

*

*Loss of OLDPWD in Erlang on MacOSX

*... 'OLDPWD not set' ..., pointing out that initially the child shell has no prior cd command to set $OLDPWD.


text:
Q: Missing two of the black "feet" at the bottom of my Macbook Pro/Started making a clicking noise inside I noticed a clicking noise comming from the underneath the keys around the number 5, 6 and 7 (make a circle with your thumb and pointer finger around those numbers, and thats where the sound is comming from). It mainly does it when I tilt the MBP back and forth or left and right. I turned the computer over and noticed the black foot on the front (nearest the spacebar, not the screen) left side was gone. The one on right has been missing for a while but it has a black "stick" in the center where the hole is.. But the one that I noticed is missing today doesn't have that "stick" in the hole and I can see right into the computer. I have put black duct tape over it to prevent any dirt or anything from getting in there. The noise has actually stopped, unless I tilt it forward nearly upside down..
1.) Does someone has any suggestions on what I can do to fix this myself?
2.) Is this harmful to the MBP?
3.) Is it okay that I put the duct tape on the "feet" holes tempararily?
4.) Should I try taking the bottom panel off my MBP and see if that little black stick fell inside?
P.S. - Please don't suggest going to an Apple store or Genius Bar because I'm in Laos (South East Asia) and there is none of which anywhere near me. It will be 20 days before I get somewhere that has an Apple store. Do you think the computer should be okay until then?
-Macbook Pro 13" 2009, Mac OS X Lion 10.7.5.

A: The feet help air to get under your Mac and cool it, which is essential because heat destroys just about everything a computer needs to keep working, like the processor or hard drive. The clicking noise is probably your internal harddrive beginning to fail. You should back up your data immediately and prepare to replace your hard drive, as clicking is often a good indicator that the drive is about to stop working. You can check the drive's SMART status using Disk Utility.app, but it may not report anything amiss until its too late.
You can find detailed instructions on checking the drive's SMART status here, but the meat of it is accomplished just by stealing their image, which I'll link to below.

A: 1) The region you are referring to is exactly where the fan is located. This may be what is causing the noise, although it could potentially be the optical drive as well. You can find an extensive DIY guide, along with the needed components, at iFixit. See below:

2) You will void any warranty you have with Apple, whether it be Apple's one year limited warranty or its extended warranty (Apple Care). Additionally, Apple may refuse to service it in the event that you fail to fix the problem.
3) Yes.
4) If you are okay with (2), and are able to carefully follow the guide linked to in (1), then yes. It's very possible that either the fan is damaged or there is some small component stuck in its vicinity, rattling around. It's also possible the optical drive is damaged and would require replacement. I wouldn't advise this if you were in any warranty window, but you aren't. Make sure to have the proper screwdriver if you decide to do so.
Best of luck


text:
Q: Flask user image input Stuck on user image input, everything works except picture, but I don't understand how to create picture object for flask_sqlalchemy, all the time shows me error.
The idea is that user input all data and image and information will be available on home screen.
    class Product(db.Model):
        id = db.Column(db.Integer, primary_key=True)  # auto +1
        title = db.Column(db.String(20), nullable=False)
        price = db.Column(db.Integer, nullable=False)
        description = db.Column(db.Text)
        status = db.Column(db.Boolean, default=True)
        picture =???

And:

@app.route('/add_product', methods=['POST', 'GET'])
def create():
    if request.method == 'POST':
        title = request.form['title']
        price = request.form['price']
        description = request.form['description']
        image = ?????

        product = Product(title=title, price=price, description=description)
        try:
            db.session.add(product)
            db.session.commit()
            return redirect('/')
        except:
            return 'Error'

A: Your image should go somewhere on the filesystem, not the database. You can put it into your flask static directory and store path to it in the database. Your picture column will then become:
picture = db.Column(db.String(254), nullable=True)

And then you accept the image with something like this:
    if request.method == 'POST':
        title = request.form['title']
        price = request.form['price']
        description = request.form['description']

        # accept uploaded image
        uploaded = request.files.get('image')
        if uploaded and uploaded.filename:
            filename = secure_filename(uploaded.filename)
            uploaded_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            uploaded.save(path)
            image = uploaded_path

There are more examples in Flask docs: Uploading Files


text:
Q: Error compile "no match for operator=="
Possible Duplicate:
no matching function error using template template parameters in a function

Good mornig I don't understand because I obtain compile error by implementing as global function the operator== (in class myList::iterator)
If I realize the operator== as member function the code compile.
The error is
error: no match for operator== in it == it1
note: candidate is:
note: tempalte<class T> bool operator==(const typename myList<T>::iterator&,const typename myList<T>::iterator&)

The code is:
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <typeinfo>

template <class T>
class myList;

template <class T>
bool operator==(const typename myList<T>::iterator& lhs,const typename myList<T>::iterator& rhs);
template <class T>
bool operator!=(const typename myList<T>::iterator& lhs,const typename myList<T>::iterator& rhs);

template <class T>
class myList
{
private:
  class myInfo;
public:
  //CTR DEFAULT
  myList():_pInfo(NULL)
  {}
  myList(T value):_pInfo(new myInfo(value))
  {}
  //  class iterator;
  //  friend class iterator;
  class iterator{
  public:
    //creo gli iteratori
    iterator():_pMyInfoIt(NULL)
    {}
    iterator(myInfo* p):_pMyInfoIt(p)
    {}
    iterator(const iterator& it):_pMyInfoIt(it._pMyInfoIt)
    {}
    iterator& operator=(const iterator& it)
    {
      _pMyInfoIt = it._pMyInfoIt;
      return *this;
    }
    //creo funzioni che lavorano sugli iteratori
    /*
    bool operator==(const iterator& rhs)
    {
      return _pMyInfoIt == rhs._pMyInfoIt;

    }
    */
    friend bool operator== <T>(const typename myList::iterator& lhs,const typename myList::iterator& rhs);
    friend bool operator!= <T>(const typename myList<T>::iterator& lhs,const typename myList<T>::iterator& rhs);
  private:
    myInfo* _pMyInfoIt;
  };

  myList::iterator begin()
  {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
    return iterator(_pInfo);
  }

private:
  class myInfo
  {
  public:
    myInfo(const T& data):_data(data),_pMyInfo(NULL)
    {}
  private:
    T _data;
    myInfo* _pMyInfo;
  };
  myInfo* _pInfo;
};

template <class T>
bool operator==(const typename myList<T>::iterator& lhs,const typename myList<T>::iterator& rhs)
{
  std::cout << __PRETTY_FUNCTION__ << std::endl;
  return lhs._pMyInfoIt == rhs._pMyInfoIt;
}

template <class T>
bool operator!=(const typename myList<T>::iterator& lhs,const typename myList<T>::iterator& rhs)
{
  return !(lhs == rhs);
}

int main(int argc,char** argv){
  myList<int> test;
  myList<int>::iterator it = test.begin();
  myList<int>::iterator it1 = test.begin();
  std::cout << typeid(it1).name() << std::endl;
  if(it == it1)
    std::cout << "EQUAL" << std::endl;
  return EXIT_SUCCESS;
}

thanks in advance

A: Compiler can not deduce T.  Change to:
template <class IT, class=typename IT::iterator_category>
bool operator==(const IT& lhs, const IT& rhs)

2nd template parameter does simple SFINAE, so that only iterators will match.

A: Define the friend functions within the class body:
friend bool operator== <>(const typename myList<T>::iterator& lhs, const typename myList<T>::iterator& rhs)
{
    std::cout << __LINE__ << std::endl;
    return lhs._pMyInfoIt == rhs._pMyInfoIt;
}
friend bool operator!= <>(const typename myList<T>::iterator& lhs, const typename myList<T>::iterator& rhs)
{
    return !(lhs == rhs);
}

It should work.

A: As pimanych says, declare the body of the friend function inside the class body:
    friend bool operator==(const iterator& lhs, const iterator& rhs)
    {
        return lhs._pMyInfoIt == rhs._pMyInfoIt;
    }
    friend bool operator!=(const iterator& lhs, const iterator& rhs)
    {
        return !(lhs == rhs);
    }

Note that these aren't really template functions, but are only declared when myList<T> (and myList<T>::iterator) is instantiated. You can check by attempting to compare a myList<int>::iterator and myList<float>::iterator - you should get a compiler error.
Look up the Barton-Nackman trick for more details.


text:
Q: Using regex for "W o.R-d".replaceAll("word", "replacement") My objective is to have a censoring. Currently atm I use message.replaceAll("(?i)word", "replacement") but this only catches the words which are not split up.
To bypass this people simply add a different character between the censored word.
So I want to have "Anyone else want to Y.O.L.O" turned into "Anyone else want to party" while just looking for 'yolo'. Keeping the '.' in there would be a bonus.

A: How about: (to replace "word" with "replacement")
msg.replaceAll("(?i)([^A-Za-z])w[^A-Za-z]?o[^A-Za-z]?r[^A-Za-z]?d([^A-Za-z])",
               "$1replacement$2") );

[^A-Za-z] is not a letter
[^A-Za-z]? is not a letter (optional)
$1 is the first thing in brackets (first ([^A-Za-z]))
$2 is the first thing in brackets (last ([^A-Za-z]))
An alternative is look-around:
msg.replaceAll("(?i)(?<=[^A-Za-z])w[^A-Za-z]?o[^A-Za-z]?r[^A-Za-z]?d(?=[^A-Za-z])",
               "replacement") );

It would not be difficult to generate the above automatically given a word.
Now that it's posted on the internet, everyone can see it and change their spamming to not get picked up by the above.
Reference.
EDIT: I removed \\b (word boundary) since 1word2 will get skipped.


text:
Q: How to insert NaN array into a numpy 2D array I'm trying to insert an arbitrary number of rows of NaN values within a 2D array at specific places. I'm logging some data from a microcontroller in a .csv file and parsing with python.
The data is stored in a 3 column 2D array like this
[(122.0, 1.0, -47.0) (123.0, 1.0, -47.0) (125.0, 1.0, -44.0) ...,
(39.0, 1.0, -47.0) (40.0, 1.0, -45.0) (41.0, 1.0, -47.0)]

The first column is an sequence counter. What I'm trying to do is iterate through the sequence values, diff current and previous sequence number  and insert as many rows with nan as there are missing sequences.
Basically,
[(122.0, 1.0, -47.0) (123.0, 1.0, -47.0) (125.0, 1.0, -44.0)]

would become
[(122.0, 1.0, -47.0) (123.0, 1.0, -47.0) (nan, nan, nan) (125.0, 1.0, -44.0)]

However the following implementation of np.insert produces an error
while (i < len(list[1])):
     pid = list[i][0]
     newMissing = (pid - LastGoodId + 255) % 256
     TotalMissing = TotalMissing + newMissing
     np.insert(list,i,np.zeros(newMissing,1) + np.nan)
     i = i + newMissing
     list[i][0] = TotalMissing
     LastGoodId = pid

---> 28                 np.insert(list,i,np.zeros(newMissing,1) + np.nan)
       29                 i = i + newMissing
       30                 list[i][0] = TotalMissing
TypeError: data type not understood

Any ideas on how I can accomplish this?

A: From the doc of np.insert():
import numpy as np
a = np.arrray([(122.0, 1.0, -47.0), (123.0, 1.0, -47.0), (125.0, 1.0, -44.0)]))
np.insert(a, 2, np.nan, axis=0)
array([[ 122.,    1.,  -47.],
       [ 123.,    1.,  -47.],
       [  nan,   nan,   nan],
       [ 125.,    1.,  -44.]])

A: Approach #1
We can use an initialization based approach to handle multiple gaps and gaps of any lengths -
# Pre-processing step to create monotonically increasing array for first col
id_arr = np.zeros(arr.shape[0])
id_arr[np.flatnonzero(np.diff(arr[:,0])<0)+1] = 256
a0 = id_arr.cumsum() + arr[:,0]

range_arr = np.arange(a0[0],a0[-1]+1)
out = np.full((range_arr.shape[0],arr.shape[1]),np.nan)
out[np.in1d(range_arr,a0)] = arr

Sample run -
In [233]: arr      # Input array
Out[233]:
array([[ 122.,    1.,  -47.],
       [ 123.,    1.,  -47.],
       [ 126.,    1.,  -44.],
       [  39.,    1.,  -47.],
       [  40.,    1.,  -45.],
       [  41.,    1.,  -47.]])

In [234]: out
Out[234]:
array([[ 122.,    1.,  -47.],
       [ 123.,    1.,  -47.],
       [  nan,   nan,   nan],
       [  nan,   nan,   nan],
       [ 126.,    1.,  -44.],
       [  nan,   nan,   nan], (168 NaN rows)
       .....
       [  nan,   nan,   nan],
       [  nan,   nan,   nan],
       [  39.,    1.,  -47.],
       [  40.,    1.,  -45.],
       [  41.,    1.,  -47.]])

Approach #2
An alternative approach could be suggested to handle such generic cases using np.insert instead of initialization, like so -
idx = np.flatnonzero(~np.in1d(range_arr,a0))
out = np.insert(arr,idx - np.arange(idx.size),np.nan,axis=0)


text:
Q: How to pass navigator.pop to custom react native component I would like to extract my navigation menu into a custom component so I don't have to keep rewriting the code. Here is my simple dashboard.js
import React, { Component } from 'react';
import {
   StyleSheet,
   View,
   Text,
   Navigator,
  TouchableHighlight,
  TouchableOpacity,
} from 'react-native';

let HeaderMenu = require('../../partials/headerMenu');

class Dashboard extends Component {
  render() {
    return (
      <HeaderMenu/>
   );
  }
}
module.exports = Dashboard;

Here is my headerMenu.js
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Navigator
} from 'react-native';

class HeaderMenu extends Component {
  render() {
    return (
        <View>
        <Text>Header Menu</Text>
         <TouchableOpacity onPress={()=>{this.props.navigator.pop()}}>
         <Text>BACK</Text>
         </TouchableOpacity>
     </View>
    );
  }
}

module.exports = HeaderMenu;

My question is how can I pass:
   this.props.navigator.pop()

from my dashboard.js file to my headerMenu.js file so the back button works?

A: You can pass in the Navigator object from dashboard.js into headerMenu.js:
<HeaderMenu navigator={your_navigator_object}/>

Then calling this.props.navigator.pop() in headerMenu.js should work.


text:
Q: How can I use settings with reloadOnChange and LoggingLevelSwitch in Serilog Using Serilog and Serilog.Settings.Configuration in .NET Core 2, I'd like to do something like the following. Is it possible?
appsettings.json
{
  "Serilog": {
    "MinimumLevel": {
      "ControlledBy": {
        "Serilog.Core.LoggingLevelSwitch": "Debug"
      }
    }
  }
}

program.cs
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", reloadOnChange: true)
    //...
    .Build();

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    //...
    .CreateLogger();

My intent is to modify the config file and have the log level change without restarting the application.

A: This works straight out of the box with the normal "MinimumLevel": "Debug" syntax.


text:
Q: Software to organize library? Im looking for a program that let me organize my itunes library (So that the CD's that I export instead of saving it like "Track 1",etc, be saved with all the sing info, such as artist, album, etc).
How to mass-organize iTunes library?
I taked a look into that question but Im looking for something more complete, It does not matter if it cotst.
Thanks.

A: I think Jaikoz might be a good choice for you. This article also has a pretty detailed list of other options: http://lifehacker.com/the-best-apps-for-automatically-cleaning-up-your-music-1561265062


text:
Q: check for duplicates in a python list I've seen a lot of variations of this question from things as simple as remove duplicates to finding and listing duplicates.  Even trying to take bits and pieces of these examples does not get me my result.
My question is how am I able to check if my list has a duplicate entry?  Even better, does my list have a non-zero duplicate?
I've had a few ideas -
#empty list
myList = [None] * 9

#all the elements in this list are None

#fill part of the list with some values
myList[0] = 1
myList[3] = 2
myList[4] = 2
myList[5] = 4
myList[7] = 3

#coming from C, I attempt to use a nested for loop
j = 0
k = 0
for j in range(len(myList)):
    for k in range(len(myList)):
        if myList[j] == myList[k]:
            print "found a duplicate!"
            return

If this worked, it would find the duplicate (None) in the list.  Is there a way to ignore the None or 0 case? I do not care if two elements are 0.
Another solution I thought of was turn the list into a set and compare the lengths of the set and list to determine if there is a duplicate but when running set(myList) it not only removes duplicates, it orders it as well.  I could have separate copies, but it seems redundant.

A: Try changing the actual comparison line to this:
if myList[j] == myList[k] and not myList[j] in [None, 0]:

A: I'm not certain if you are trying to ascertain whether or a duplicate exists, or identify the items that are duplicated (if any).  Here is a Counter-based solution for the latter:
# Python 2.7
from collections import Counter

#
# Rest of your code
#

counter = Counter(myList)
dupes = [key for (key, value) in counter.iteritems() if value > 1 and key]
print dupes

The Counter object will automatically count occurances for each item in your iterable list.  The list comprehension that builds dupes essentially filters out all items appearing only once, and also upon items whose boolean evaluation are False (this would filter out both 0 and None).
If your purpose is only to identify that duplication has taken place (without enumerating which items were duplicated), you could use the same method and test dupes:
if dupes:  print "Something in the list is duplicated"

A: If you simply want to check if it contains duplicates. Once the function finds an element that occurs more than once, it returns as a duplicate.
my_list = [1, 2, 2, 3, 4]

def check_list(arg):
    for i in arg:
        if arg.count(i) > 1:
            return 'Duplicate'

print check_list(my_list) == 'Duplicate' # prints True

A: To remove dups and keep order ignoring 0 and None, if you have other falsey values that you want to keep  you will need to specify is not None and not 0:
print [ele for ind, ele in enumerate(lst[:-1]) if ele not in lst[:ind] or not ele]

If you just want the first dup:
for ind, ele in enumerate(lst[:-1]):
    if ele in lst[ind+1:] and ele:
        print(ele)
        break

Or store seen in a set:
seen = set()
for  ele in lst:
    if ele in seen:
        print(ele)
        break
    if ele:
        seen.add(ele)

A: In my opinion, this is the simplest solution I could come up with. this should work with any list. The only downside is that it does not count the number of duplicates, but instead just returns True or False
for k, j in mylist:
    return k == j

A: You can use collections.defaultdict and specify a condition, such as non-zero / Truthy, and specify a threshold. If the count for a particular value exceeds the threshold, the function will return that value. If no such value exists, the function returns False.
from collections import defaultdict

def check_duplicates(it, condition, thresh):
    dd = defaultdict(int)
    for value in it:
        dd[value] += 1
        if condition(value) and dd[value] > thresh:
            return value
    return False

L = [1, None, None, 2, 2, 4, None, 3, None]

res = check_duplicates(L, condition=bool, thresh=1)  # 2

Note in the above example the function bool will not consider 0 or None for threshold breaches. You could also use, for example, lambda x: x != 1 to exclude values equal to 1.

A: Here's a bit of code that will show you how to remove None and 0 from the sets.
l1 = [0, 1, 1, 2, 4, 7, None, None]

l2 = set(l1)
l2.remove(None)
l2.remove(0)


text:
Q: Hacklang unexpected interface error I am learning hacklang and having issues with using interface in different files.
Here is my code.
IpAuthorizedController.php
<?hh
namespace App\Controller\Interface;

interface IpAuthorizedController {

}

HomeController.php
<?hh
namespace App\controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Controller\Interface\IpAuthorizedController;

class HomeController extends Controller
{
  /**
   * @Route("/", name="index")
   *
   */
  public function index()
  {
    die(var_dump(return $this->render('index.html.twig')));
  }
}

Error message
FatalThrowableError

syntax error, unexpected T_INTERFACE, expecting '{'
in HomeController.hh (line 5)

I am new to this language so any help is much appreciated, thanks.

A: "Interface" is a reserved word and cannot be used as a namespace.