Upload file via FTP - Server returned error (550) File is unavailable, cannot find file

Question: I'm trying to upload a file via FTP from my local computer to an FTP server, which is also on my local computer at the moment. I've got this sub I'm calling:
    Public Sub UploadFTPFile(ByVal ftpservername, ByVal fullfilepath, ByVal filename, ByVal username, ByVal password)

    Dim clsRequest As System.Net.FtpWebRequest = _
    DirectCast(System.Net.WebRequest.Create("ftp://" & ftpservername & "/" & filename), System.Net.FtpWebRequest)
    clsRequest.Credentials = New System.Net.NetworkCredential(username, password)
    clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

    clsRequest.KeepAlive = False

    ' read in file...
    Dim bFile() As Byte = System.IO.File.ReadAllBytes(fullfilepath)

    ' upload file...
    Dim clsStream As System.IO.Stream = _
        clsRequest.GetRequestStream()
    clsStream.Write(bFile, 0, bFile.Length)
    clsStream.Close()
    clsStream.Dispose()
End Sub

When calling the sub, I do it like this:
UploadFTPFile("192.168.1.3/Temp", selectedSoundFileLong, OpenFileDialog.SafeFileName, "", "")

In other words, in the Sub, this string:
DirectCast(System.Net.WebRequest.Create("ftp://" & ftpservername & "/" & filename), System.Net.FtpWebRequest)

, creates the following:
    DirectCast(System.Net.WebRequest.Create("ftp://192.168.1.3/Temp/test.mp3"), System.Net.FtpWebRequest)

And at this line in the sub:
        Dim clsStream As System.IO.Stream = _
        clsRequest.GetRequestStream()

This error occurs:
The remote server returned an error: (550) File unavailable

What could be the cause of this?
I'm running an FTP Server using Golder FTP Server, which is freeware.
I think it's setup correctly because connecting to the FTP Server using the exact same string as above using Windows Explorer works great.
Answer: Try flipping the UsePassive property.  Control and data use different ports in FTP, it's possible you're getting through on the control port but getting blocked somehow on the data port.
Comment: Thanx, I tried this and it seemed to do the trick :)
Even though, it didn't work alone, I needed to set some settings on the FTP Server to be able to allow incoming traffic. Works now, thanx! :)
Comment: Btw, any idea how I can have a progressbar show the progress?
Answer: are you sure there is no extra white space in the webRequest string?  I believe you would get this error if the string happened to be like "ftp://192.168.1.3/ Temp/test.mp3"  Also, check to make sure you have the correct privileges to write to that server.  Additionally, make sure you file is test.mp3 and not test.MP3.
Comment: I didn't have ny spaces in the filename at all. The priveleges to write to the server was the solution :)
Answer: 550 is a System.Net.FtpWebRequest connection error code.
Also you have not constructed your FTP correctly check out my FTP class: Its pretty straight forward.
Public Class FTP
        '-------------------------[BroCode]--------------------------
        '----------------------------FTP-----------------------------
        Private _credentials As System.Net.NetworkCredential
        Sub New(ByVal _FTPUser As String, ByVal _FTPPass As String)
            setCredentials(_FTPUser, _FTPPass)
        End Sub
        Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String)
            Dim _FileInfo As New System.IO.FileInfo(_FileName)
            Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)
            _FtpWebRequest.Credentials = _credentials
            _FtpWebRequest.KeepAlive = False
            _FtpWebRequest.Timeout = 20000
            _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
            _FtpWebRequest.UseBinary = True
            _FtpWebRequest.ContentLength = _FileInfo.Length
            Dim buffLength As Integer = 2048
            Dim buff(buffLength - 1) As Byte
            Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()
            Try
                Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()
                Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)
                Do While contentLen <> 0
                    _Stream.Write(buff, 0, contentLen)
                    contentLen = _FileStream.Read(buff, 0, buffLength)
                Loop
                _Stream.Close()
                _Stream.Dispose()
                _FileStream.Close()
                _FileStream.Dispose()
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Upload Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
        Public Sub DownloadFile(ByVal _FileName As String, ByVal _ftpDownloadPath As String)
            Try
                Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpDownloadPath)
                _request.KeepAlive = False
                _request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
                _request.Credentials = _credentials
                Dim _response As System.Net.FtpWebResponse = _request.GetResponse()
                Dim responseStream As System.IO.Stream = _response.GetResponseStream()
                Dim fs As New System.IO.FileStream(_FileName, System.IO.FileMode.Create)
                responseStream.CopyTo(fs)
                responseStream.Close()
                _response.Close()
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Download Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub
        Public Function GetDirectory(ByVal _ftpPath As String) As List(Of String)
            Dim ret As New List(Of String)
            Try
                Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpPath)
                _request.KeepAlive = False
                _request.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails
                _request.Credentials = _credentials
                Dim _response As System.Net.FtpWebResponse = _request.GetResponse()
                Dim responseStream As System.IO.Stream = _response.GetResponseStream()
                Dim _reader As System.IO.StreamReader = New System.IO.StreamReader(responseStream)
                Dim FileData As String = _reader.ReadToEnd
                Dim Lines() As String = FileData.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
                For Each l As String In Lines
                    ret.Add(l)
                Next
                _reader.Close()
                _response.Close()
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Directory Fetch Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
            Return ret
        End Function

        Private Sub setCredentials(ByVal _FTPUser As String, ByVal _FTPPass As String)
            _credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)
        End Sub
    End Class

To initialize:
Dim ftp As New FORM.FTP("username", "password")

ftp.UploadFile("c:\file.jpeg", "ftp://domain/file.jpeg")

ftp.DownloadFile("c:\file.jpeg", "ftp://ftp://domain/file.jpeg")

Dim directory As List(Of String) = ftp.GetDirectory("ftp://ftp.domain.net/")
        ListBox1.Items.Clear()
        For Each item As String In directory
            ListBox1.Items.Add(item)
        Next


R error number of items to replace is not a multiple of replacement length

Question: I try to write a script that simulates 100 coin tosses with a certain probability of success, a starting capital and certain amount of capital to stop the game ('l'). It returns the probability of success. The code works, but it returns an error message. Could someone help me out? Thanks in advance!
spins=100
SuccessVector=c()
ProbSuccess<-function(p, capital, l){
for(i in 1:spins){
cap=rep(capital,spins)
while(cap[i]>0 & cap[i]<l){
cap[i]=cap[i]+sample(c(-1,1), replace = TRUE, prob= c(1-p,p))
if(cap[i]==l){SuccessVector[i]=1}
else(SuccessVector[i]=0)
}
}
successes=length(SuccessVector[SuccessVector==1])/length(SuccessVector)
return(successes)
}
ProbSuccess(0.5,10,20)

There were 50 or more warnings (use warnings() to see the first 50)
warnings()
Warning messages:
  1: In cap[i] = cap[i] + sample(c(-1, 1), replace = TRUE,  ... :
    number of items to replace is not a multiple of replacement length
Answer: From the help of sample():

"For sample the default for size is the number of items inferred from
  the first argument, so that sample(x) generates a random permutation
  of the elements of x (or 1:x)."

That's why you get samples of size 2. You might want to use:
cap[i]=cap[i]+sample(c(-1,1), size=1 , replace = TRUE, prob= c(1-p,p))

Comment: No worries. Please also consider accepting the most helpful answers to your questions (see stackoverflow.com/help/someone-answers).


Check if a key exists and return another key

Question: I need help with jq syntax on how to return the Gitlab job ID if it contains an artifact. The JSON output looks like this (removed a lot of unrelated info from it and added [...]):
[{
    "id": 3219589880,
    "status": "success",
    "stage": "test",
    "name": "job_with_no_artifact",
    "ref": "main",
    "tag": false,
    "coverage": null,
    "allow_failure": false,
    "created_at": "2022-10-24T18:21:25.119Z",
    "started_at": "2022-10-24T18:21:25.986Z",
    "finished_at": "2022-10-24T18:21:38.464Z",
    "duration": 12.478682,
    "queued_duration": 0.499786,
    "user": {
        "id": 123456789,
        [...]
    },
    "commit": {
        "id": "5e0e1f287d20daf2036a3ca71c656dce55999265",
        [...]
    "pipeline": {
        "id": 123456789,
        [...]
    "project": {
        "ci_job_token_scope_enabled": false
    },
    "artifacts": [],
    "runner": {
        "id": 12270859,
        [...]
    },
    "artifacts_expire_at": null,
    "tag_list": []
}, {
    "id": 3219589878,
    "status": "success",
    "stage": "test",
    "name": "create_artifact_job_2",
    "ref": "main",
    "tag": false,
    "coverage": null,
    "allow_failure": false,
    "created_at": "2022-10-24T18:21:25.111Z",
    "started_at": "2022-10-24T18:21:25.922Z",
    "finished_at": "2022-10-24T18:21:39.090Z",
    "duration": 13.168405,
    "queued_duration": 0.464364,
    "user": {
        "id": 123456789,
        [...]
    },
    "commit": {
        "id": "5e0e1f287d20daf2036a3ca71c656dce55999265",
        [...]
    },
    "pipeline": {
        "id": 675641982,
        [...],
    "project": {
        "ci_job_token_scope_enabled": false
    },
    "artifacts_file": {
        "filename": "artifacts.zip",
        "size": 223
    },
    "artifacts": [{
        "file_type": "archive",
        "size": 223,
        "filename": "artifacts.zip",
        "file_format": "zip"
    }, {
        "file_type": "metadata",
        "size": 153,
        "filename": "metadata.gz",
        "file_format": "gzip"
    }],
    "runner": {
        "id": 12270845,
        [...]
    },
    "artifacts_expire_at": "2022-10-25T18:21:35.859Z",
    "tag_list": []
}, {
    "id": 3219589876,
    "status": "success",
    "stage": "test",
    "name": "create_artifact_job_1",
    "ref": "main",
    "tag": false,
    "coverage": null,
    "allow_failure": false,
    "created_at": "2022-10-24T18:21:25.103Z",
    "started_at": "2022-10-24T18:21:25.503Z",
    "finished_at": "2022-10-24T18:21:41.407Z",
    "duration": 15.904028,
    "queued_duration": 0.098837,
    "user": {
        "id": 123456789,
        [...]
    },
    "commit": {
        "id": "5e0e1f287d20daf2036a3ca71c656dce55999265",
        [...]
    },
    "pipeline": {
        "id": 123456789,
        [...]
    },
    "web_url": "WEB_URL",
    "project": {
        "ci_job_token_scope_enabled": false
    },
    "artifacts_file": {
        "filename": "artifacts.zip",
        "size": 217
    },
    "artifacts": [{
        "file_type": "archive",
        "size": 217,
        "filename": "artifacts.zip",
        "file_format": "zip"
    }, {
        "file_type": "metadata",
        "size": 152,
        "filename": "metadata.gz",
        "file_format": "gzip"
    }],
    "runner": {
        "id": 12270857,
    },
    "artifacts_expire_at": "2022-10-25T18:21:37.808Z",
    "tag_list": []
}]

I've been trying to do either of the following using jQ:
Either:

Check if artifacts_file key exists in each iteration and if it does return the (job) id (so .[].id)

Check if artifacts array is empty in each iteration and if it is empty return the (job) id.

In both cases I'm able to do the first part but I am not sure how to return the .id key.
Related stackoverflow questions that I've been trying to utilize and adapt to my case:

jq - return array value if its length is not null
How to check for presence of 'key' in jq before iterating over the values

What I have so far: jq '[.[].artifacts[]|select(length > 0)] | .[]' which returns all the artifacts found (but it doesn't contain the .id of the job).
Comment: I could do this via shell/bash script but I think it'd be cleaner if done with jQ
Answer: Checking the existence of a field using has:
.[] | select(has("artifacts_file")).id

3219589878
3219589876

Demo
Checking if a field is an empty array by comparing it to []:
.[] | select(.artifacts == []).id

3219589880

Demo
Comment: @Fadi Checking with `.artifacts_file != null` would disregard cases with field `.artifacts_file` present but explicitly set to `null` (which might suffice for your use case, just wanted to point it out as you were asking if a "key exists").
Comment: @Fadi To use `@tsv`, which requires an array as input, don't decompose the top-level array with `.[] | …`. Rather use a `map(…)` to retain it, then apply `@tsv` to it at the end, i.e. `map(select(…).id) | @tsv` (along with the `--raw-output` or `-r` flag, of course, to output raw text).
Comment: @Fadi `map` should **replace** `.[]`, not be composed to it. See a [Demo](https://jqplay.org/s/1L4pKpVKaw1).
Comment: Nice, I just also was able to do it this way:

`.[]| select(.artifacts_file != null) | .id`  (you beat me to the answer haha)
Comment: If you don't mind, how would you output this in a way that can be parsed easier (@tsv perhaps?).
Comment: I did `jq --raw-output '.[] | map(select(has("artifacts_file")).id) | @tsv'` but I get the following error:

`jq: error (at :283): Cannot check whether number has a string key exit status 5`


How can I tell if event 1 occurred before, after or at the same time as event 2?

Question: New to R: If I have multiple observations for the same ID.  How can I tell if event 1 occurred before, after or at the same time as event 2 for each ID?
ID is an integer. The number of observations for each ID varies.  Time is just the time period; 1,2,...t. Events 1 and 2 are 0/1 dummies.
I need to be able to count the number of times event 1 occurs before, after or at the same time as event 2.  Seems like this should be pretty simple/straight forward, but I haven't had any luck.
UPDATE: this should give a sense of the data:
my.df <-  structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L), Time = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 1L, 2L, 3L, 4L,
5L), Event.1 = c(0L, 1L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 1L,
1L), Event.2 = c(1L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L,
0L)), .Names = c("ID", "Time", "Event.1", "Event.2"), class = "data.frame", row.names = c(NA,
-12L))

Thanks!
Comment: Please post some data.
Comment: Make your question [reproducible](http://stackoverflow.com/q/5963269/1315767)
Comment: You should provide data , the problem as it is not well defined. For example , does event1 and event2 occurs the same number of time?
Comment: Sorry, I think the update should help.
Comment: You still haven't explained how to compare the `Time` value with the values for "events" .
Answer: Assuming that you want to count how often Event.1 occurred per ID before Event.2 did, this would be a shortcut using ddply
ddply(
  my.df, .(ID), summarize,
  Event.1 = sum( Event.1[ seq_len( which.max( Event.2 ) ) ] )
)

which gives
  ID Event.1
1  1       0
2  2       1
3  3       0


Repair old garage workbench

Question: I have this old garage workbench that seems very sturdy

The wood is OK, I could replace the door.
But the surface's corner has cracking like this:

This is done from previous owner. I would like to fix it somehow. What is that thin strip of wood outside? It seems like it's harden by some chemical process (not paint or maybe...).
Answer: That looks like hardboard, "High density fibreboard" to use its full name.
AKA "Masonite"(tm)
Comment: Any suggestions for how to fix it?  -)

Repair old garage workbench


Performance counter inaccurate in C#

Question: I am working on a project that is collecting data about performance, like the Performance Monitor does.
However, when I running a monitor on pages/sec, it is givning a different result than the Performance Monitor.
I am thinking it is because the performance counter not giving all the decimals, and the average calculation becomes inaccurate.
My code UPDATED:
<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Management;
using System.Net.NetworkInformation;

namespace PerformanceMonitor
{
    class Program
    {

        static void Main(string[] args)
        {
       List<float> pagesSec = new List<float>();
        PerformanceCounter memoryPages = new PerformanceCounter("Memory", "Pages/sec");

        while (count < 50)
        {
            pagesSecValue = memoryPages.NextValue();
            pagesSec.Add(pagesSecValue);

           Console.WriteLine("Pages: " + pagesSecValue);
           count++;

            Thread.Sleep(1000);
            Console.Clear();
        }

Console.WriteLine("Avg pages/sec: " + pagesSec.Average());

 Console.ReadLine();
        }
}
}
</code>
While running the program, most of the time I get 0 printed on the console.
Results:
My program: 4,06349
Windows Performance Monitor: 12,133
Why the difference?
Comment: @Ramhound I find your first two sentences ridiculously axiomatic. Obviously something is wrong, and of course it is a result of how the OP coded it. Otherwise they would not be asking for help. I don't understand what about this question demonstrates a lack of research in your eyes, or what code you are missing.
Comment: The reason this counter is inaccurate is because of how you decided to code it. If you are getting a 0 then you are doing something wrong.  Please post how exactly this loop is being called.  I have to downvote this question due to your lack of research before asking it.
Answer: You're doing different calculations than the performance counter.  What you're doing is getting the pages per second once a second for 50 seconds and getting the average of those 50 numbers.  One, clearly the performance counter is working with data for a longer period of time.  Two, this isn't a useful average.  The performance counter is effectively taking a much higher sample.  For example, what do you think would happen if the pages per second values did this over a period of 2 seconds:
0    .5    1    1.5    2
5    15    6    20     4
And your code sampled at 0, 1 and 2 seconds?  Your "average" would be 5 and the performance counter (if it sampled at .5 seconds, which it doesn't) would be 10.
Comment: Thank you for your answer. Now my sample rate is every 100ms and gives a result that is more equel to Windows Performance Monitor value.

Performance counter inaccurate in C#


Silverlight 4.0 Accordion Template

Question: Is their a free template of accordion which behaves like Outlook? When the user adjusted its grid, the accordion item will form an images, stack horizontally?
Comment: Take a look at the Accordion Control included in the Silverlight Toolkit.
Answer: There is an accordion in the Silverlight toolkit, but it's not quite "Outlook like".
http://silverlight.codeplex.com/
You can customize it, but I found it a bit complex. there are some good examples in the Expression Gallery. eg.
http://gallery.expression.microsoft.com/en-us/site/search?f[0].Type=SearchText&f[0].Value=accordion&x=0&y=0
and I just found this that might help
http://gallery.expression.microsoft.com/en-us/animatedmenu

Silverlight 4.0 Accordion Template


Logo is not changing

Question: I'm working on a new website and the logo from the homepage is not changing.
My URL: http://sugubat.inbanat.ro/
The logo that I want to appear: https://sugubat.inbanat.ro/wp-content/uploads/2020/11/logo-sugubat-1.png
The logo that actually appears: https://sugubat.inbanat.ro/wp-content/uploads/2018/08/retina-logo-2.png
I've also delete The logo that actually appears from the Media section from WordPress... but nothing.
Have anybody had this problem? Can you help me????
Comment: probably a caching issue. Empty the browser cache, log out and in again etc.
Comment: Can you provide a [mre]? Without one it will be pretty much impossible for us to tell you why your code is giving incorrect results.
Comment: P.S.: The header is built in Elementor. Layouts > https://sugubat.inbanat.ro/layouts/elementor-header-default/
Comment: This question might be better suited for the WordPress StackExchange site.
Answer: you forget to mention https: at the beginning and you just mention the address of logo as //sugubat.inbanat.ro/wp-content/uploads/2018/08/retina-logo-2.png .
just change the address to:
https://sugubat.inbanat.ro/wp-content/uploads/2020/11/logo-sugubat-1.png

Logo is not changing


Why does my hello world with streams not show anything?

Question: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CSQuick
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var ff = new MemoryStream())
            using (var f = new StreamWriter(ff))
            {
                f.WriteLine("Stream hello world fail");
                f.Flush();
                using (TextReader ts = new StreamReader(ff))
                {
                    Console.WriteLine(ts.ReadToEnd());
                }
            }
        }
    }
}

Answer: Set
ff.Position = 0;
before reading, otherwise you start reading at the end of the stream.


VueJS. Issue with VueX understanding

Question: I build SPA using VueJs + VueX and I have buttons "Login" and "Sign Up" to be clicked in one component and <component></component> tag in other component where should be conditionally rendered 1 of to Modals ("SignUp" form and "Login form"). Modals are also components.
When I call console.log, I see that state.currentView changes depending which button clicked but checking {{ $data | json }} inside markup shows that state wasn't changed and what is more important the modal are not changing. So I've code as follows:
App.vue:
<template>
  <navbar></navbar>
  <component v-bind:is="currentView"></component>
</template>

In Navbar.vue template I keep the buttons and methods to change currentView state:
    <md-button class="navbar__link"
               @click="changeCurrentModal('Signup')">
      Sign Up
    </md-button>

    <md-button class="navbar__link"
               @click="changeCurrentModal('Login')">
      Login
    </md-button>

    export default {
     name: 'navbar',
     computed: {
       currentView () {
        return this.$store.state.currentView
      }
    },
    methods: {
      changeCurrentModal (curentView) {
        this.$store.commit('changeCurrentModal', curentView)
     }
   }
 }
 </script>

My store.js file looks as follows:
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {
  currentView: 'Signup'
},
mutations: {
  changeCurrentModal: (state, currentView) => {
    console.log(currentView)
    state.currentView = currentView
  }
},
actions: {
   changeCurrentModal: ({commit}, currentView) => {
     commit('changeCurrentModal', currentView)
   }
  }
})

Comment: Just found my error. There should be as follows:
Answer: What you should do is make a getter and pull it into your component using a computed property.
Your vuex would become...
...

export default new Vuex.Store({
   state: {
      currentView: 'Signup'
   },
   getters: {
      getCurrentView: state => {
          return state.currentView
      }
   }
   mutations: {
      ...
   },
   actions: {
      ...
   }
})

And your computed prop would look like this...
computed: {
  currentView () {
    return this.$store.getters.getCurrentView
  }
}

By doing this, you will maintain reactivity with vuex data.
Answer: Although you got Vuex to work, you may want to check out Vue-router if you haven't already. It would accomplish the same thing you want and might offer code that's easier to follow.

VueJS. Issue with VueX understanding


how to pass in f-string inside another string in dataframe series

Question: How does one pass the number 6 defined as a string into 'text2=self.nmb' where self.nmb is a method attribute
self.nmb='6'
X = pd.DataFrame({'A':['text1', 'text2=f'{self.nmb}'']})
print(X)

Desired output
           A
0      text1
1    text2=6

Comment: pd.DataFrame({'A':['text1', 'text2='+nmb]})
Answer: Use:
In [1232]: nmb='6'

In [1235]: X = pd.DataFrame({'A':['text1', f'text2={nmb}']})

In [1236]: X
Out[1236]:
         A
0    text1
1  text2=6

Comment: In place of `{nmb}`, use : `{self.nmb}`.
Comment: Hi. I forgot to mention it is inside a class/method


New 12.10 Install, Windows Not in Boot Menu

Question: I just installed Ubuntu 12.10 on my new computer alongside my previous Windows 7 installation. Upon booting for the first time (post install) my boot menu only lists Ubuntu.
I installed using a liveCD, I had to set up my partitions myself because my Windows wasn't being detected (I set up the new partition out of free space on the drive.). I know Ubuntu did not overwrite my Windows because I can mount the Windows drive and access the files from here.
I also tried running boot-repair, as was recommended for people who didn't have Ubuntu showing up in the menu, but now I just have two different Ubuntu options. Still no Windows.
(If you require any additional data [logs, etc.], could you tell me how to find it, I am a bit new to this.
Any help is greatly appreciated.
Answer: The Boot Repair option worked perfectly for me. Installed 12.10 after windows 8, the install did not recognize win8, using the boot repair utility found the windows partition and successfully added it.
Answer: Try updating Grub using the steps below and hopefully it will restore your windows to boot menu

Press Ctrl+Alt+T to open the terminal.
Now type on terminal window
sudo update-grub

Enter your password, wait and restart.
Comment: I ran the grub updater and it said,
      Generating grub.cfg ...
      Found linux image: /boot/vmlinuz-3.5.0-17-generic
      Found initrd image: /boot/initrd.img-3.5.0-17-generic
      Adding boot menu entry for EFI firmware configuration
      Done
I'm down to 1 ubuntu entry but still no Windows.
Answer: Boot into Windows with the installation disk, then install EasyBCD.  (I don't think there is a linux version).  If set up right, you can pick a os from their menu before hitting grub.
Comment: Just checking what this is going to do before I do it. Will EasyBCD make a second boot menu that comes up before GRUB? Would Grub only come up if I choose to boot into Ubuntu? Am I completely misreading that?
Comment: Correct, EasyBCD creates a boot menu.  If you select the Ubuntu option, it bypasses grub.  When I installed 12.04 after Windows, I was unable to boot into Ubuntu, I only received the Windows boot menu.  I installed EasyBCD and was able to boot into both OS's.  A downside is that you cannot use grub's advanced options like safe boot and such.  Getting grub to show Windows would be a better option, but if not possible, consider EasyBCD
Comment: A side note, I recently ran boot-repair, and now grub took over as the main boot menu and it shows Ubuntu and Windows, which may or may not pertain to you.
Comment: When I put in my Windows disk and boot off of it, the thing freezes on the area where I'm supposed to select my language. My mouse and keyboard don't work at all (can't even do something like turning on number lock).
Comment: I was wondering, if the EasyBCD might work because it allows me to use their boot menu instead of the GRUB one, would something like Burg that customizes the boot menu do something similar? Because I could install that from here.
Comment: I have not used burg, but I assume that if grub can't find your windows boot files, then burg won't.  Nevertheless, it's worth a try.  Also, maybe try boot-repair again and try the advanced options.  Above my level of experience because I only tried "Recommended repair".
Answer: I noticed the same thing.
I also didn't have a Windows CD to fix the MBR but found a useful utility that sorted everything out quicksticks.

Open terminal and paste the following commands:
sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update

After the update, install Boot Repair:
sudo apt-get install -y boot-repair

You can run it via the menu or by entering:
boot-repair

I used the recommended repair and my boot was back to normal.
You can check out the community documentation at:
http://help.ubuntu.com/community/Boot-Repair
Comment: Sorry, I did not see you mentioned trying boot-repair. Please ignore my suggestion.
Answer: Kinda sounds like some windows files are corrupt by the way you say that you can't boot from the disk and the Ubuntu installer could not even detect Windows.  If you had installed Ubuntu to a separate drive, then I would say, disconnect it and boot into Windows and try to repair Windows from there.  But if they are on the same drive, then uninstall Ubuntu and then repair Windows. Put in the Ubuntu disk, boot from your cd drive and install Ubuntu.  Ensure the installer can detect Windows before continuing.
Comment: Is it possible to uninstall Ubuntu from Ubuntu? Because I can't get into the Windows to do it otherwise.
Comment: I would boot into Ubuntu "Just try it out", and format the Ubuntu partitions.  You might need to install gparted if you are unable to do it with the stock disk management software.  I'm not sure if that would delete the Ubuntu boot files because they are usually installed on a special area on the hdd ([MBR](http://en.wikipedia.org/wiki/Master_boot_record)), not in the Ubuntu partitions.  But if you remove grub, which is saved on your /boot partition, you should be able to boot into Windows after that.
Answer: I asked about this on the Ubuntu forums as well and got some really good feedback from the maker of the Boot-Repair utility. I'm pasting their instructions here which worked perfectly for me in case someone else has the same problem.

This case is rare. You have no original
  /EFI/Microsoft/Boot/bootmgfw.efi . (presence of
  /EFI/Microsoft/Boot/bootmgfw.efi.grb indicates that B-R created a
  dummy /EFI/Microsoft/Boot/bootmgfw.efi ). I will update B-R for this
  case. Meanwhile, you can do this:
Please : 1) boot an Ubuntu CD, choose "Try Ubuntu" 2) open a terminal
  and type the following commands one by one:
sudo mount /dev/sda1 /mnt
Press Enter
sudo rm /mnt/EFI/Microsoft/Boot/bootmgfw.efi*
Press Enter
sudo cp /mnt/EFI/Boot/bootx64.efi.bkp /mnt/EFI/Microsoft/Boot/bootmgfw.efi
Press Enter
3) run Boot-Repair --> Recommended Repair , indicate us the new URL
  that will appear
  4) then reboot the pc without CD, and tell us what
  you observe
Comment: Actually, this isn't entirely solved because the problem returns as soon as I shut down or restart from Windows. I'll update again once I figure that out.


Self hosting WCF service: unable to use wcfTestClient - unable to get metadata

Question: the service DOES work normally, but for some reason, I an unable to use wcftestclient.exe from my local pc to the server - I Want to call a method using wcftestclient.exe.
Its all company-internal, self-hosting (running within windows service, no iis). framework 4. Basichttpbinding, no need for anything secure.
Here is my servicemodelconfig ...
<system.serviceModel>
    <services>
      <service name="myService">

        <endpoint
          address="http://servername:8001/myService"
          binding="basicHttpBinding"
          contract="IMyService" />

      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name ="MyDefaultBehaviour">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://servername:8001/myService/mex" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceThrottling maxConcurrentCalls="1" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

I get ...
Error: Cannot obtain Metadata from  If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address.  For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error    URI:
Metadata contains a reference that cannot be resolved:'.    Content Type application/soap+xml; charset=utf-8 was not supported by service
The client and service bindings may be mismatched.    The remote server returned an error: (415) Cannot process the message because the content type 'application/soap+xml; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'..HTTP GET Error    URI:
There was an error downloading 'http://
The request failed with HTTP status 400: Bad Request.
I 've blanked out our servernames above, so lots of blanks, but hopefully the message is clear enough.
I did experiment with adding additional endpoint ...
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />

but with this, the windows service wouldn't start.
Thanks
----- added later --- have also tried this, but once again, service doesn't start
<system.serviceModel>
    <services>
      <service name="myService" behaviorConfiguration="MyDefaultBehaviour">
        <host>
          <baseAddresses>
            <add baseAddress="http://myServer:8001/myService" />
          </baseAddresses>
        </host>

        <endpoint
          address=""
          binding="basicHttpBinding"
          contract="Contracts.ImyService" />

        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetaDataExchange" />
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name ="MyDefaultBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceThrottling maxConcurrentCalls="1" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Answer: If you add the mexendpoint, you need to add the baseAddress:
like below:
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:9999/WcfTcp/Service1"/>
          </baseAddresses>
        </host>

Comment: Thanks @Grady - I did try base address way, but not within endpoint tag, but within service tag, but the windows service wouldn't start. Also, I'm using http.
Answer: My second config DOES work after all, ie, w ith the basaddresses, the empty string for the standard endpoint, and the "mex" endpoint. IMetadataExchange was spelt with incorrect capital D. Sorted. Thanks very much @Grady


Why there are hearts around my Pokémon?

Question: I was playing sapphire today as usual but when I sent my zigzagoon to battle I noticed that there are hearts flown around him when it just came out of poke ball not the usual animations of lines or dots. Why is that?
Answer: Different kinds of Poké Balls have different animations for when they pop open. In your case, I believe it's either a Nest Ball or a Luxury Ball.

Why there are hearts around my Pokémon?


Is there a value of $\alpha$ such that $\cot\alpha=-2\sqrt{3}\sin\alpha?$

Question: Is there a value of $\alpha$ such that $\cot\alpha=-2\sqrt{3}\sin\alpha?$
How can I think to solve the problem? We can find that $\dfrac{\sin\alpha}{\cot\alpha}=-\dfrac{1}{2\sqrt{3}},$ so $\sin\alpha$ and $\cot\alpha$ should be with different signs. I looked at the trig ratio table and saw that $\dfrac{\sin150^\circ}{\cot150^\circ}=-\dfrac{1}{2\sqrt{3}},$ but I really don't like that solution. Can you come up with something better?
What if we have the following problem:
Is there a value of $\alpha$ such that $2\tan\alpha=-\sqrt{2}\sin\alpha?$
Answer: Hint:
$$\cos(\alpha)=-2\sqrt{3}\sin^2{\alpha}=-2\sqrt{3}(1-\cos^2{\alpha})$$
Comment: @nicoledobreva - Write cot($\alpha$) = cos($\alpha$)/sin($\alpha$).
Comment: It comes from the formula $\tan={\sin\over\cos}$ and that $\cot={1\over \tan}$
Comment: It is a quadratic equation of the variable $\cos(\alpha)$. You can use the quadratic formula.
Comment: You can think of it this way: If we assume there is a value then we do the above to see if we can find the value or find out there is a contradiction. If we find a contradiction then that means there is no value.
Comment: Thank you for the response! I don't see why $\cos\alpha=-2\sqrt{3}\sin^2\alpha.$ Can you clarify that for me?
Comment: Thank you! I saw why $\cos\alpha=-2\sqrt{3}(1-\cos^2\alpha),$ but I don't see how this helps for the solution. How from here can we say if there is a value for $\alpha$?
Comment: Oh, I see thank you! I have just one more question. Here we used the identity $\sin^2\alpha+\cos^2\alpha=1.$ Doesn't it hold only if there is a value for $\alpha$ which is what we need to check?
Answer: $\cot\alpha = \frac{\cos \alpha}{\sin \alpha}=-2\sqrt{3}\sin\alpha$ is equivalent to $\cos \alpha = -2\sqrt{3}\sin ^2 \alpha$ and so to $$\cos \alpha = -2\sqrt{3} (1-\cos ^2 \alpha)$$
If we note $X = \cos \alpha$, then $$2\sqrt{3} X^2 -X -2\sqrt{3}=0$$
The discriminant is $\Delta = 49>0$.
So the solutions of the polynomial equations are $x_{1,2}=\frac{1\pm7}{4\sqrt{3}}$ and $x_2 = -\frac{\sqrt{3}}{2}$ is the only one that is inferior to $1$ in absolute value (this is important because $\forall \alpha, |\cos \alpha | \leqslant 1$)
So there is only one solution to your equation, which are $\alpha = \pm \cos ^{-1} -\frac{\sqrt{3}}{2} +2k\pi$ so $$\alpha = \pm \frac{5\pi}{6} + 2k\pi$$
Comment: the thing is since $|\cos|<1$ if the roots had been superior to $1$ in absolute values, there would have been no solution despite the fact that the polynomial equation had solutions
Comment: In fact. thank you. I edited
Comment: Okay the solutions are $-\dfrac{\sqrt3}{2}$ and $\dfrac{2\sqrt3}{3}.$ What should I do next? I don't understand what you have noted: "which are both inferior to $1$ in absolute value".
Comment: I think it would be better if you wrote $|\cos\alpha|\le1$.
Comment: for a reason I don't understand, i can't edit my comment, but I edited my answer.
Comment: Also, I think that the positive root $\dfrac{2\sqrt{3}}{3}$ is greater than $1.$
Comment: Sorry (again). I edited. This time I think it's right.


CSS Inheritance - Why is a 'later' declaration being overwritten by an 'earlier' one?

Question: I'm new to html and CSS but through the recent work I've been doing I thought I was getting a hold of how CSS works.. And it seemed to work kind of like scope in a language like Java.
My understanding was that, like Java, the declaration with the narrowest scope wins.. aka the most specific declaration would override its inherited versions, allowing you to, like I am trying to do, declare a set pattern for a group of objects and then if one of those needs a slightly different setting you can simply override the general rule for that one item.
However, I'm getting the feeling this is not the case, here I have a tabbed content box I'm working on;
The html:

What We Do

What Makes Us Different

Our Background

Why We Do It

And of course I labelled the one list-item as "large" so that I could force its width to be a little wider so it can fit on one line.
The CSS:
ul#tabs li a {
    width: 144px;           //TRYING TO OVERRIDE THIS DECLARATION
    height: 33px;
    color: #42454a;
    background-color: #fff;
    border-left: 1px solid #000;
    border-right: 1px solid #000;
    text-decoration: none;
    display: block;
    text-align: center;
    border-radius: 3px;
}
    a#large {
        width: 155px;          //WITH THIS ONE
        display: block;
    }

What is happening is that the width of a"large" is being overwritten by a. (144px not 155px)
So, two questions:

Is it possible to do what I am trying to do here-override an inherited trait?
Is it possible to simply vertically align each of the 4 tab's text to be centered? (This would make up for the ugly look I'm getting from the one button being two lines, where the rest are just one)
Answer: See Cascading. The order in which the CSS is encountered is only used as a final resort.
Both selectors have the same media type.
Both selectors have the same importance and origin.
The specificity of your selectors are different
ul#tabs li a         a=0 b=1 c=0 d=3
a#large              a=0 b=1 c=0 d=1

The top one is more specific, so it's the one that will get used.
But if you used ul#tabs li a#large, it would get selected because it has the highest specificity.
ul#tabs li a#large   a=0 b=2 c=0 d=3

Answer: The CSS specifications define some 'rules of specificity' that determine which properties override others. This article covers the basics of it.
The selector ul#tabs li a is more specific than a#large and therefore the properties from a#large that are also in the other ruleset are ignored.
One workaround is to use !important:
a#large {
    width: 155px !important; // !important gives this property precedence
    display: block;
}


Chocolate Pieces

Question: With only two linear cuts,
it is possible to divide the
chocolate cue represented
as a matrix of rows 4 and columns 5 so that
Aldo gets half,
Bruno a fifth, to Ciro the
remaining part.

How much does Ciro get as a fraction?

Answer this last
question in two ways: either by deducting it from the figure
based on the cuts made, or by calculating an
an appropriate numerical expression.

The chocolate cue is represented as a matrix of 4 rows and 5 columns:
$$ \begin{bmatrix} X & X & X & X & X \\ X & X & X & X & X \\ X & X & X & X & X \\ X & X & X & X & X \end{bmatrix} $$
We cut the chocolate stick in half along the lines:
$$\begin{bmatrix} X & X & X & X & X \\ X & X & X & X & X \end{bmatrix} $$
$$\begin{bmatrix} X & X & X & X & X \\ X & X & X & X & X \end{bmatrix} $$
Aldo gets the upper half.
We cut the bottom half in half along the columns:
$$ \begin{bmatrix} X & X \\ X & X \end{bmatrix} $$
Aldo gets the top half, Bruno gets the piece on the left, and Ciro gets the piece on the right.
If we denote the total number of chocolate squares as $N$, we have:

Aldo gets $\frac{1}{2}N$.
Bruno gets $\frac{1}{5} \times \frac{1}{2}N = \frac{1}{10}N $.
Ciro gets $\frac{4}{5} \times \frac{1}{2}N = \frac{2}{5}N $.

The sum of these quantities must equal the total, so:
$$ \frac{1}{2}N + \frac{1}{10}N + \frac{2}{5}N = N $$
$$\frac{1}{2} + \frac{1}{10} + \frac{2}{5} = 1 $$
Cyrus gets $\frac{2}{5}$ of the chocolate stick but the solution is $3/10$.
Comment: What is the question?
Comment: @Henriksupportsthecommunity the question is likely to correct where he went wrong.
Comment: @Henriksupportsthecommunity How much does Ciro get as a fraction?
Comment: Why is there the request of closure? I have given the problem and my answer.
Answer: Bruno gets a fifth of the entire chocolate bar, not a fifth of the remaining half after Aldo gets his half. So Aldo gets $N/2$, Bruno gets $N/5$ and Ciro the rest. Can you take it from here?
Comment: Yes, that was a typo, thanks
Comment: Bruno gets $N/5$.

Chocolate Pieces


How to turn the content of a text field into a variable in Xcode 11 (swift)?

Question: As you can see from. the title, i am trying to turn the content of a text field into a variable. I have used this code:
@IBOutlet weak var TextField: UITextField!
let variable = TextField.text

UPDATE: I created a new project with new code, which I have inserted above. The only errors I got was this: Cannot use instance member 'TextField' within property initializer; property initializers run before 'self' is available.
Comment: Basically `String(textfield.text)` (create a string from a string) is redundant apart from the *optional* issue.
Comment: Is there a typo in `textfeild.text` in the question or you also have the typo in your code? Should be `textfield.text`
Comment: The original code did not have textfeild.text. Instead, the actual one is o.text. The variable was repton. I just made my variable into things that i know i could spell. I changed it to not confuse you guys.
Answer: UPDATE: I think you are having different issues than the one you mentioned, after your answer has changed a few times, I understood that you want to use the value of a UITextField to use it for your WebView URL to load and also to check the prefix sometimes in a different state later on. But you are actually loading the webview on viewDidLoad which won't work for you as you didn't have yet the chance to change your UITextField value manually from your phone/simulator.
That means there can be different work-case scenarios and flows, that you might want to think and implement which one best works for your business needs. For now, if you want the value of a UITextField to be stored in a variable and access the latest value or the first value of it, you can follow my original answer:
If you want variable to be a stored property, here you store the value of textfield.text in the exact moment you instantiate variable, then the issue in your code is that textfield.text can be nil, so you would have better handled that as:
let variable = textfield.text ?? ""

If you want variable to be a computed property, in this case everytime you try to access variable and get its value it will calculate it based on the code in its closure, so it will fetch the latest textfield.text value everytime you try to get variable value:
var variable: String? { // optional, remember textfield.text can return nil
    return textfield.text
}

If you always want to return something you could instead declare it this way, and return an empty string in case textfield.text is nil (remember, textfield.text can be nil):
var variable: String { // not optional, you give a "" default value if nil
    return textfield.text ?? ""
}

Comment: In the new project, for some reason, it happened to work! Thank you denis_lor
Comment: Sorry, it didn't work. The first one made a random error with a variable in the line beneath it, the second one just had errors EVERYWHERE and the third had no errors but when i ran it, it gave me a blank white screen and gave me the error Thread 1: signal SIGABRT. By the way, the variable i am trying to store is a  URL. Would that effect anything?
Comment: Maybe you are having other code issues, this code is really independent of anything, and works exactly as shown. Can you post some screenshots to see how your error are now appearing or more code so we can try something concrete?
Comment: Well, i was trying to make a web browser, i used the code of the first answer in https://www.stackoverflow.com/questions/36231061/wkwebview-open-links-from-certain-domain-in-safari and then replaced all the google.coms in the code as the variable variable and i created a text field that you entered a URL in. That text field's content then got turned into variable but i got these 4 errors above.
Comment: @QiwiCode Can you post your code in the question, edit the question and post more code so I can see exactly what you are still missing and help you out
Comment: I thought you just used the code on that answer and replace `google.com` with textfield values, then post the code at least till the first 2-3 errors you get from top to bottom.
Comment: Right. I used the exact same code, replaced google.com with a variable, got a textfield on main.storyboard, control-dragged it into the assistant editor and failed to turn it's content into the variable that replaces google.com.
Comment: I can't post 2 screenshots in one go sorry!
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210287/discussion-between-denis-lor-and-qiwicode).
Comment: @QiwiCode did my answer helped you with your initial problem? If yes - please mark it as accepted


ASP.NET Mermbership.cs file Template

Question: Is there any ASP.NET Membership file Template available ?
if it is not available how to write Custom Membership file from the Scratch... ?
Thanks in Adv.
Answer: Here are the methods you need to override for your membership provider. If you want to learn, you can decompile this ASP.NET Universal Providers using JetBrains's dotPeek or telerik JustDecompile; you will get DefaultMembershipProvider.cs (I cannot upload it as it is too long).
<code>public class CustomMembershipProvider : MembershipProvider
{
    public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
    {
        throw new NotImplementedException();
    }

    public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
    {
        throw new NotImplementedException();
    }

    public override string GetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }

    public override bool ChangePassword(string username, string oldPassword, string newPassword)
    {
        throw new NotImplementedException();
    }

    public override string ResetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }

    public override void UpdateUser(MembershipUser user)
    {
        throw new NotImplementedException();
    }

    public override bool ValidateUser(string username, string password)
    {
        throw new NotImplementedException();
    }

    public override bool UnlockUser(string userName)
    {
        throw new NotImplementedException();
    }

    public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    {
        throw new NotImplementedException();
    }

    public override MembershipUser GetUser(string username, bool userIsOnline)
    {
        throw new NotImplementedException();
    }

    public override string GetUserNameByEmail(string email)
    {
        throw new NotImplementedException();
    }

    public override bool DeleteUser(string username, bool deleteAllRelatedData)
    {
        throw new NotImplementedException();
    }

    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override int GetNumberOfUsersOnline()
    {
        throw new NotImplementedException();
    }

    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override bool EnablePasswordRetrieval
    {
        get { throw new NotImplementedException(); }
    }

    public override bool EnablePasswordReset
    {
        get { throw new NotImplementedException(); }
    }

    public override bool RequiresQuestionAndAnswer
    {
        get { throw new NotImplementedException(); }
    }

    public override string ApplicationName
    {
        get { throw new NotImplementedException(); }
        set { throw new NotImplementedException(); }
    }

    public override int MaxInvalidPasswordAttempts
    {
        get { throw new NotImplementedException(); }
    }

    public override int PasswordAttemptWindow
    {
        get { throw new NotImplementedException(); }
    }

    public override bool RequiresUniqueEmail
    {
        get { throw new NotImplementedException(); }
    }

    public override MembershipPasswordFormat PasswordFormat
    {
        get { throw new NotImplementedException(); }
    }

    public override int MinRequiredPasswordLength
    {
        get { throw new NotImplementedException(); }
    }

    public override int MinRequiredNonAlphanumericCharacters
    {
        get { throw new NotImplementedException(); }
    }

    public override string PasswordStrengthRegularExpression
    {
        get { throw new NotImplementedException(); }
    }
}
</code>
Comment: Hey savior you are. yes i was expecting this answer for long time. i was expecting that DefaultMembershipProvider.cs thing... this is a great reply. thank you very much...
Answer: I'm not sure what you're talking about but here you have an good sample about how to implement a custom membership provider
On MSDN you'll also find several resournces about this topic
Comment: sorry for that, now i updated my question and i hope this is clear.    Thank u.
Comment: @omm: I think links on my answer should help you. Please take a look to them.
Comment: Thanks  but my question is : is there any Predefined Membership file is available or we have to write on our own ?

MSDN says that we can write our own Custom Membership Files, so is there any Default Membership available ? where?

ASP.NET Mermbership.cs file Template


find string values in pandas

Question: I have nearly 200+variables and ~2M records in Pandas dataframe. All variables should contain numeric data. But due to some error all the variables having some random text inside. I don't know what are those text and all the variables not having same kind of text.
I want to extract those string in variable wise.
Ex:
Input

Output

Could you please help me on this.
Answer: Use DataFrame.melt with filter by to_numeric with Series.isna:
out = df.melt().loc[lambda x: pd.to_numeric(x['value'], errors='coerce').isna()]

out = df.melt()
out = out[pd.to_numeric(x['value'], errors='coerce').isna()]

find string values in pandas


Web App (Svelte): How to divide screen in distinct sections

Question: I am creating a program calculating flow in piping systems. In the user interface, the program contains a graphical drawing diagram, a ribbon on top of the screen containing functions helping the user drawing, and possibly a side ribbon with additional functions.
Here i've included a picture explaining my intentions:

As of now, my approach to achieve the division of screen, is to have nested elements in a tree structure, where the main branches are the divisions of the screen (the functional areas and the graphical drawing area). In the graphical area, the objects drawn in this area are positioned using absolute coordinates w.r.t. the drawing area element, and are also nested inside this element. As of now, this is the progress that has been made (grey area is the graphical drawing area, the red area is going to contain functions):

To obtain this current division of screen, the general html code looks like this, and the general css code uses mainly certain flex-settings.
App.svelte:

    <Bar/>

    <DrawBoard/>

DrawBoard.svelte:

    {#each $editor.objects as object}
        <ObjectOnBoard bind:object={object}/>
    {/each}

    <ObjectSelection/>

Using this method leads to several problems. As can be seen in the current progress, one object is moved to the edge of the screen, but instead of going out of the screen, it appears above the functional area. I would want to elements inside elements (the object inside the graphical area) disappear if they went out of the element, as if the graphical area was a screen of its own just like the whole tab. This leads me to my question:
Is this the right approach to achieve the user interface with area divisions i want? It seems so easy to not include a certain combination of setting in css, and then the different sections of the screen will intersect each other. I want to imagine that one solution would be to create one html body for each area, so that elements of each area would never intersect each other (i know that a document only has one body). Is there a totally different approach than the one shown, or do i have to find just the right (imo. kludgy) css settings, so that i make the visuals work as intented? And if this is the right approach, what kind of css-settings and other settings should i look into?
Comment: Please do *not* screenshot code. You can insert it as text and use the "code" button to have it formatted as such.
Comment: Thank you for the reminder, image is replaced by code.
Answer: Look into CSS grid for the main layout. (Though this can be done with two flex layouts as well.) You can, for example, use grid-template-areas to set up named areas and then position element in them.
Elements intersecting other areas is just an issue of overflow. Either let the individual sections overflow with scroll (auto/scroll) or cut off their contents (hidden).
Comment: Thank you, that solved all current problems! So this is propably the right approach anyways? It's hard to know when you're new to html and css and have never tried all these things.
Comment: Well, I would wrap the section components in another elements and use that for layout. That way the section components do not have to "know" about their surroundings. [Example](https://svelte.dev/repl/92cc2951d6e84172a83eeb14e88941ae?version=3.49.0)
Comment: That's an amazing example, i'll 100% be incorporating that layout technique. Without googling anything, is it easy to make the lines in the grid draggable?
Comment: There is no native method to my knowledge, unfortunately. There are JS libraries for that, which will insert an additional element that e.g. adjusts the relation of the adjacent columns/rows. I have used [`split-grid`](https://github.com/nathancahill/split/tree/master/packages/split-grid) for this before.
Comment: [Example with splitters](https://svelte.dev/repl/e8e97cf1fe694ed7ad13d55118e4e0ec?version=3.49.0)
Comment: This https://github.com/orefalo/svelte-splitpanes would be a Svelte library for splitters
Comment: Thank you guys alot, this is everything i need regarding this topic!


Error on executing qplot in R. Statbin requires continuous variable

Question: I am learning R and was trying to generate some histograms. My data set is called "test" and it has a field called dob which stands for date of birth which I am using on the x-axis. I want to show all values from 1:31 in the x-axis. My command is :
qplot(x = dob_day, data = fb) +
  scale_x_discrete(breaks = 1:31)

I get the following error in the terminal.
Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"?

I read a few SO posts but could not understand.
Comment: `qplot()` with one argument plots a histogram - is that what you are aiming to do? Then simply convert `x` from character/factor to numeric.
Comment: Yes but how to do that
Comment: as.numeric(fb$dob_day), but make sure it returns what you expected - difficult to comment more without seeing the data.
Answer: Just realized what I was doing wrong
It should be scale_x_continuous command not discrete
Answer: "Previously it was used for any discrete variables, whether numerical or non-numerical. Now it is only used for non-numerical discrete variables.
Use scale_x_continuous()"I saw this on Udacity forum


Is a nonzero divisor locally nonzero divisor?

Question: Suppose $X$ is a scheme (or locally ringed space), $a\in \Gamma (X,O_X)$, not a zero divisor. Can we show $a_x$is also a nonzero divisor in $O_{X,x}$?
(It is true if $X$ is an affine scheme)
Comment: It's also true if each $\mathscr{O}_{X, x}$ is flat over $\Gamma (X, \mathscr{O}_X)$.
Comment: This question is essentially answered here: http://mathoverflow.net/questions/73936/the-restriction-of-a-global-section-which-is-not-a-zero-divisor-is-still-an-non
Answer: Let $f\in\Gamma(X,\mathcal{O}_X)$ and let
\begin{equation}
X_f=\{x\in X\mid f_x\in\mathcal{O}_{X,x}^{\times}\}
\end{equation}
because $f_x$ is not a zero divisor in $\mathcal{O}_{X,x}$ if and only if $f_x\notin\mathfrak{m}_x$ that is if and only if $f_x\in\mathcal{O}_{X,x}^{\times}$.
By definition of scheme:
\begin{gather}
\forall x\in X,\,\exists U\subseteq X\,\text{open,}\,R\,\text{commutative ring with unit}\mid x\in U,\\
(U,\mathcal{O}_{X|U})\cong(\operatorname{Spec}R,\mathcal{O}_R)\Rightarrow\mathcal{O}_{X,x}\cong\mathcal{O}_{R,x},
\end{gather}
therefore, fixed the open affine subset $U$ of $X$, we get:
\begin{equation}
r^X_U(f)=g\in\mathcal{O}_X(U)\cong\mathcal{O}_R(\operatorname{Spec}R)=R;
\end{equation}
where $r^X_U$ is the restricting morphism of $\mathcal{O}_X$ from $X$ to $U$.
Because
\begin{equation}
g:x\in\operatorname{Spec}R\to[g]_{\mathfrak{p}_x}\in\coprod_{\mathfrak{p}_x\in\operatorname{Spec}R}R_{\displaystyle/\mathfrak{p}_x},
\end{equation}
then
\begin{gather*}
\{x\in\operatorname{Spec}R\mid g_x\in R_{\mathfrak{p}_x}^{\times}\}=\{x\in\operatorname{Spec}R\mid g\notin\mathfrak{p}_x\}=\\
=\{x\in\operatorname{Spec}R\mid g(x)\not=0_{\mathfrak{p}_x}\}=D_{\operatorname{Spec}R}(g)\cong\operatorname{Spec}R_g;
\end{gather*}
that is
\begin{equation}
X_f\cap U\cong D_{\operatorname{Spec}R}(g),
\end{equation}
or in other words: for any $x\in X_f$ there exists an open affine neighbourhood of $x$ contained in $X_f$, and we can state that $X_f$ is an open subset of $X$.
In particular, if $X$ is an affine scheme then $X_f$ if an its open (affine) subscheme.
From all this: we can not state that, in general, for a nonzero divisor $f\in\Gamma(X,\mathcal{O}_X)$ one has that $f_x\in\mathcal{O}_{X,x}$ is a nonzero divisor for any $x\in X$; but this statement is true for any $x\in X_f$ as constructed before.
Sometimes $X_f$ is called support of $f$.


Bar plot with a few extreme values

Question: Consider the following vector:
vec <- c(-0.137042293280008 ,-0.0085530023889108 ,7.696986350237e-05 ,9.85275557252565e-05 ,0.000246261331270769 ,-0.0013658222244989 ,0.00117046787783182 ,-0.000423648394606887 ,-0.000112607126438433 ,0.00212185051472275 ,-0.000110104526782098)
names(vec) <- paste("var", 1:length(vec), sep = " ")

I would like to plot vec using a bar plot in R. However, as you can see, there is one or two values that are extreme compared to the rest of the vector. When the bar plot is drawn, the small values barely show on the graph.
par(xaxs='i',yaxs='i', mai = c(0.5,2,0.5,1.5))
bp2 <- barplot(vec, horiz = TRUE, col = "lightblue4", border = "lightblue4", yaxt = 'n', cex.axis = 0.7)
axis(2, at = bp2, labels = names(vec), tick = FALSE, las = 2, cex.axis = 0.7)

Is there a way to better display the chart? For example, is there a way to eventually split the x-axis? The graph below is an (unrelated) example, but it shows how the y-axis in this case is split to allow for all values to show on the graph.
P.S: Plotting with a log-scale is not an option in my case, as some of the vector values are negative.

Thank you!
Comment: You may have a look at `gap.barplot` in the `plotrix` package, which basically produces a plot like the lower one.
Comment: Would it be possible to use some other transformation, such as sign(x) * log(abs(x))?
Comment: @ChristopherLouden Unfortunately, no. The interpretation of the graph wouldn't be intuitive.
Comment: [This question](http://stackoverflow.com/questions/19612348/break-x-axis-in-r/19612566#19612566) can be useful for you.
Comment: @Jiber It is helpful indeed. Thanks! However, I am still trying to figure out how to work that function with a bar chart..
Answer: You need gap.barplot from plotrix package. Take a look at this:
library(plotrix)
gap.barplot(vec,gap=c(-0.12,-0.04),xlab="Index",ytics=c(-0.04,-0.02,0),
            ylab="",main="Barplot with gap", horiz=TRUE)

Modify gap and ytics argument to get the desired aesthetic for your plot.

Bar plot with a few extreme values


How to move files out of subdirectories with given extension recursively to a destination-folder?

Question: I want to move all the *.txt files from all the subdirectories located in a given directory to one destination-directory.
When doing it as below, it moves EVERY file - how can I reduce it to all the *.txt files only?
find -type f -print0|xargs -0r mv -it "/path to my folder/destination-directory"

Comment: try: `find . -type f -name "*.txt" -print0|xargs -0r mv -it "/path to my folder/destination-directory"`
Answer: Use a glob pattern with -name option of find to indicate the desired pattern, *.txt in your case:
find . -type f -name '*.txt' -exec mv -t /destination {} +

Of course, replace /destination with the actual destination directory.
Notes:

You don't need to spawn xargs and an anonymous pipe, use the mv logic within the -exec predicate of find
find ... -exec handles all kind of possible filenames and ARG_MAX as well
GNU mv (default in Ubuntu) has -t to take a destination directory, so that you can leverage the + argument of -exec to send all files in single run of mv (or at least minimal runs if ARG_MAX is triggered in the process)
Answer: Add a -name test
find -type f -name "*.txt" -print0 |...

Don't forget to quote the glob to prevent shell expansions.
For case-insensitive search, use -iname instead of -name
Answer: find /folder/ -type f -name "*.txt" -exec mv {} /other/folder/ \;

I tested this, works nicely.
Answer: Using your original command:
find . -type f -name "*.txt" -print0|xargs -0r mv -it /path/to/destination

Info:

.: search in current location
"*.txt": files that have a .txt extension in their names


How to test voltage between neutral and ground

Question: I'm not an electrician.  Per, https://www.apc.com/us/en/faqs/FA158817/, I want to test the outlets in a room for the following:

Overloaded neutral wire (>5 Volts AC measured between Neutral and Ground).
Reversed polarity (hot and neutral wires are reversed).
Missing ground wire. (Note: this also includes using a 3 prong to 2 prong adapter)

I've found simple plug-in devices on Amazon that I'm confident can test for #2 and #3, but what sort of tool do I need for #1, to measure the voltage between Neutral and Ground?
Comment: cheap 3-led testers should test for condition #1 by having the third LED come on.
Answer: A simple multimeter can help you verify all three, as well as many other voltage related troubleshooting.  It's a real must have for... anyone really.
To measure between neutral and ground, you will set the meter to AC voltage, 200V range, and stick one probe into the neutral slot of the socket (the wider slot for USA standard sockets, on the left if the ground hole is on the bottom) and one probe into the ground slot (the D shaped hole).
Comment: you would need to test the voltage between the leg and ground to test #2. Once you've established zero volts between neutral and ground, check the resistance between the two: infinite means no ground, under an ohm or two means it's good.
Comment: If it's not against the rules to extend the question here, how do I test for #2 and #3 using a voltmeter?
Answer: A common digital voltmeter will do everything you need.  Quality should be reasonable since you will be sticking this thing in electric sockets.
You should be wary of the 3-light testers.  While they do provide a simple pass/fail test for most outlets, the legend describing the likely faults for "fail" conditions are misleading and wrong.  Many hours have been wasted because people believed the legend's interpretations of the fault.  I just saw a labeled "hot-ground reverse" which was in fact a lost neutral. (night and day, like reporting a bad fuel injector when the problem is actually a flat tire).
Be doubly wary of anything from Amazon.  Anything to do with mains AC power should be UL-listed (e.g. a responsible testing lab should approve it). Anything you buy at retail (e.g. Home Depot or Target) will meet this standard.  Amazon will not.  Amazon seems like a legit retailer, but they quietly opened the platform to third party sellers. As a result, it is completely flooded with the same junkstream you see on eBay, but in sheep's clothing: gussied up to look like a legit product.
Products which direct-ship from China, or are drop-shipped from China via Amazon's Fulfillment warehouses (e.g. Prime), do an end-run around all the product safety laws.  That may be fine for fidget spinners, but anything that touches mains power can kill you.
Answer: You're going to need a volt meter with test leads and read between the ground point and the neutral point. Most home stores have inexpensive ones that will answer your question but if you're doing this for a living, you'll want to invest in a good/great one. Since you need the meter anyway, you can save yourself a few bucks and not get the plug-in device because the meter will be good for #2 and #3.


Joomla upload zip and run in plesk

Question: I try to host a site in plesk created with joomla.
I have installed joomla from Applications -> Joomla Install.
I can log in to the backend interface and see the general by default joomla template.
However in plesk in Files -> httpdocs where the site exist I have upload my joomla work from my local disk and extract it and their are all my files.
What should I do to configuration.php file in order to make the public url to see the results from the content I uploaded, or in other files?
I mean I have a zip file with the joomla content. I uploaded to http docs and extracted but in the public url I receive error. Why this is happening?
I noticed that index.php was overwriten when I openned the joomla from the application and after that I can't understand what changed.
Answer: Joomla consists of files and a database.
One of the easiest ways to transfer a website is to use the free or paid version of Akeeba Backup which backs up the files and the database into one file. You can then use the free Akeeba Kickstart utility to restore the files and the database on the target location.
Answer: I don't have rep points to comment, which is why this is posted as an answer. Sorry!
Can you give a little more information? You installed Joomla from the Plesk panel, so you should have all of the Joomla code files and directory structure. What is the "joomla work" you want to upload -- a complete site like Neil's answer I think assumed? Graphics files? Text documents? If it's artwork or the like, it would go in your "media" folder under the Joomla document root (httpdocs I would guess), and be accessible through the media manager.

Joomla upload zip and run in plesk


Cant find Google Map Android API v2

Question: I just come to know there is no Google Map Android API v2 available in google developers APIs menu,
http://s30.postimg.org/txz8319g1/image.png
Anybody has any idea what has happened ?
Comment: `Google Map Android API` exists. It is first under `Google Maps API` section.
Comment: I can see that but I need Google Map Android API v2. I had seen that 3-4 days back right there.
Comment: Maybe they just changed a name..
Comment: Yes, you are right @bjiang I implemented Google Map Android API instead of Google Map Android API v2 and it is working fine for me.
Answer: They just changed a name. Implemente Google Map Android API instead of Google Map Android API v2 and it will work fine.

Cant find Google Map Android API v2


Bug on file upload

Question: im developing an application in jsf with primefaces, and i found a bug in fileUpload. When i refresh the page this component
appears distorted
I tried:
1 - remove style an styleClass
2 - remove draganddrop support, remove mode atribute...
3 - put a form inside of dialog instead outside
3 - create component from current context application
The file upload is inside a p:outputPanel > h:form > p:dialog > p:panelgrid
<code>PanelGrid childPanelGrid = (PanelGrid) app.createComponent(PanelGrid.COMPONENT_TYPE);

                    FileUpload fileUpload = (FileUpload) app.createComponent(FileUpload.COMPONENT_TYPE);
                    fileUpload.setId("fileUpload_id");
                    fileUpload.setStyle("height: 230px; overflow: auto; border: 1px solid  #e6e6e6; border-radius: 10px;");
                    fileUpload.setDragDropSupport(true);
                    fileUpload.setLabel("Selecionar documentos");
                    fileUpload.setCancelLabel("Cancelar");
                    fileUpload.setUploadLabel("Enviar");
                    fileUpload.setStyleClass("removeBordaFileUpload");
                    fileUpload.setInvalidSizeMessage("Tamanho máximo do arquivo excedido");
                    fileUpload.setSizeLimit(10000000L);
                    fileUpload.setAllowTypes("/(\\.|\\/)(gif|jpe?g|png|pdf|txt|rtf|doc|docx)$/");
                    fileUpload.setInvalidFileMessage("O formato do arquivo informado não é suportado");
                    fileUpload.setFileUploadListener(createMethodExpression("#{testeSalvarMenu.handleFileUpload}", void.class, FileUploadEvent.class));
                    fileUpload.setUpdate("formTeste:tabview_id:formDocumentos:dataTableDocumentos formTeste:tabview_id:formEnviarDocumentos:dialog_documento_id"); /**Alteracao em relacao ao estatico*/
                    childPanelGrid.getChildren().add(fileUpload);

                    dialogChildPanelGrid.getChildren().add(childPanelGrid);
</code>
When refresh the page i expected this
 https://drive.google.com/open?id=1i_IiAVAKekE1GDza5tvpf3KJBMDHclSN
but when refresh page i got this
https://drive.google.com/open?id=1Vm42u84kONh9Gt2B6PjPXq13JfFzX_4O
Comment: start with reading [mcve]  and [ask] and https://www.stackoverflow.com/tags/jsf/info, but most of all, debug with the browser developer tools (basic webdevelopment thing)
Answer: Found the solution: put a fileupload tag in the xhtml with css atribute visibility: "hidden", only making this can work fine.
Comment: Great you 'solved' it, but this is a very weird solution for an unclear problem. Unless you create a clear [mcve] with the question, the answer is sort of useless.

Bug on file upload


Custom title in embeded pdf

Question: when I embed pdf to html page, I want it to have custom title, not the name of the pdf document. And I can't access it with JS because of shadow DOM.
<embed src="pdfFiles/interfaces.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">

Answer: You cannot access the DOM of a user-agent Shadow DOM, only custom Shadow DOM.
Maybe you can use an alternate way to embed a PDF (without the <embed> tag), like pdf.js from Mozilla.
See this SO question for further detail: Recommended way to embed PDF in HTML

Custom title in embeded pdf


Banshee stops autoplaying, I must manually click on the song to play

Question: When I use banshee I usually shuffle my library of music ~3000 songs mostly in flac. Sometimes it reaches a song and stops playing, it has the song lined up but never plays. I have to manually double click on the song to make it play and everything continues. It won't work if I use the play/pause keyboard shortcut either so it's a bit annoying.
I've run it in debug mode and there are not warnings and errors. Can anyone point me in the right direction.
Answer: Do you have gapless playback enabled? Try disabling it, that worked for me.
See https://bugs.launchpad.net/ubuntu/+source/banshee/+bug/917035
paul


Strange behaviour executing query on postgresql

Question: I'll try to explain what happend to me without pasting every single piece of my code because it's a lot.
If I run this query alone it returns 6.0 (the expected behaviour)
select distancia_euclediana_para_imagenes(vector_cuadrante1,
                       vector_cuadrante2,
                       vector_cuadrante3,
                       vector_cuadrante4,
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)])
from imagen,pivotes
where id=id_imagen and indice_pivote=2

and if I run this other query it returns 2 (again the expected behaviour)
with distancia_a_pivote(distancia) as
(select distancia_euclediana_para_imagenes(vector_cuadrante1,
                       vector_cuadrante2,
                       vector_cuadrante3,
                       vector_cuadrante4,
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)])
from imagen,pivotes
where id=id_imagen and indice_pivote=2)
select id from imagen, indice, distancia_a_pivote d
where id=id_imagen  and
fqa[2]>= 6-1 and
fqa[2]<= d.distancia+1;

However, with this little change it stops working and returns nothing
with distancia_a_pivote(distancia) as
(select distancia_euclediana_para_imagenes(vector_cuadrante1,
                       vector_cuadrante2,
                       vector_cuadrante3,
                       vector_cuadrante4,
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)],
                       ARRAY[SQRT(8),SQRT(8)])
from imagen,pivotes
where id=id_imagen and indice_pivote=2)
select id from imagen, indice, distancia_a_pivote d
where id=id_imagen  and
fqa[2]>= d.distancia-1 and
fqa[2]<= d.distancia+1;

I'll be grateful if you could help me because I have no idea what can cause this issue. Besides I've been coding in a TDD style, so I have tests to prove the right behaviour and I was pretty it was going to work
Thanks
Comment: What is `fqa[2]`? The integer 5 perhaps?
Comment: yes, do you have an idea what could be wrong?
Answer: You say that fqa[2] is the integer 5 and d.distancia is the floating point value 6.0. That means that you end up looking at this:
5 >= 6.0 - 1

That 6.0 probably isn't exact so 6.0 - 1 could come out a shade less than 5.0 and your comparison would fail. One solution is to add a little bit wiggle room to account for the usual floating point problems:
fqa[2] >= d.distancia - 1.00001 and
fqa[2] <= d.distancia + 1.00001

The 0.00001 is just an example, you'd need to look at your situation to see how much extra you should allow. Adding ceil and floor calls might be another option as they would give you better control over the floating point to integer conversion.


Sprite sheet generator for iPhone?

Question: Until now I have been making my own 1024*1024 sprite sheets by placing the images in an 64 x 64 grid to help to identify easily the position and size of each sprite.
Needless to say, it works but i'm wasting a lot of space.
Is there any  kind of tool to help me take separate sprites in .png format and generate sprite sheets of any dessired size with them ?. even better if it also generates a file with information about size and coordinates of each sprite.
Thanks.
Answer: I read about Zwoptex in Michael Daley's book Learn iOS Game Programming.
http://zwoptexapp.com
Answer: Is something like CATiledLayer what you need? I does not contain info about each tile, but it is the way maps and large zoom functionality is usually implemented.
Answer: There are a number Ruby implementations on github. While they generate CSS and or HTML, it would be possible to take these one stage further and convert it into an XML file. Would make a nice little tool...
Answer: Here's a simple texture packer in Python.
Answer: You can use Sprite Master to do this. It's trimming feature allows you to use minimal space for your sprite sheet. It also exports coordinate data for your sprite sheet in different formats (Generic XML, Cocos2D, Corona, LibGDX, Sparrow, CSS Export)
Answer: There is also texturepacker from codeandweb.com
http://www.codeandweb.com/texturepacker

Sprite sheet generator for iPhone?


How do I Host an Online Minetest Server?

Question: I want to host a minetest server on my computer, but I don't know how.
So basically, I just want to know how to, in layman's terms, how to host a server that would run off of my internet service.  That way I can decide what settings and mods are on.
Comment: Are you having an issue with something specific?  They have an official [wiki on server setup](https://wiki.minetest.net/Setting_up_a_server).
Comment: Basically I wanted layman's terms of how to create a server other people can join using my personal internet service.
Comment: Your best bet is probably to follow a tutorial, like the one in the wiki linked above or try finding a [video on YouTube](https://www.youtube.com/results?search_query=minetest+server+setup).  If you run into a specific problem, feel free to ask a new question, and you can always post an answer to this yourself if you think it'd be helpful for others.
Answer: The easiest solution I've found is to use Docker.
I hosted a few Minetest servers using LinuxServer.io's Docker image. All the info on how to run them is here: https://hub.docker.com/r/linuxserver/minetest
I've run them without issues for about three years even on really cheap VPS servers with less than 1GB of RAM (but for 2-3 players).
You have the option to simply run using Docker CLI, but I prefer using docker-compose, as I sometimes have more Minetest servers on the same machine.
Recently I noticed that there's an official set of Minetest Docker images that you could try.


How to manually add Sims 3 to Origin Launcher when already installed?

Question: I installed Sims 3 a few years ago and I didn't play it for a year, so Origin needed to update. I also needed to log in to my Origin account, but I don't know my email, password or ID anymore, so I made a new one, but that account doesn't have Sims 3 in the launcher. Since it was already installed earlier, I can add this manually, but I don't know which file I should pick to launch the game.
Edit: When I search in The Sims 3\Game\Bin, this is what I get, I know it's not Sims3, that's the icon. I'm Dutch, so everything on the picture will be in Dutch.
Answer: I dont have Sims 3 installed at the moment, but it works the same way as other Origin games. The file you want is the .exe file.
The game folder is located under (as default): C:\Program Files (x86)\Origin Games
Once you are in the Sims 3 game folder look for an .exe file called Sims3 (or similar). That's the file that launches the game.
Hope this answer was of any use. If you have any questions leave a comment.
Comment: Yes, I know that, but the problem is, there are many .exe files and I don't which one.
Comment: @WoutHuygens can you take a screenshot?
Comment: Added it to my question.
Comment: It's the one simply called Sims3


Julia - How to know what is the latest version (v1.0.0) equivalent function?

Question: I previously used ismatch function in Julia v0.6.0 but now it returns an error with v1.0.0 and it's not present in the v0.7.0 or v1.0 documentation. So how can I find the non depreciated equivalent of ismatch for latest Julia version ?
More generally in Julia, how is it possible to know the equivalent of any depreciated function if it exists ?
I only have Julia v1.0 installed on my computer.
Comment: You may call the deprecated function *once* in v0.7. It should give you deprecation warning and ideally a solution.
In addition, you can instead look up [v0.7.0 Release Notes](https://docs.julialang.org/en/v0.7.0/NEWS/)  to find news about the deprecated functions. For example, `ismatch(regex, str)` has been deprecated in favor of `contains(str, regex)`. There is a catch though, `contains` has also been deprecated: "`contains` has been deprecated in favor of a more general `occursin` function, which takes its arguments in reverse order from `contains`."
Answer: When it comes to porting old v0.6 code to v1.0, it is generally recommended to use v0.7. Typically, it will show you a deprecation warning with instructions on how to get the same result in v1.0.
For example, we can run code involving ismatch as follows (on Julia v0.7):
julia> ismatch(r"a.c", "abc")
┌ Warning: `ismatch(r::Regex, s::AbstractString)` is deprecated, use `occursin(r, s)` instead.
│   caller = top-level scope at none:0
└ @ Core none:0
true

According to the deprecation warning, we should replace all calls to ismatch(r::Regex, s::AbstractString) with occursin(r, s) for future compatibility. In the case that deprecations occur throughout a project, Julia (v0.7) may be started using the --depwarn=error flag, which will immediately error (and provide detailed information about location) upon calling a deprecated method.
Note that deprecations are defined in base/deprecations.jl. You can check this file on github or locally to see what function 0.7 is mapping the deprecated method to.
(Note that there is also a function match in v1.0, which one gets as a suggestion when doing ?ismatch on 1.0.)
Comment: Thank you, that helped, however, the link in the original answer from @crstnbr [`deprecated.jl`](https://github.com/JuliaLang/julia/blob/release-0.7/base/deprecated.jl#L1287) (click it!) was useful and I don't think it sould be edited
Comment: For reference, https://github.com/JuliaLang/julia/blob/master/HISTORY.md lists most important changes between v0.6 and v0.7, most of which remain valid in v1.0 (has saved me several times!)


Why Trace and the main diagonal of a matrix are distinguished

Question: Let $A$ be a square $n \times n$ over a field (say $\mathbb{R}$ or $\mathbb{C}$). As we know, the main diagonal $(a_{1,1},...,a_{n,n})$ is important in linear algebra while the off-diagonal is far less important. The deep question is why?
We try to test it using the trace, which lies heavily on the main diagonal of a matrix.
Recall that the trace is defined as
$$ \operatorname{Tr}(A) := \sum_{i=1}^n a_{i,i} \ .$$
We know that it is a good operator, in the sense it is invariant under matrix conjugation (matrix similarity: $B = M A M^{-1} \Rightarrow \operatorname{Tr}(A) = \operatorname{Tr}(B)$).
Let us look on the symmetry group $S_n$ of $n!$ permutations. Let us define a more general trace: let $\sigma \in S_n$ then
$$ \operatorname{Tr}_{\sigma}(A) := \sum_{i=1}^n a_{i,\sigma(i)} \ . $$
Note that $\operatorname{Tr}(A) = \operatorname{Tr}_{\operatorname{id}}(A)$
I checked on few examples that $\operatorname{Tr}_{\sigma}(A)$ is not generally invariant under matrix conjugation. The question is why?
My thought is that it is due to the fact $\operatorname{Tr}(A) = \operatorname{Tr}_{\operatorname{id}}(A)$ and that $\operatorname{id} \in S_n$ is the unit element of the group $S_n$ and hence a distinguished element. However, I did not managed to show how this fact implies that the trace is invariant under matrix conjugation while $\sigma$-trace is generally not. What I did managed to show is that
$$ \operatorname{Tr}_{\sigma}(AB) \ne \operatorname{Tr}_{\sigma}(BA) $$
unless $\sigma = \operatorname{id}$. I think this implies that the $\sigma$-trace isn't invariant under conjugation (as $\operatorname{Tr}(MAM^{-1}) = \operatorname{Tr}(AM^{-1}M) = \operatorname{Tr}(A)$).
I want to connect between the deep fact the the identity is the unit element of $S_n$ to the fact the only the $\sigma$-trace $\operatorname{Tr}_{\operatorname{id}}(A)$ is invariant under matrix conjugation.
Comment: Is it possible to write your $\sigma$-trace in a form like tr$_\sigma A = $ tr${P_\sigma A}$ where $P_{\sigma}$ is an appropriate permutation matrix? If so, that'd give a natural explanation of why it only is cyclic if $\sigma=$id.
Comment: While this is just an idea, you could maybe think of some properties which are useful for the trace to have, and then see if these are enough to characterize the trace completely up to a scalar multiple (just like how volume forms are the determinant up to a scalar). This probably requires some idea as to what the trace means geometrically though - from Wikipedia it says "Geometrically, the trace can be interpreted as the infinitesimal change in volume (as the derivative of the determinant)", so that might help.
Comment: I think yes (I checked it for $2 \times 2$ and $3 \times 3$ examples, but havn't prove it). This actually show that $Tr(P_\sigma AB ) \ne Tr(P_\sigma BA)$ which I showed explicitly using index notation. However, this explains while $Tr_{id}$ is the only good trace but don't explain why the main diagonal is distiguished.
Answer: Let $M$ be an invertible matrix. Let $m_k$ me the $k^{th}$ row of $M$, $n_k$ the $k^{th}$ row of $M^{-1}$ and $a_k$ the $k^{th}$ column of $A$.
Then the $k^{th}$ row of $MA$ is $(m_k\cdot a_1,\dots, m_k\cdot a_n)$. Thus $(MAM^{-1})_{kk}=(m_k\cdot a_1,\dots, m_k\cdot a_n)\cdot n_k$. Hence $$\text{tr}(MAM^{-1})=\sum_{k=1}^n (m_k\cdot a_1,\dots, m_k\cdot a_n)\cdot n_k=\sum_{k=1}^n \sum_{i=1}^n\sum_{j=1}^n m_{ki}a_{ij}n_{jk}=\sum_{i=1}^n\sum_{j=1}^n a_{ij}\sum_{k=1}^n m_{ki}n_{jk}$$ while for each $k$ by definition $\sum_{k=1}^n m_{ki}n_{jk}=\delta_{ij}$. From this we get the result.
But notice that if we apply this argument to $\text{tr}_\sigma(MAM^{-1})$ the same calculation will go through except $\sum_{k=1}^n m_{ki}n_{j\sigma(k)}=\delta_{ij}$ will not hold unless $\sigma(k)=k$ for all $k$. But there's only one element in $S_n$ that does this!
Comment: $Tr(XY)=Tr(YX)$, take $X=MA$, $Y=M^{-1}$ then
$$ Tr(MAM^{-1})=Tr(XY)=Tr(YX)=Tr(M^{-1}MA)=Tr(IA)=Tr(A) \  .$$
Comment: That works too!


How to install Light Fixtures - no ground in the ceiling box

Question: I am trying to install a lighting fixture that I bought from Ikea.  The ceiling box has one black, one white, one blue, and one yellow lines (as in the photo below).  But, I cannot find a ground line in the box.   Can anyone explain how I can connect the ground line in the lighting fixture?  Also, I would like to use a switch to turn on and off the lighting, but I'm not sure which hot wire I should use. I guess it may be blue or yellow.
Thank you!
Answer: If you don't know, get an electrician. Your life and property are at stake.
I could make some educated guesses here but if you followed them, had a problem, and I found out about it, I'd feel bad.
Answer: There should be a bare ground wire up in the box somewhere. Connect the green wire to that.
The lamp black goes to yellow.
The lamp white goes to white.
The little double white goes to your bulb.
The black and the blue in the yellow wire nuts are just pass throughs not used for the light.
Comment: You cannot be entirely sure of the function of any of those wires without testing.
Comment: Sorry, except for the ground. bare or green pretty much always means ground (in the US)