text:
Q: BackgroundDownloader The system cannot find the file specified I'm using C# and Windows Phone 8.1 as Universal.
I Have an issue with BackgroundDownloader. when I start a downloader, it gave me an exception:
Downloading http://localhost/MySong.mp3 to MySong.mp3 with Default priority, a95c00db-738d-4e22-a456-dc30d49b0a3b

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Exception: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

here is my code:
        private void downladButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            PumpUrl(txtUrl.Text);
        }
        async void PumpUrl(string url)
        {
            if (!string.IsNullOrEmpty(url) && CheckUrl(url))
                StartDownloadMethod(url);
            else
                await new MessageDialog("Looks like URL is invalid.\r\nPlease check your URL and try again"").ShowAsync();
        }
        public bool CheckUrl(string URL)
        {
            Uri source;
            if (Uri.TryCreate(URL, UriKind.RelativeOrAbsolute, out source))
                return true;
            else
                return false;
        }
        public void StartDownloadMethod(string url, string fileName = null)
        {
            StartDownload(url, BackgroundTransferPriority.Default, false, fileName);
        }

        private async void StartDownload(string url, BackgroundTransferPriority priority, bool requestUnconstrainedDownload, string fileName = null)
        {
            Uri source;
            if (!Uri.TryCreate(url.Trim(), UriKind.RelativeOrAbsolute, out source))
            {
                Debug.WriteLine("Invalid URI.");
                return;
            }

            string destination = null;

            if (string.IsNullOrEmpty(fileName))
                try
                {
                    destination = System.IO.Path.GetFileName(Uri.UnescapeDataString(url)).Trim();
                }
                catch { }
            else
                destination = Uri.UnescapeDataString(fileName).Trim();

            if (string.IsNullOrWhiteSpace(destination))
            {
                Debug.WriteLine("A local file name is required.");
                return;
            }

            StorageFile destinationFile = null;
            try
            {
                if (vars.localType == LocalType.SDCard)
                    destinationFile = await KnownFolders.RemovableDevices.CreateFileAsync(
    "Downloads\\Test App\\" + destination, CreationCollisionOption.GenerateUniqueName);
                else
                    destinationFile = await KnownFolders.MusicLibrary.CreateFileAsync(
"Test App\\" + destination, CreationCollisionOption.GenerateUniqueName);
            }
            catch (FileNotFoundException ex)
            {
                Debug.WriteLine("Error while creating file: " + ex.Message);
                return;
            }
            catch (Exception ex) { Debug.WriteLine("Error while creating file: " + ex.Message); }

            if (destinationFile == null)
                return;

            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download = downloader.CreateDownload(source, destinationFile);

            Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}",
                source.AbsoluteUri, destinationFile.Name, priority, download.Guid));

            download.Priority = priority;
            Add(url, destination, download);
            if (!requestUnconstrainedDownload)
            {
                // Attach progress and completion handlers.
                await HandleDownloadAsync(download, true);
                return;
            }

            List<DownloadOperation> requestOperations = new List<DownloadOperation>();
            requestOperations.Add(download);

            UnconstrainedTransferRequestResult result;
            try
            {
                result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations);
            }
            catch (NotImplementedException)
            {
                Debug.WriteLine(
                    "BackgroundDownloader.RequestUnconstrainedDownloadsAsync is not supported in Windows Phone.");
                return;
            }

            Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Request for unconstrained downloads has been {0}",
                (result.IsUnconstrained ? "granted" : "denied")));

            await HandleDownloadAsync(download, true);
        }

        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                Debug.WriteLine("Running: " + download.Guid);
                bool bb = false;
                foreach (DownloadOperation item in DownloadDB.activeDownloads)
                {
                    if (item != null && item.Guid == download.Guid)
                    {
                        bb = true;
                        break;
                    }
                }
                if (!bb)
                    DownloadDB.activeDownloads.Add(download);

                Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
                CancellationTokenSource cts = new CancellationTokenSource();
                AppendCancellationTokenSource(download, cts);

                if (start)
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                else
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);

                ResponseInformation response = download.GetResponseInformation();

                DownloadDB.RemoveChildByGuid(download.Guid.ToString());
                DownloadDB.SaveDB();
                Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
                    download.Guid, response.StatusCode));

            }
            catch (TaskCanceledException taskCanceled)
            {
                Debug.WriteLine("TaskCanceledException: " + download.Guid + "\t" + taskCanceled.Message);
                DownloadDB.RemoveChildByGuid(download.Guid.ToString());
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception: " + ex.Message);
            }
            finally
            {
                DownloadDB.RemoveChildByGuid(download.Guid.ToString());
                DownloadDB.activeDownloads.Remove(download);
            }
        }

I used my code in other application 3 month ago and it works fine but in this application dosent work. Where I wrong?
Thanks


text:
Q: cannot check in; \packages\EntityFramework.6.1.3\EntityFramework.6.1.3.nupkg: The server returned content type text/plain, which is not supported I am trying to check in my code, but I keep getting this error;
\packages\EntityFramework.6.1.3\EntityFramework.6.1.3.nupkg:
The server returned content type text/plain, which is not supported.

How do I fix this?

A: I found the problem was that there was a setting on Sophos that excluded this file. When that was fixed, then no problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating pivot table is not working I'm trying to create a VBA script to create a Pivot Table, but unfortunately it isn't working.
The whole script is as follows:
Sub SeparateBrandNonBrand()
'
' Last Months Data Summary
'
'
   Dim PT                     As Excel.PivotTable
   Set PT = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
                                              "2013-10-28!R1C1:R200000C20", Version:=xlPivotTableVersion1).CreatePivotTable( _
                                              TableDestination:="'Data-Summary'!R1C1", TableName:="PivotTable1", _
                                              DefaultVersion:=xlPivotTableVersion1)
   With PT
      With .PivotFields("Sites")
         .Orientation = xlRowField
         .Position = 1
      End With
      With .PivotFields("campagin")
         .Orientation = xlColumnField
         .Position = 1
      End With
      .AddDataField .PivotFields("visits"), "Sum of visits", xlSum
   End With

End Sub

But specifically at run time the script complains that the following part of the code is invalid (invalid procedure call or argument).
Set PT = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
                                                  "2013-10-28!R1C1:R200000C20", Version:=xlPivotTableVersion1).CreatePivotTable( _
                                                  TableDestination:="'Data-Summary'!R1C1", TableName:="PivotTable1", _
                                                  DefaultVersion:=xlPi

votTableVersion1)

Does anyone have any ideas as to what may be going wrong?

A: One thing that may result in this error
Version:=xlPivotTableVersion1 & DefaultVersion:=xlPivotTableVersion1
Try recording a macro to capture the correct version, in my case, 14


text:
Q: Getting the error "Unable to infer complex closure return type; add explicit type to disambiguate" when trying to recreate the SwiftUI List demo I'm trying to recreate the SwiftUI demo with a difference being I want to use my own object Item.
Item:
class Item {

    var company: String = ""
    var item_class: String = ""
    var name: String = ""
    var stock: Int = 0
    var average_cost: Decimal = 0.00
    var otc_price: Decimal = 0.00
    var dealer_price: Decimal = 0.00
    var ctc_price: Decimal = 0.00

    class var _API_LIST_EP: String {return "api/inventory/items/"}

    // Init and Funcs
    // JToken is an extended typealias for [String : Any] that makes parsing easier
    required init(_ jt: JToken) {
        company = jt.string(forKey: "company")
        item_class = jt.string(forKey: "item_class")
        name = jt.string(forKey: "name")
        stock = jt.int(forKey: "stock")
        average_cost = jt.decimal(forKey: "average_cost")
        otc_price = jt.decimal(forKey: "otc_price")
        dealer_price = jt.decimal(forKey: "dealer_price")
        ctc_price = jt.decimal(forKey: "ctc_price")
    }

}

In a similar question, it was noted that the issue stemmed from one of the object's variables being initialized in an ambiguous state however after filling up all of my object's variables, it still comes up
Problematic code:
struct ContentView : View {

    var itemList: [Item] = []
    var body: some View {
        List(itemList) { item in
            Image(systemName: "photo")
            VStack(alignment: .leading) {
                Text(item.name)
                Text(item.company)
                .font(.subheadline)
                .color(.gray)
            }
        }
    }
}

Screenshot of the error:

A: The error message is misleading.
List(itemList) { item in ... }

requires that the element type of itemList conforms to the Identifiable protocol. For classes (as in your case) it is sufficient to declare protocol conformance
class Item: Identifiable {
   // ...
}

because there is a default implementation (based on the object identifier).


text:
Q: TestFlight to App Store transition I just want to know the process from TestFlight to the App Store like
Once my app is visible in the TestFlight of iTunes Connect:

*

*When and how will it be moved to the App Store for being LIVE?

*Apps, once uploaded, are automatically visible in the TestFlight app, when will this be removed: after 180 days, or 90 days, or when the app is live?

*When does the reviewing process start? The moment app is uploaded to TestFlight, or when it is promoted by someone for LIVE?

*Who promotes the build for LIVE?

A:

*

*When and how will it be moved to the App Store for being LIVE?

When the developer is confident the version is ready to go live, he/she just submits the TestFlight build (or a newer one with fixes) like a regular app update. Apple has to review it again (even if you use the same build as for TestFlight) and after approval it will go live.

*Apps, once uploaded, are automatically visible in the TestFlight app, when will this be removed: after 180 days, or 90 days, or when the app is live?

The standard testing period is 90 days, so after that, the app will disappear, but (IIRC) if that version of the app goes live, that ends the availability in TestFlight as well.

*When does the reviewing process start? The moment app is uploaded to TestFlight, or when it is promoted by someone for LIVE?

When the app is uploaded to TestFlight for an alpha test (by users which also have access to the iTunes Connect backend), no review takes place (except for some automated integrity checks). For a beta test via TestFlight, a short (manual) review is conducted by Apple, but nowhere near as rigorous as for an app going live. Again, the "going live"-review is a separate review.

*Who promotes the build for LIVE?

This is part of the process described under 1.


text:
Q: Draw edges through nodes in Graphviz I am trying to draw a graph using Graphviz in Dot language, and this graph has edges which runs through nodes.
Please see the attached picture below.
So far I did not able to find a way to do this. Any help would be highly appreciated!.
Thanks in advance. ( Tips on any other way to render a graph like this would also be really helpful )

A: The information above is not that sufficient, however you can check the Drawing with Constrained ranks (Ref: Drawing graphs with dot by "Emden Gansner and Eleftherios Koutsofios and Stephen North").
Graph with constrained ranks
Please read the below for more information :Drawing graphs with dot

A: Had the same issue today, this worked for me in layout=dot.
(1) setting splines to false
(2) have the specific edge attribute constraint set to false, for edges which must go through another node.
splines=false
x -> y [constraint=false]

Be aware it only worked OK because I did not use a label for the edge.
Using the edge attributes taillabel and headlabel worked for me.


text:
Q: How does sed and read line works in shell? I have tried to search it but still doesnt understand on what it does.
In our code, sed is use as this:
var1 = $(sed /s/date/date01/g << EOF1
$var1
EOF)

and read line is use as this:
/src/path | grep  -E "String" | while read line
do {
.... some functions to do.
}

I'm very confused on how it works.

A: This is the usage of here document. '<< EOF1' treats everything before next EOF1 as input of command sed.
In your code, sed replaces('s') every('g') 'date' with 'date01' from input which is the value of variable var1. But I suppose it is a typo that the slash before 's' is redundant. And no space should among =.


text: Q: Deleting /usr/loca/pgsql before reinstalling postgres I've uninstalled postgres by running make uninstall and make clean and I want to reinstall it using homebrew this time, however, I noticed that my /usr/local/pgsql directory is still there.  Should I delete this before doing a homebrew postgres install?


text:
Q: how to automatically loop through colors using Random() by simply click a button Am doing a simple application, whereby when the user clicks on the button. the background color will keep changing to different colors using the Random(). how can i implement that ? here is my code
if (looper == false)
{
    Jbutton1.setText("loop now ");
    int color;
    Random rnd = new Random();
    color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),                             rnd.nextInt(256));
    JmyScreen.setBackgroundColor(color);
    looper = true;
}
else
{
    Toast.makeText(getApplicationContext(), "stop loop",Toast.LENGTH_SHORT).show();
    Jbutton1.setText("stop looping");
    JmyScreen.setBackgroundColor(Color.WHITE);
    looper = false;
}

A: Here the background of the button getting changed periodically after every 4 seconds.Here you pass the id of your background and check it is work for you or not.
Hope this helps :)
public class MyActivity extends Activity {

        private Runnable mEndlessRunnable;

        @Override
        public void onCreate(Bundle savedState) {
            super.onCreate(savedState);
            setContentView(R.layout.my_activity);

            mEndlessRunnable = new UpdateRunnable(new Handler(), new Button[] {
                (Button) findViewById(R.id.button_1),
                (Button) findViewById(R.id.button_2)
            });
            mEndlessRunnable.run();

        }

        private static class UpdateRunnable extends Runnable {

            private Random mRand = new Random();
            private Handler mHandler;
            private Button[] mButtons;

            private Button mCurButton;
            private int mState;

            public UpdateRunnable(Handler handler, Button[] buttons) {
                mHandler = handler;
                mButtons = buttons;
            }

            public void run() {
                // select a button if one is not selected
                if (mCurButton == null) {
                    mCurButton = mButtons[mRand.nextInt(mButtons.length)];
                }
                // check internal state, `0` means first bg change, `1` means last
                switch (mState) {
                case 0:
                    mCurButton.setBackgroundResource(R.drawable.blue_bg);
                    mState = 1;
                    break;
                case 1:
                    mCurButton.setBackgroundResource(R.drawable.yellow_bg);
                    // reset state and nullify so this continues endlessly
                    mState = 0;
                    mCurButton = null;
                    break;
                }

                mHandler.postDelayed(this, 4000);
            }
        }
    }


text:
Q: how to apply joins against my table **when user enter coutry america and course master than select country and institute/university name from institute table if the university offer master course than select its course(master) from degree table institute_id is foreign key in degrees table:
Institute Model
protected $table = 'institutes';

protected $fillable = [
    'user_id','email', 'contact', 'country','about','name','city'

];

public function degree()
{
    return $this->hasMany('App\Degree','institute_id');

}

Degree Model
  protected $table = 'degrees';

protected $fillable = [
    'institute_id','description', 'course', 'fees','session','education_req'

];

**  link for the site to understand the problem more clear in this site if you enter country america for master than it shows all the unviserity of america who  offer master degree **
link


text:
Q: How to delete top n rows by group in dplyr This should be easy, but when I run:
require(dplyr)
data.frame(a = c(1,1,1,2,2,2), b= c(1,2,3,4,5,6)) %>%
group_by(a) %>%
slice(-1:-2)

expecting data.frame(a = c(1,2), b = c(3,6)),
I receive the following error:
Error in UseMethod("slice") :
  no applicable method for 'slice' applied to an object of class "c('grouped_df', 'tbl_df', 'tbl', 'data.frame')"

Not much to add really - by all accounts and answers on here, this should be the correct solution. Can anyone help?

A: It could be an issue stemming from masking of the slice function from other packages when those packages are also loaded.  e.g. if we use the xgboost::slice
data.frame(a = c(1,1,1,2,2,2), b= c(1,2,3,4,5,6)) %>%
  group_by(a) %>%
  xgboost::slice(-1:-2)

Error in UseMethod("slice") :    no applicable method for 'slice'
  applied to an object of class "c('grouped_df', 'tbl_df', 'tbl',
  'data.frame')"

Instead specify the dplyr::slice
data.frame(a = c(1,1,1,2,2,2), b= c(1,2,3,4,5,6)) %>%
  group_by(a) %>%
  dplyr::slice(-1:-2)
# A tibble: 2 x 2
# Groups:   a [2]
#     a     b
#  <dbl> <dbl>
#1     1     3
#2     2     6

Or do this in a fresh session with only dplyr loaded


text:
Q: Describe Interim Table and Basic Concept behind it? Hy Everyone...
Can anyone describe me what is interim table in sql Server 2008? what is the basic concept and structure behind it.
thanks in advance.

A: Interim table is a table that is generated by joining two tables and not the final result table. In other words, when two tables are joined they create an interim table as resultset but the resultset is not final yet.
Check this link for examples


text:
Q: How to make a record read-only in a Django form? Using Django 1.6.5, I have a case where I want to make a particular record read-only after comparing it with some pattern in an inline formset.
Is it possible to do this?

A: You can do it using jquery. This is the way at clientside if suitable for you.
You can get value of form fields using id generated by form like(abc_1, abc_2 etc)
then you can compare it with some value and apply css ('disable',true) to specific field using id.

A: Yes, it is possible by using parent model form init method sample code:
class VForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(VForm, self).__init__(*args, **kwargs)

        if self.instance.field == 'Y':
            self.fields['field2'] = forms.ChoiceField(
                choices=[(self.instance.field,
                          self.instance.field),], required=True)

This will filter the choice field restricted to only 1 choice, and a blank to select from .In above case 'N' as one of the choice fields is suppressed.
Same is the case for model fields also.


text:
Q: Longest duration that can be specified with xsd:dayTimeDuration() I have a simple question: what is the longest / "infinite" duration that can be specified using xsd:dayTimeDuration() (in the ISO8601 format)?
Thanks,
M.

A: The W3C XSD specification doesn't restrict/specify the maximum value for an xs:dayTimeDuration:

The values of the Year, Month, Day, Hour and Minutes components are
  not restricted but allow an arbitrary unsigned integer, i.e., an
  integer that conforms to the pattern [0-9]+.

However, a particular implementation may impose its implementation-dependent limits.
For example, Saxon allows this value:
xs:dayTimeDuration('P999999999DT2H30M10S')

but raises an error on this value (one more 9-digit added to the days component):
xs:dayTimeDuration('P9999999999DT2H30M10S')

FORG0001: Invalid duration value 'P9999999999DT2H30M10S' (non-numeric
  component)

XQSharp allows a bigger value  -- this is accepted:
xs:dayTimeDuration('P999999999999999999DT2H30M10S')

But one digit more in the days component raises an error:
xs:dayTimeDuration('P9999999999999999999DT2H30M10S')

FODT0002: Underflow or overflow in construction of 'dayTimeDuration' in namespace 'http://www.w3.org/2001/XMLSchema' from value 'P9999999999999999999DT2H30M10S'.

Both of these two XPath implementations allow much bigger value-space than would be practically needed -- just take into account that the age of the Universe is estimated at not more than 14 billion years, which is 5124000000000 days.
XQSharp allows for durations considerably bigger than the age of the Universe, while the maximum Saxon allows is just slightly less than the age of the Universe.


text:
Q: R programming: Dataframe Subset Returning Inconsistent Results I am having this problem in R.  I have been scratching my head for 2 days.
If a did
list.of.genes.common.to.Group1.and.Group2<-intersect(Group1df, Group2df)

a <- unlist(list.of.genes.common.to.Group1.and.Group2)

#if I don't unlist, then I get nothing

b <- Group1df[rownames(Group1df) %in% a,]

c <- Group2df[rownames(Group2df) %in% a,]

dimensions of b and c are NOT the same, yet the list a was generated from the length of the list common to both...
b is about 200 short and c is about 300 short.
What is the deal?


text:
Q: Unexpected parsing of Timestamps reading pandas dataframe from .csv file I have a pandas dataframe read from a csv file which includes a column of dates
In[1]: df = pd.read_csv(fileStats, index_col=0, parse_dates= ['start_date'])

In[2]: df.head()
Out[3]:
                 start_date
    customer_ID
    10006414       2012-10-02 08:30:00
    10006486       2013-12-02 09:00:00
    10006492       2013-12-02 09:00:00
    10006572       2012-03-31 08:30:00
    10006630       2012-01-06 10:30:00

I want to find the earliest date:
In[4]: df['start_date'].min()
Out[5]:
Timestamp('2011-01-12 08:00:00')

which looks fine except that when I open the .csv file in excel, and order the rows by start_date, the earliest date is 2011-10-06 13:00:00. The same problem happens with .max()  This post refers to a similar problem, but related to np.datetime64 which I am not using here. Is there an issue with .max() and .min() or is it to do with parsing the dates in .read_csv ?
EDIT:
Further investigation on suggestions from @DYZ shows that the Timestamps have been read or parsed incorrectly.  6/10/2011 13:00 in the .csv file has become 2014-03-03 10:00:00 in the dataframe. How to correct this?


text:
Q: Heroku add-ons 'Logentries' & 'FlyData' query I have a Ruby on Rails web app hosted on Heroku and I've setup Logentries add-on which sets up alarms for 'High Response Time'.
Lately, I have started getting emails for 'ALERT High Response Time', which mention that the high response time was triggered for
heroku router - - at=info method=GET path="/robots.txt"
Now, I know that Search Engines like Google, Microsoft use the robots.txt to ignore the pages that should not be indexed. Is there any other reason, why this file would be accessed?
Please correct me if I am missing something here.
Oh, and I am using the free version of Heroku i.e. 1 worker for website-content and I have 1 worker which runs periodic jobs using the Scheduler.
Query #2-
What's wrong with my application, when I get the following email from Logentries, with subject - 'ALERT Exit Timeout'
Exit timeout: Heroku/my-app
2014-10-13 18:53:56.351
188 <45>1 2014-10-13T18:53:56.053533+00:00 heroku web.1 - - Error R12 (Exit timeout) -> At least one process failed to exit within 10 seconds of SIGTERM
Query #3-
I also installed the FlyData add-on trial to see how it works. I get emails with the subject - '[FlyData-Alert] (myapp) Application Error notification'.
The email says-
We noticed the following error logs on your application (myapp) :
2014-10-08T23:59:53.042662+00:00 app[scheduler.3266]: ** [NewRelic][10/08/14 23:59:53 +0000 21fd815f-5e08-42ab-80d8-4771ea1593c7 (2)] INFO : Installing Rails3 Error instrumentation
I think this email is triggered because of the INFO message from New Relic, which says - Installing Rails3 Error instrumentation. The FlyData add-on probably looks at the keyword 'Error' and triggers the email alert.

A: For Query #2:  Heroku - Exit timeout: Heroku/my-app
According to Heroku's documentation,
"A process failed to exit within 10 seconds of being sent a SIGTERM indicating that it should stop. The process is sent SIGKILL to force an exit."
There is a complete list of Heroku Errors codes, including this one, that can be found here: https://devcenter.heroku.com/articles/error-codes#r12-exit-timeout
If you're using webrick to run your application on Heroku, you should try to switch to using 'thin' to see if that helps: See https://devcenter.heroku.com/articles/rails3#webserver.
or see the previous answer on stackoverflow here:
Rails app hosted on heroku: Error R12 (Exit timeout)
Hope this helps.
Michael


text:
Q: Exchange 2010 queue viewer not working in Exchange Management console I recently agreed to help my works network admin with the exchange 2010 server (seeing as I have experience in 2016 which were migrating to at the end of the year), but when trying to administer it, I get this message. This happens when I try to open queue viewer, or message viewer. I have the same exchange privileges that the network admin has but when he tries there is no issue. I also can not run a handful of cmdlets in the exchange management shell. Unless there is a certain privilege I do know about I don't know the issue. Any help?

A: Alright after a lot of digging I found out that Active directory groups is not the same as exchange server roles. So to fix this you have to go to your EMC -> toolbox -> Role Based Access Control User Editor -> log in then options -> See all options -> Manage my organization -> Roles and Auditing -> then add yourself (or have an admin) to Organization Management role. Simple but annoying.


text:
Q: mongo is not recognized as internal or external command inspite of installing mongodb ,my mongo command showing that "mongo isn't recognizable as internal or external command"
though i have set the path variable mongod and mongosh is working but when I m trying to go for mongo then it hasn't happening


text:
Q: How to use an  tag  inside a  in the middle of a text? I want to do something like this:

This is a
text
 paragraph.

I disabled margin and padding for the h2 but it still breaks the line before and after the h2 tag. How can I use the h2 tag in the middle of a text and make it look like if it was a normal word, just like  does?
The doctype of my html document is "XHTML 1.0 Transitional"

A: It is not valid to have a h2 inside of a p.
Aside from that, and to answer your question, a h2 is a block level element. Making it an inline level element will cause it to behave similarly to how you describe the b tag acting.
p h2{display:inline}

As I said above though, the HTML you've given is invalid.

A: Don't, the whole point of  is that it's a header. Headers are on their own line.  Instead, use CSS.  Say text and then in a CSS file, choose a font size.

A: It's not appropriate to use a tag that means "heading" within body text. The <h..> tags are logical tags; their use imparts meaning to the enclosed text -- namely, that the text is a section heading.
Although you could use the display: inline attribute, consider using a more appropriate tag, or even a  tag.

A: You'll have to make it
display:inline;

h2 is a block element.
The h2 tag marks a headline, which is per definition not part of a text. So what you're doing is probably not the best way. Consider doing it differently.

A: Despite of the wrong use of the
 tag inside a paragraph, we can style
 to keep him into a paragraph. I tested one of the above css trick in Firefox and Chrome as follow:
HTML code
One paragraph with
title text
 in the middle

CSS trick p h2{display:inline}
BUT it doesn't get the result I expect. The browser truncate the paragraph right before the initial h2 tag. Look at DOM from Firebug:

Therefore the CSS trick p h2{display:inline} doesn't work properly because CSS rule is not true, i.e. the
 tag is not inside the
 tag. It looks like this:

Adding CSS trick only for
 tag h2{display:inline} is not the definitive solution. It will look like this:

The final work-around is:
HTML code
One paragraph with
title text
 in the middle

CSS trick .inline-object" {display:inline}
This will look as we expect:

If you are trying to mask
 title text as ordinary text, just add two more rules to the class .inline-object" {display:inline;font-size: inherit;font-weight: normal;}

A: Create a class like .myH2 (not the best name) with same code of h2 and use a span in p like

this is myH2.

A: Firefox cutting out my P, because of H2 inside it. And then creating P for  (empty paragraph). And its good. Because its auto-generated, and for cleaning out P tags i need to write tens of PHP code.


text:
Q: Why smoothScrollTo inside onTouchEvent does not work when I do Scroll? On the next code:
hScroll.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_UP) {
                hScroll.smoothScrollTo(20, 0);
            }
            return false;
        }
}

When I only touch the HorizontalScrollViewit works, but if I move the scroll it doesn't. Someone can help me? (Sorry for my poor English)

A: When you touch , it includes two actions , MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP. If you want the same result when scrolling, you should change like this
if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_UP) {
    hScroll.smoothScrollTo(20, 0);
}


text:
Q: Is JupyterHub kernel safe across users? I'm using JupyterHub to share computational power of a big computer among some users. The software that's primarily used is a ctypes extension Python script that uses a sophisticated C/C++ code. This code isn't invulnerable to memory problems and crashes.
My question is: If a low-level problem happens with one user and his kernel gets, say, a segmentation fault, will that crash the main server by design and get all users to lose their kernel information? Or is it designed to create a new server for every user that logs in, so that such problems don't happen?

A: Even if you were using straight Jupyter Notebook instead of JupyterHub, each kernel is a single process, that runs kind of independent of the notebook server. Crashes of individual kernels will not take down the notebook server.
Check out the architecture documentation. We've been running a setup with a single Jupyter Notebook instance (not even JupyterHub, because Windows :/) for about 3 years now. The only problems occuring are due to resource constraints (e.g. single kernel takes up a lot of memory), but that's solvable on both the OS and organisational level.


text:
Q: Programa que dado un nombre y apellidos, me convierta las iniciales en mayúsculas en Java Estoy aprendiendo String methods, y hasta ahora he conseguido aislar las iniciales, pero no consigo que sean mayúsculas. Seguro que es una tontería y me estoy complicando demasiado. Gracias.
    Scanner sc = new Scanner(System.in);

    System.out.println("Escribe tu nombre y apellidos:");
    String nombreApellidos = sc.nextLine();

    String[] iniciales = nombreApellidos.split(" ");

    for (int i = 0; i < nombreApellidos.length(); i++) {
        System.out.println(iniciales[i].charAt(0));
    }
}

A: Para convertir una letra en mayúscula puedes usar el método toUpperCase de la clase String
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Escribe tu nombre y apellidos:");
        String nombreApellidos = sc.nextLine();

        //creamos un String en la cual iremos concatenando cada letra leida
        String iniciales="";

        for (int i = 0; i < nombreApellidos.length(); i++) {
            //La primera letra es mayúscula
            if(i==0)iniciales=iniciales+nombreApellidos.toUpperCase().charAt(i);
            else
                //Si encontramos un espacio concatenamos a iniciales
                //convertimos mayúscula el caracter después del espacio vacio
                //aumentamos i en 1 para que no nos vuelva a leer el mismo caracter
                if (nombreApellidos.charAt(i) == ' '){
                    iniciales=iniciales+nombreApellidos.charAt(i);
                    iniciales=iniciales+nombreApellidos.toUpperCase().charAt(i+1);
                    i++;
                }
                else
                    iniciales=iniciales+nombreApellidos.charAt(i);
        }
        System.out.println("\n Nombres y Apellidos con primera letra en Mayúscula");
        System.out.println(iniciales);
    }

Salida
Escribe tu nombre y apellidos:
jose luis brañez chavez

 Nombres y Apellidos con primera letra en Mayúscula
Jose Luis Brañez Chavez

A: Intenta con esto, es más legible y fácil de entender, dejé algunos comentarios para que comprendas el funcionamiento.
Scanner sc = new Scanner(System.in);
System.out.println("Escribe tu nombre y apellidos:");
String nombreApellidos = sc.nextLine();

nombreApellidos = nombreApellidos.trim().replaceAll(" +", " ");// elimina espacios de más y deja solo uno entre cada palabra
String[] iniciales = nombreApellidos.split(" ");
String resultado = "";

for (int i = 0; i < iniciales.length; i++) {//recorre cada palabra separada por espacio

    char inicial = iniciales[i].charAt(0);
    //reemplaza las iniciales por mayusculas y las va almacenando
    resultado  += iniciales[i].replace(String.valueOf(inicial), String.valueOf(Character.toUpperCase(inicial)))+ " ";
}
System.out.println(resultado);//imprime el resultado final


text:
Q: How to update MySQL Row at a later time? LANGUAGES USED:

*

*Python

*Python Web Browsing with Mechanize

*Python HTML Parsing with BS4

*MySQL (later)

OVERVIEW:
I want to be able to track when a user logs on and logs off of a game server.
Like
ID, username, activty, loggedin, loggedoff
example:
1,archer,online,11-24-2015 05:10:11,11-24-2015 12:10:11
Using this data I want to then make a website that shows a chart of the most common times a particular player is online, the best time to play (when the most players are online) etc.
The ONLY data I am using to figure all this out is a "Who's Online" list published on the game's website.
So what I've done is I've written a python script that checks the list every 1minute (filters out all the HTML with BS4 and dumps to a text file of users online 1 per line), and it is able to figure out who signed on and who signed off by comparing to the list of the previous minute.
Now for the problem I am trying to figure out:
THE PROBLEM:
Currently the script just dumps the newly-online or newly-offline users to a text file.
I need to update a MySQL database like I said above instead.
I can google around and figure out how to get python to update the database everytime some comes online - just create a new row, auto increment the ID, put in the username, and a timestamp for when they signed on.
BUT I have no idea how I would be able to later, go and update that row to add the Logged Off time. How would I know what row to update?
There will be multiple rows with the same username, because a new row will be added for each logon/logoff session ! I know it will probably have to be found by the ID but how would I keep track of that?
Thanks!!!!!
What I have:
 # IMPORT WEB BROWSER
import mechanize

# IMPORT HTML PARSER
from bs4 import BeautifulSoup, NavigableString, Tag

# FOR TIME CALCS
from datetime import datetime, timedelta, date

# FOR RENAMING FILES
import os

# FOR SLEEP
import time

# FOR TIMESTAMPS
import datetime

# Used for timestamps when writing to database [DB not used yet]
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

###############################################################
# BEGIN NEVER ENDING LOOP THAT SLEEPS 1 MINUTE BETWEEN CYCLES #
###############################################################
# This will eventually be removed and will run as a 1min cronjob when ready

while True:

    #########################################
    # SETUP MECAHNIZE TO USE AS WEB BROWSER #
    #########################################

    br = mechanize.Browser()
    br.set_handle_equiv(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

    ###########################################
    # GET "WHO'S ONLINE?" LIST FROM GAME SITE #
    ###########################################

    try:
        # User-Agent
        br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko')]
        r = br.open('http://en.war2.ru/wp-content/themes/war2.ru/lib/server-stats.php')
        page = r.read()
        soup = BeautifulSoup(page)
        user_list = soup.find_all('div', class_='status-list')
    except:
        print "ERROR: Connection failed. Retrying ..."
        continue

    #################################################
    # ERASE USERS ONLINE THIS MINUTE FROM LAST TIME #
    #################################################
    with open("users-on-this-minute.txt", "w") as f:
        f.close()

    #########################################################
    # FILTER OUT HTML AND GIVE A PLAIN LIST OF USERS ONLINE #
    #########################################################
    for br in user_list:
        users = br.findAll('br')

        for br in users:
            next = br.nextSibling
            if not (next and isinstance(next,NavigableString)):
                continue
            next2 = next.nextSibling
            if next2 and isinstance(next2,Tag) and next2.name == 'br':
                text = str(next.encode('latin1')).strip()
                if text:
                    output = next[1:].encode('latin1')

                    ####################################################
                    # PRINT EACH ONLINE USER TO TEXT FILE ONE PER LINE #
                    ####################################################
                    file = open("users-on-this-minute.txt", "at")
                    print >>file, str(output)
                    file.close

        ############################
        # CREATE NEWLY ONLINE LIST #
        ############################
        # Creates the Newly Online list by checking the users logged on now
        # against the users logged on a minute ago. If there is a user logged on
        # now who wasn't on a minute ago, he is added to newly online

        with open("users-on-previous-minute.txt", "r") as f:
            check_online = f.readlines()
            new_online = set() # holds lines already seen
            outfile = open("users-newly-online.txt", "w")
            for line in open("users-on-this-minute.txt", "r"):
                if line not in check_online: # not a duplicate
                    new_online.add(line)
            outfile.writelines(sorted(new_online))
            outfile.close()
            f.close()

        #############################
        # CREATE NEWLY OFFLINE LIST #
        #############################
        # Creates the Newly Offline list by checking the users logged on now
        # against the users logged on a minute ago. If there was a
        # user logged on a minute ago but not now, he is added to newly offline

        with open("users-on-this-minute.txt", "r") as f:
            check_offline = f.readlines()
            new_offline = set() # holds lines already seen
            outfile = open("users-newly-offline.txt", "w")
            for line in open("users-on-previous-minute.txt", "r"):
                if line not in check_offline: # not a duplicate
                    new_offline.add(line)
            outfile.writelines(sorted(new_offline))
            outfile.close()
            f.close()

        #############################################################
        # COPY CURRENT MINUTE LIST TO BECOME "PREVIOUS" MINUTE LIST #
        #############################################################
        # We are done using the list from the previous minute, and now we write
        # the current minute's list to become "previous minute" for next loop

        with open("users-on-this-minute.txt", "r") as f:
            lines = f.readlines()
            with open("users-on-previous-minute.txt", "w") as f1:
                f1.writelines(lines)
                f1.close()
            f.close()

        print "Sleeping for 1 minute ..."
        time.sleep(60)

A: I believe you are making this a bit too complicated.  The following is the gist of your question:

BUT I have no idea how I would be able to later, go and update that row to add the Logged Off time. How would I know what row to update?
There will be multiple rows with the same username, because a new row will be added for each logon/logoff session! I know it will probably have to be found by the ID but how would I keep track of that?

Since you have the username, all you have to do is update the row that doesn't have a log off time for that username.
"UPDATE logtable SET logouttime = NOW() WHERE username = " + username + " AND logouttime IS NULL"

When you set the database up the default value for logouttime will be NULL.


text:
Q: Springfox-Swagger2 406 not acceptable error -Spring 4 Hi I am getting "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers" error i.e Http 406 not acceptable.
I am using the below dependencies for swagger
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.0.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.8.4</version>
</dependency>

<dependency>
    <groupId>com.wordnik</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.3-M1</version>
</dependency>

My swagger config file is as below
@EnableSwagger2
@Component
public class SwaggerConfig {

    @Bean
    public Docket swaggerSpringMvcPlugin() {

        ArrayList<ResponseMessage> standardExpectedHttpResponses =
                createStandardExpectedHttpResponses();

        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.GET,
                        standardExpectedHttpResponses)
                .globalResponseMessage(RequestMethod.POST,
                        standardExpectedHttpResponses)
                .globalResponseMessage(RequestMethod.PUT,
                        standardExpectedHttpResponses)
                .globalResponseMessage(RequestMethod.DELETE,
                        standardExpectedHttpResponses)
                /*.globalOperationParameters((List<Parameter>) new ParameterBuilder()
                        .name("xyz=id")
                        .description("Description of someGlobalParameter")
                        .modelRef(new ModelRef("string"))
                        .parameterType("query")
                        .required(true)
                        .build())*/
                .produces(createStandardProducesConsumes())
                .consumes(createStandardProducesConsumes()).pathMapping("")
                .select()
                .apis(RequestHandlerSelectors
                        .basePackage("com.x.y.z"))
                .paths(PathSelectors.ant("/*"))
                .build().apiInfo(metadata());
    }

    private ApiInfo metadata() {

        return new ApiInfoBuilder()
                .title("API - xyz")
                .description(
                        "This is a Swagger-enabled API representation for the xyz.")
                .version("1.0").build();
    }

    private ArrayList<ResponseMessage> createStandardExpectedHttpResponses() {
        ArrayList<ResponseMessage> messages = new ArrayList<ResponseMessage>();

        messages.add(new ResponseMessage(200, "Ok", null));
        messages.add(new ResponseMessage(400, "Bad Request", null));
        messages.add(new ResponseMessage(401, "Unauthorized", null));
        messages.add(new ResponseMessage(403, "Forbidden", null));
        messages.add(new ResponseMessage(404, "Not Found", null));
        messages.add(new ResponseMessage(500, "Internal Server Error", null));

        return messages;
    }

    private HashSet<String> createStandardProducesConsumes() {
        HashSet<String> producesConsumes = new HashSet<String>();

        producesConsumes.add("application/json");

        return producesConsumes;
    }
}

Also CORS filter is setup for the project. Anything is missing ? How do i resolve this.
When i hit the service it is giving me the response. It is working fine. I dont have to add any request parameters. Above link is giving me the response.
When I hit http://localhost:8080/endpoint/v2/api-docs, I have the http 406 error. Do i need to add any annotations to my service ?

A: I have commented below code in my Servlet. It started working.
<util:map id="mediaTypesMapping">
      <!--   <entry key="text/plain" value="text/plain;charset=UTF-8" />
        <entry key="text/html" value="text/html;charset=UTF-8" />
        <entry key="application/json" value="application/json;charset=UTF-8" />
        <entry key="application/xml" value="application/xml;charset=UTF-8" />
        <entry key="jsonp" value="application/javascript" />
        <entry key="application/javascript" value="application/javascript" />
        <entry key="application/x-protobuf" value="application/x-protobuf" /> -->
        <entry key="application/json" value="application/json" />
    </util:map>

My Service URL is
http://localhost:8080/endpoint
My Swagger UI is adding param name to URL. How do i change this ?
URL produced by my swagger UI is after passing query param
http://localhost:8090/rendpoint?allRequestParams=q%3Did%3A*%26fl%3Did


text: Q: Hello, I was wondering if it was possible to create a copy and pasting tool? This is purely a hypothetical question, but I was wondering if it would be possible to program something that would work similar to how traditional copying and pasting works, for example what language would be used and what functions of that language would be implemented? Thank you!


text:
Q: How do optimise the performance of Remmina? I have installed Remmina on my Oneiric Ubuntu laptop for home RDP access to my work Windows 7 PC.
This works, I can access my work PC etc...however the performance is not what I had hoped.
I am using the default settings for Remmina, and after researching through Google I have set my mouse pointers option on tehe windows 7 box to none.
Can any one else offer any advise on how to configure Remmina prefernces to optimise the performance please?
Thank you

A: AFAIK Remmina uses FreeRDP as its RDP backend. Since FreeRDP is under heavy development the FreeRDP version (0.8.2-2build1) in 11.10 may not be as optimized as the development versions from the FreeRDP homepage.
For high-performance (kind of) RDP connections to Windows 7 (or other RDP servers) I use rdesktop (command line) with the following settings:
rdesktop -a 16 -z -x m -P SERVERNAME


text:
Q: Should I be worried about "Ubuntu experienced internal error on restart" errors? Whenever I restart I get an ubuntu experienced internal error asking for details shows the crash is located in usr/bin/xorg.
Should I be worried about this? So far I have not found out what is affected by this crash. It's at the very least annoying so I would like to fix this. If it matters I run on a elitebook 8570w.

A: This has been going on for a while?  Occasionally is seems something gets stuck in the apport system and needs to be cleared out.
Open a terminal (press alt+ctrl+t)
In the terminal type the following commands
cd /var/crash
sudo rm -r *
exit

Please be very sure you are in the /var/crash directory before you execute the 'rm' command.  What we are doing is removing the crash reports from you system - if there is an error still going on, a new crash report will be generated.


text:
Q: How to correctly use fwrite? So I have a char* called bufptr that is of size 512. Within the first couple of spots is the name of the file that I will be reading from and everything else after that is data.
ex. char* bufptr = {'f', 'o', 'o', '.', 'c', '\0', ...}
I did not initialize it like that but that is the general idea
After this I store the name of the file into a different file using strcpy
ex.
auto int i = 0;
while(*bufptr != '\0')
{
    fname[i++] = *bufptr;
    bufptr++;
}
bufptr++;

After that, I open up the file
What I am having problems with is the fwrite portion.
I tried writing fwrite(bufptr, 1, 512 - strlen(destString), fp)
but instead of
// ============================================================================
// File: fcclient.c (Fall 2017)
// ============================================================================

I got þ================================================
How would I correctly call fwrite so that I don't run into this issue or is it because I am not skipping over the null? Or does string have something before or after the null?
edit:
I added a loop to check over bufptr and got this as the output
fcclient.c▒▒▒▒▒▒▒▒▒▒id▒.N=▒C▒h▒▒▒.8▒▒l▒ ▒ ▒▒▒`▒ ▒P▒▒▒H▒
▒`▒djd▒▒dd▒▒@▒
▒@▒(▒d▒p▒▒jd▒▒▒▒▒Бd▒=======================================================================
// File: fcclient.c (Fall 2017)
// ============================================================================
// This program is a file transfer client. The user at the keyboard is pread a total of 1 bytes

this was the loop I used
auto int t = 0;
for(; t < 512; t+=)
   if(*(bufptr + t) != '\0')
     printf("%c", *(bufptr + t));

Here is the server code
#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
#include    <unistd.h>
#include    <sys/types.h>
#include    <netinet/in.h>
#include    <sys/socket.h>

// prototypes
int     CopyFile(int  src_sock);

// defined constants
#define BUFLEN              512
#define SERVER_PORT         50004
#define TRUE                1
#define FALSE               0

// function prototypes
int     CopyFile(int  src_sock);

int     main(void)
{
    auto    char                buf[BUFLEN];       // local buffer
    auto    socklen_t           client_addr_size;  // used for call to accept
    auto    int                 client_socket;     // used for call to accept
    auto    int                 server_socket;     // used for call to socket
    auto    struct sockaddr_in  client_address;    // used for call to accept
    auto    struct sockaddr_in  server_address;    // used for call to bind

    // greet the user
    puts("Welcome to fcserver!");
    puts("Waiting to recieve file from client...");

    // create a socket for the server
    server_socket = socket(AF_INET, SOCK_STREAM, 0);

    // prepare the socket address structure for the server
    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(SERVER_PORT);

    // bind the server socket to an address, using the address structure
    if(bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)))
    {
        perror("server -- bind failed");
    }

    // put the server socket into a listening state
    if(listen(server_socket, 5))
    {
        perror("server -- bind failed");
    }

    // let stdout know the server is waiting for a connection
    puts("server waiting...");

    // wait for an actual client connection (this will block)
    client_addr_size = sizeof(server_address);
    client_socket = accept(server_socket, (struct sockaddr*) &server_address, &client_addr_size);

    CopyFile(client_socket);

    // close the client and server sockets
    close(client_socket);
    close(server_socket);

    return 0;

}  // end of "main"

int     CopyFile(int  src_sock)
{
    auto    char                        buf[BUFLEN];
    auto    char                        *bufptr;
    auto    char                        fname[BUFLEN];
    auto    FILE*                       fptr;
    auto    int                         num_client_bytes;
    auto    unsigned long               total_bytes = 0;

    if(-1 == (num_client_bytes = recv(src_sock, bufptr, BUFLEN, 0)))
        perror("server -- recv failed");

    strcpy(fname, bufptr);;
    auto int t = 0;
    for(; t< num_client_bytes; t++)
    {
        if(*(bufptr + t) != '\0')
            printf("%c", *(bufptr + t));
    }

    fptr = fopen(fname, "w");

    auto  int i = strlen(fname) +1;
    bufptr += i;
    total_bytes = fwrite(bufptr, sizeof(bufptr), 1, fptr);
    printf("read a total of %lu bytes \n", total_bytes);

    // loop and read the rest of the file from the client
    do  {

        if(num_client_bytes == 0)
            break;

        printf("read a total of %d bytes \n", num_client_bytes);

        total_bytes += fwrite(buf, 1, num_client_bytes, fptr);

        } while (TRUE);

    fclose(fptr);

    printf("there were a total of %lu bytes written \n", total_bytes);

    return TRUE;

}  // end of "CopyFile"

Here is the client file
  // ============================================================================
// File: fcclient.c (Fall 2017)
// ============================================================================

#include    <sys/types.h>
#include    <sys/socket.h>
#include    <stdio.h>
#include    <stdlib.h>
#include    <sys/un.h>
#include    <unistd.h>
#include    <string.h>
#include    <netinet/in.h>

#define BUFLEN          256
#define SERVER_PORT     50004

int     main(void)
{
    auto    char                buf[BUFLEN];       // general purpose buffer
    auto    int                 server_socket;     // used for server socket
    auto    struct sockaddr_in  server_address;    // used for server address
    auto    char                fname[BUFLEN];     // used for filename
    auto    char                *bufptr;           // used for heap block
    auto    FILE                *fptr;             // used for input file
    auto    int                 result;            // used to check return values
    auto    long                fileSize;          // used to store file size

    // greet the user
    puts("Welcome to fcclient!");

    // get the filename from stdin
    printf("Please enter in the filename: ");
    scanf("%s", fname);

    // open the input file
    fptr = fopen(fname, "r");
    if(fptr == NULL)
    {
        printf("Sorry there was an error trying to locate the file. Please exit and try again \n");
        return 0;
    }

    // get the size of the file
    fseek(fptr, 0, SEEK_END);
    fileSize = ftell(fptr);
    fseek(fptr, 0, SEEK_SET);

    // allocate a buffer to store the file in heap memory
    bufptr = malloc(sizeof(char) * fileSize);

    // create a socket to connect with the server
    server_socket = socket(AF_INET, SOCK_STREAM, 0);

    // setup a socket address structure to target the server
    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(SERVER_PORT);
    server_address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    printf("Currently connecting to server... \n");

    // connect to the server
    if(-1 == connect(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)))
        perror("client -- connect failed");

    // send the filename to the server (include the NULL!)
    if(-1 == send(server_socket, fname, BUFLEN, 0))
        perror("client -- send failed");

    // read the file into the allocated buffer
    fseek(fptr, sizeof(bufptr),SEEK_SET);
    if(0 == fread(bufptr, sizeof(bufptr), fileSize, fptr))
    {
        printf("There was an error sorry. \n");
        return 0;
    }

    // send the data to the server
    if(-1 == send(server_socket, bufptr, fileSize, 0))
            perror("client -- send failed");

    // close the input file and the sockets
    fclose(fptr);
    close(server_socket);

    return 0;

}  // end of "main"

A: bufptr is not pointing to the content of the buffer,Because of bufptr += strlen(destString) , Its pointing to the location next to the content. Update the value of bufptr to point to the content you actually want to write.

A: There are two sets of problems in the code (some of them diagnosed in comments made to question).  First, you write a full length buffer even though it contains mostly junk, and then you try to interpret that as part of the file, but it isn't.  And second, you're playing with an uninitialized variable in the client file copy code — you're (un)lucky it didn't crash.
This code works.
fcserver.c
#include    <stdio.h>
#include    <stdlib.h>
#include    <string.h>
#include    <unistd.h>
#include    <sys/types.h>
#include    <netinet/in.h>
#include    <sys/socket.h>

#define BUFLEN              512
#define SERVER_PORT         50004

void    CopyFile(int src_sock);

int     main(void)
{
    socklen_t client_addr_size;
    int client_socket;
    int server_socket;
    struct sockaddr_in server_address;

    puts("Welcome to fcserver!");
    puts("Waiting to recieve file from client...");

    server_socket = socket(AF_INET, SOCK_STREAM, 0);

    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(SERVER_PORT);

    if (bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)))
    {
        perror("server -- bind failed");
    }

    if (listen(server_socket, 5))
    {
        perror("server -- bind failed");
    }

    puts("server waiting...");

    client_addr_size = sizeof(server_address);
    client_socket = accept(server_socket, (struct sockaddr *)&server_address, &client_addr_size);

    CopyFile(client_socket);

    close(client_socket);
    close(server_socket);

    return 0;
}

void     CopyFile(int src_sock)
{
    char buf[BUFLEN];
    char fname[BUFLEN];
    FILE *fptr;
    int num_client_bytes;
    unsigned long total_bytes = 0;

    if (-1 == (num_client_bytes = recv(src_sock, fname, BUFLEN, 0)))
    {
        perror("server -- recv failed");
        exit(1);
    }

    printf("File name: [%s]\n", fname);
    fptr = fopen(fname, "w");
    if (fname == 0)
    {
        perror(fname);
        exit(1);
    }

    while ((num_client_bytes = recv(src_sock, buf, BUFLEN, 0)) > 0)
    {
        printf("read a total of %d bytes\n", num_client_bytes);
        total_bytes += fwrite(buf, 1, num_client_bytes, fptr);
    }

    fclose(fptr);

    printf("there were a total of %lu bytes written\n", total_bytes);
}

That's 85 lines, instead of 170-odd lines.
fcclient.c
#include    <sys/types.h>
#include    <sys/socket.h>
#include    <stdio.h>
#include    <stdlib.h>
#include    <sys/un.h>
#include    <unistd.h>
#include    <string.h>
#include    <netinet/in.h>

#define BUFLEN          256
#define SERVER_PORT     50004

int     main(void)
{
    int server_socket;
    struct sockaddr_in server_address;
    char fname[BUFLEN] = "";
    char                *bufptr;
    FILE                *fptr;
    size_t fileSize;

    puts("Welcome to fcclient!");

    printf("Please enter in the filename: ");
    scanf("%s", fname);

    fptr = fopen(fname, "r");
    if (fptr == NULL)
    {
        printf("Sorry there was an error trying to locate the file. Please exit and try again \n");
        return 0;
    }

    fseek(fptr, 0, SEEK_END);
    fileSize = ftell(fptr);
    fseek(fptr, 0, SEEK_SET);

    bufptr = malloc(sizeof(char) * fileSize);

    server_socket = socket(AF_INET, SOCK_STREAM, 0);

    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(SERVER_PORT);
    server_address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    printf("Currently connecting to server... \n");

    if (-1 == connect(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)))
        perror("client -- connect failed");

    if (-1 == send(server_socket, fname, BUFLEN, 0))
        perror("client -- send failed");

    fseek(fptr, 0, SEEK_SET);
    if (fileSize != fread(bufptr, sizeof(char), fileSize, fptr))
    {
        printf("There was an error sorry. \n");
        return 0;
    }

    if (-1 == send(server_socket, bufptr, fileSize, 0))
        perror("client -- send failed");

    fclose(fptr);
    close(server_socket);

    return 0;
}

That's 68 lines instead of 170-odd lines.
Testing
It is crucial to run the server in a different directory from the client, else you could get files truncated.  However, when I used a sub-directory junk containing a file animals19.c and ran the client in that directory, while the server ran in the parent directory, I got the output:
server window
$ ./fcserver
Welcome to fcserver!
Waiting to recieve file from client...
server waiting...
File name: [animals19.c]
read a total of 512 bytes
read a total of 292 bytes
there were a total of 804 bytes written
$

client window
$ ../fcclient
Welcome to fcclient!
Please enter in the filename: animals19.c
Currently connecting to server...
$ ls -l animals19.c ../animals19.c
-rw-r--r--  1 jleffler  staff  804 Dec 13 00:42 ../animals19.c
-rw-r--r--  1 jleffler  staff  804 Dec  3 21:54 animals19.c
$ diff animals19.c ../animals19.c
$

Oh, and at some point, you should note "i before e except after c" (so it is receive and not recieve).  You should also note that perror() prints an error; it does not exit.  Continuing after using perror() is usually wrong.


text:
Q: How to go from one fragment to another fragment by click on menu item I want to move from the fragment I am in by the add (+) item to the add fragment.
How do I switch between fragments in the menu?enter image description here
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.student_list_menu,menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId() == R.id.addStudentFragment){
        Log.d("TAG","ADD...");
        return true;
    }else {
        return super.onOptionsItemSelected(item);
    }
}

Menu view

A: just use navigation component and navigate
 @Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.student_list_menu,menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId() == R.id.addStudentFragment){
        Log.d("TAG","ADD...");
findNavController(HERE YOUR FRAGMENT ID YOU WANT TO NAVIGATE)
        return true;
    }else {
        return super.onOptionsItemSelected(item);
    }
}


text:
Q: Create a custom Task.WhenAll() in java? I've been trying to port bits of a project of mine from C# to Java (more accurately, from .NET Core 3 to Android 5.0), one of these bits relies heavily on the TPL (lots of async/await, spawining many tasks, etc...), and I couldn't get the performance I wanted usaing a simple ConccurrentQueue<T> and a bunch of threads polling from it.
So I embarked on the foolish journey of building my own small TPL for java, and I think I succeeded in the fundamentals (Task lifecycle, global and thread-local Task queues, building a Task that can 'await', etc...), however I am stuck at replicating C#'s Task.WhenAll() efficitiently.
Right now, I implemented it with a normal task that simply returns IDLE until all of the other tasks it can wait for are over, however this task sits in the task queue for potentially very long periods of time, consuming an entire Thread that could otherwise Wait() without draining the device battery.
I had an idea of creating* an ad-hoc thread that would specifically wait for all the waiting tasks completed signal, thus avoiding putting the waiting task in any queue.
However this 'solution' has the potential problem that there could be easily tens or hundreds of threads waiting, if my Task.WhenAll() is used frequently (which it is).
I have been looking through the .NET documentation on the TPL looking for some implementation details (tho no source code for .NET Core/5, as this project will not be MIT-compatible), with little luck.
If anyone can help in any way, I'd be super grateful!
Also, if I've missed a library/utility comparable to .NET's TPL in Android 5, feel free to let me know.
*: of course, such threads would be saved and re-used if necessary, with the usual timeouts when there's no work for them.


text:
Q: Sort object array with objects that are not quite the same using two different sort conditions /*
        I have two people
*/

var person_one= 'person_one';
var person_two= 'person_two';

/*
    This is a response I get from a server
*/

var response = [
{"key":{"name":"person_one","kind":"attrA","path":["attrA","person_one"]},"data":{"q":"3","n":"0"}},
{"key":{"name":"person_one","kind":"attrB","parent":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"path":["attrA","person_two","attrB","person_one"]},"data":{"some_data":"p"}},
{"key":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"data":{"q":"1","n":"0"}}
];

/*
    Sort the object array by the key.kind field. So all attrA will come first and then attraB
*/

function compare(a,b) {
  if (a.key.kind < b.key.kind )
    return -1;
  else if (a.key.kind  > b.key.kind)
    return 1;
  else
    return 0;
}

response.sort(compare); //sort

console.log('Sorted response = ' + JSON.stringify(response) ); //print sorted response

This is the code I have so far. What is happening is I get a response from the server which is:
[
{"key":{"name":"person_one","kind":"attrA","path":["attrA","person_one"]},"data":{"q":"3","n":"0"}},
{"key":{"name":"person_one","kind":"attrB","parent":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"path":["attrA","person_two","attrB","person_one"]},"data":{"some_data":"p"}},
{"key":{"name":"person_two","kind":"attrA","path":["attrA","person_two"]},"data":{"q":"1","n":"0"}}
]

I need to now sort this response using two following conditions:

*

*The first condition is to sort it by the key.kind attribute which the code does. All attraA will need to show first, then attraB

*The second condition is after this is sorted by key.kind it then needs to sort it by name. So that person_one will always come before person_two (these are just fake names to show the concept, but actual names could be like jack or jill, etc). So I am able to sort by key.kind, but I am unsure how to add a second sort condition now and sort it by it. If this was SQL it would be similar to something such as this: SELECT * FROM table ORDER BY KIND,NAME; -- sort by KIND first then NAME

A: Let's assume your server response is stored within array people. Then you can use the Array sort() method with a user defined compare function:
people = people.sort(function(a, b) {
    if (a.key.kind != b.key.kind) return a.key.kind > b.key.kind;
    else return a.key.name > b.key.name;
});


text:
Q: Java: String not printed I am reading some data from a file and each line is assigned to one cell of the String array. For some reason when I try to print the array after reading the file(lines 8-10), I get nothing printed. When I print the line in the While loop(line 5) I get the line printed correctly.
    1: int count = 0;
    2: String[] s = new String[300];

    3: while(!StdIn.isEmpty()) {
    4:  s[count]=StdIn.readLine();
    5:  System.out.println(s[count]);
    6:  count++;
    7: }

    8:  for(int i=0;i<count;i++) {
    9:   System.out.println(s[i]);
   10: }

Same code using Scanner:
    Scanner in = new Scanner(System.in);

    int count = 0;
    String[] s = new String[300];

    while(in.hasNextLine()) {
        s[count]=in.nextLine();
        System.out.println(s[count]);
        count++;
    }
    for(int i=0;i<count;i++) {
        System.out.println(s[i]);
    }

I can't figure out what's wrong with my code.
Thanks in advance.
EDIT: When the last line has been read, the in.hasNextLine() is not returning anything. It got stuck at the count++. See photo -> DEBUGGER

A: 8:  for(int i=0;i<count;i++) {

here your error, this should be s.length instead of count

A: This will only work with a file but when using System.in here the in.hasNextLine() never gives false. You need to provide it with a condition to break the while loop.


text:
Q: python function does not seem to be looping correctly I wrote a function that asks the user some information. At the end of the task it will prompt the user to make sure if its correct. If yes or y then the function should continue. If else it should repeat the questions. I cant figure out why the function stops regardless of what the user enters:
157 def runAllfunctions():
158 #       getAccessSecretName()
159         mcIPNumber()
160         makeNameMCTag()
161         makeTfvars()
162         makeMainTF()
163         Provisioners()
164         Resources()
165         Outputs()
166
167
168 def runTerraform():
169         getAccessSecretName()
170         infoCorrect = raw_input('Is the information above correct? (y or n)')
171         if infoCorrect.lower() == "yes" or "y":
172                 runAllfunctions()
173         else:
174                 runTerraform()
175
176 runTerraform()

What I expect to happen from the above, if the user enters anything other than yes or y it will re-run runTerraform(), which prompts the user for the information again until it is correct. Once it is correct it will go through and run the rest of the functions
Here's what I'm seeing:
When answer is not yes or y
You Entered:
Access Key: asdfds
Secret Key: asfads
Your full name is: dsafd dsafdas

Is the information above correct? (y or n)n
newnumber = 16
Your EC2 instance will tagged:
Name Tag: vlslabs16
Multicast Tag: vlslabmc, 172.16.0.16

It should have re-asked the questions again.
When answer is indeed yes or y :
python terraTFgen.py

Enter Access Key: asdfdsa
Enter Secret Key: asdfads
Enter your name: asdfads

You Entered:
Access Key: asdfdsa
Secret Key: asdfads
Your full name is: asdfads

Is the information above correct? (y or n)y
newnumber = 16
Your EC2 instance will tagged:
Name Tag: vlslabs16
Multicast Tag: vlslabmc, 172.16.0.1

^ this is correct.
What am I missing when the condition is not "yes" or "y" that is preventing the function from asking the questions again?
ps this is the function that is asking the questions in case you were curious, or if this helps
13 def getAccessSecretName():
 14         global access_key, secret_key, yourName
 15         access_key = raw_input("Enter Access Key: ")
 16         secret_key = raw_input("Enter Secret Key: ")
 17         yourName = raw_input("Enter your name: ")
 18
 19         print "\n\nYou Entered:"
 20         print "Access Key: %s" % access_key
 21         print "Secret Key: %s" % secret_key
 22         print "Your full name is: %s\n" % yourName
 23         with open (tfVariables,"w") as text_file:
 24                 text_file.writelines(['access_key = \"'+ access_key +'\"\nsecret_key = \"'+ se    cret_key +'\"\n\n\n',
 25                                 'amis = {\n',
 26                                 '   ',
 27                                 'us-west-1 = '+ usWest1ami +'\n',
 28                                 '   ',
 29                                 'us-west-1 = '+ usWest2ami +'\n',
 30                                 '   ',
 31                                 '}'])

Thanks!

A: The if condition should be if infoCorrect.lower() == "yes" or infoCorrect.lower() == "y":.


text:
Q: File upload in module configuration panel, Prestashop I'm trying to create a XML import module that will convert given file to CSV format and then use that CSV to import categories and products.
I have a working configuration page made with getContent() it basically calls a method that generates this form via $helper->generateForm(). $helper is a HelperForm() object.
protected function getConfigForm()
{
    return array(
        'form' => array(
            'legend' => array(
            'title' => $this->l('Settings'),
            'icon' => 'icon-cogs',
            ),
            'input' => array(
                array(
                    'type' => 'file',
                    'label' => $this->l('XML file'),
                    'name' => 'XMLIMPORT_XML_FILE',
                    'desc' => $this->l('Select file you wish to import.'),
                    'required' => true
                ),
                array(
                    'col' => 3,
                    'type' => 'text',
                    'prefix' => '<i class="icon icon-envelope"></i>',
                    'desc' => $this->l('Enter a valid email address'),
                    'name' => 'XMLIMPORT_LINES',
                    'label' => $this->l('Records per file'),
                ),
            ),
            'submit' => array(
                'title' => $this->l('Save'),
            ),
        ),
    );
}

I need to get this data to my XML converter. How do I upload a file (around 10-20MB) to Prestashop to be then able to do other stuff with it? How to save it permanently on the server?
I tried doing this:
return array(
    'XMLIMPORT_XML_FILE' => Configuration::get('XMLIMPORT_XML_FILE', null),
    'XMLIMPORT_LINES' => Configuration::get('XMLIMPORT_LINES', 1000)
);

And after that this:
$form_values = $this->getConfigFormValues(); // returned array from above

foreach (array_keys($form_values) as $key)
    Configuration::updateValue($key, Tools::getValue($key));

And later using my own class for XML conversion like this, hoping that it will give me file handle.
$xml_converter = new XMLToCSVConverter(Configuration::get('XMLIMPORT_XML_FILE'), 'output', 'example_products.php');

Apparently it didn't as nothing happens. The class itself is working fine outside of Prestashop module. The constructor is __construct($xml_file, $csv_filename, $template_file).
I need to pass the file I upload to that constructor. I've been struggling for days now.
@edit: I can see the contents of the file inside the HTTP call when submit is clicked. But how do I pass that file to my class?

A: As far as I remember 'type' => 'file', doesn't actually save any values in the database. This type is only meant to output a file field in your form.
After submitting, you should then do you custom processing with $_FILES['XMLIMPORT_XML_FILE'] : move to upload/ or whereever you want.
'XMLIMPORT_XML_FILE' => Configuration::get('XMLIMPORT_XML_FILE', null), won't return you anything. After uploading you my wish to save the uploaded file path here, but it won't show up next time in the form unless you build the output yourself.
Module configratuon is meant to save text config values. Handling files is trickier and you have to do them yourself each time.
EDIT:
To intercept the saving process, look up the submit button name and make an if statement:
public function getContent() {
    if(Tools::isSubmit('submitButtonName')) {
      error_log(print_r($_FILES, 1));
    }
}

There's probably a function postProcess which does the same (it looks like you copied the methods from a default module).

A: prestashop handles the image upload with ImageManager class, this class contains more methods which are useful for handling image upload, resize etc.. so its better refer the default homeslider module for the image upload using a module. This module is handling the image upload process in postProcess method with the help of ImageManager class, this class methods will do the all the processes related to upload.


text:
Q: Show and hide Grid Column How to change the grid column value basend on the certain value in another column of that record (row).
I have two column step1_formula and step2_formula if user selected step2 formula from UI form i need to show the content of both column in grid but if user select only step1_formula I need to show Not Applicable in the column step2_formula on that record (row )

A: you can show hide ui component grid column by this way in ui component.
Add a custom class in your column

    <column name="step1_formula" class="vendor\module\Ui\Component\Listing\Column\FormulaGridActions">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true"> Step1 Formula </item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                </item>
            </argument>
        </column>

Paste the following code here

vendor\module\Ui\Component\Listing\Column\FormulaGridActions

<?php

namespace vendor\Module\Ui\Component\Listing\Column;

use Magento\Framework\Exception\LocalizedException;
use Magento\Ui\Component\Listing\Columns\Column;

class FormulaGridActions extends Column
{
    public function __construct(
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
        array $components = [],
        array $data = []
    ){
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource) {
        if (isset($dataSource['data']['items'])) {

            foreach ($dataSource['data']['items'] as & $item) {

                if($item['result_steps'] == 0)
                {
                    $item['step2_formula'] = "";
                    // $item['step1_formula'] = $item['result_color_grams'].''.;
                }

            }
        }

        return $dataSource;
    }

 */
    public function prepare()
    {
       if ($condition) { // Your condition goes here
       $status = true;
        }
          $this->_data['config']['componentDisabled'] = true; // for removing the column
          parent::prepare();
    }

}


text:
Q: GCP compute engine permission denied (public key) after manual edit authrized_keys PROBLEM:
I edited ~/.ssh/authorized_keys manually using vi to add my mac's public key.
I exit from ssh shell and try to connect via vs code remote development.
Then, I can no longer access my VM instance. (ssh, ssh on console or else. in every way)
I assume my authorized_keys is damaged.
What can I try more?
Thanks.
WHAT I HAVE TRIED:

*

*edit metadata in gcp console to add my ssh key. (old one and new one with username)

*resize disk space 10 -> 15 -> 50


text:
Q: How can i scale down an image to a window? I have a window, and i want to draw a BufferedImage inside the window, but scaled down, and i want it to always change when i resize the window.
The dx1, and dx2 should be the destionation X position, and the dy1, and dy2 should be the destionation Y position. (I don't know these four)
The sx1, and sx2 should be the source X position, and the sy1, and sy2 should be the destionation Y position. (0, 0, image.getWidth(), image.getHeight() because i want to use the full image)
gr.drawImage(image, dx1, dx2, dy1, dy2, sx1, sx2, sy1, sy2, null);

I will need 2 paddings i think (p1, p2), and the windowWidth is the width of the JPanel, and the windowHeight is the height of the JPanel.
That's my code:
gr.drawImage(image, p1, p2, windowWidth-p1, windowHeight-p2, 0, 0, image.getWidth(), image.getHeight(), null);


text:
Q: Finding $E \left[\frac{1}{\bar{X}} \right]$ for $X_1, ...,X_n \sim_{iid} Geo(p)$ I am trying to prove that the estimator $\hat{p}=\frac{1}{\bar{X}}$ is unbiased.
Since the $X_i$ s are iid geometric, I know that $Y=\sum_{i=1}^n X_i$ is negative binomial.
So what I want to do is
$$E[\hat{p}] = nE \left[ \frac{1}{Y} \right]=n\sum_{Y=1}^{\infty}\frac{1}{Y} {Y-1 \choose n-1}p^n(1-p)^{y-n}$$
but I am not sure how to evaluate this.
I appreciate your help.

A: $\newcommand{\E}{\Bbb{E}}\newcommand{\x}{\bar{X}}$Actually, it will be biased. By Jensen's Inequality, you can show that $$\E\left[\frac{1}{\x}\right] > \frac{1}{\E\left[\x\right]}.$$
(Because the function $x \mapsto \frac{1}{x}$ is strictly convex on the positive reals.)
Since $\E\left[\x\right] = \frac{1}{p}$, we have $  \frac{1}{\E\left[\x\right]} = p$, and so $$\E\left[\frac{1}{\x}\right]  > p.$$


text:
Q: I am having trouble exiting my infinite loop in pygame Code
This is my little game of pig. I only got it coded for 2 players. I have ran multiple scenarios and it seems to work out good.
I just can't seem to exit the while loop
I am having trouble at line #109.
I set it to break, but i believe it may be break from the small if statement, which I don't want.
I am wanting to break from the large while loop ( game loop ) line #100
I also want to use pygame to add some graphics of dice i have created.
I was wondering if I can keep my code as is and just modify it to work with pygame easily or do I have change the entire code to work with pygame?
I just want to do a simple interface
It will be similar to this : http://cs.gettysburg.edu/projects/pig/pi…
but I will add in dice, simulation of dice rolling 2d, sounds, a win state graphics and sounds, and input, mainly mouse toggle.
Any tips on how to do the pygame portion is much appreciated.
I have read many tutorials on pygame, but I just don't feel confident to get it to work with my own game.
I have made a ball bounce, but I really don't understand what some of pygame's code mean.
I am a little confused on display screen vs background
screen would be pygame.display.set_mode((some size))
then background will capture the exact size of the screen, but not really sure.
I have figured out how to put dice on the screen, and change face every half a second, but that's it.

A: nice little program.  it seems to work fine for me (break exits for and while loops, not if).
when you play the game it's a little confusing because the check to see if someone has won comes only after the other player plays and then you enter 'hold'.  perhaps that is what made you think it wasn't working?  it might be better (i don't know the exact rules of pig) to put the check for winning right after the code that runs on 'hold'?
sorry can't help with pygame; just wanted to post to say it seems to work.
also, if you wanted, you could put the two players in an array:
players = [player1, player2]

and then the current player would be:
players[player_turn-1]

and you could use the same code for either player, duplicating the logic in the main loop.  so the code would be more like:
if players[player_turn-1].winner():
    ...

A: #Make a Variable set it to "False".
#= means to assign something to something.
#== means equal to.
#Example in a if statement if something == to something do something.
test = False

#This is the loop.
while test == False:
    #Put Code Here.
    #Put a If Statement `enter code here`to stop loop.
    if #Parameters:
        test = True


text:
Q: I get an error "Trying to get property 'perbaikan' of non-object" when looping data from hasMany table I geeting an error Trying to get property 'perbaikan' of non-object. Please help me to resolve my problem.

My Perbaikan model
public function tagihan()
    {
        return $this->belongsTo('App\Tagihan', 'id_tagihan');
    }

My Tagihan model
  public function perbaikan()
    {
        return $this->hasMany('App\Perbaikan');
    }

My controller
public function report(Tagihan $tagihan)
{
   return view('tagihan.report', compact('tagihan'));
}

My view blade

   <?php $no = 0;?>
   @foreach ($tagihan as $data)
   @foreach ($data->perbaikan as $row)
   <?php $no++ ;?>

         {{ $no }}
         {{ $row -> nomor_dokumen }}
         {{ $row -> kulkas -> nomor_asset  }}
         {{ $row -> tipepekerjaan -> kode_tipe_pekerjaan }}
         {{ $row -> tanggal_perbaikan }}

   @endforeach
   @endforeach

dd($tagihan)

Tagihan {#337 ▼
  #primaryKey: "id_tagihan"
  #guarded: []
  #connection: "mysql"
  #table: "tagihans"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:5 [▼
    "id_tagihan" => 1
    "nomor_dokumen" => "A00001919191"
    "periode_tagihan" => "Januari"
    "created_at" => "2019-02-05 08:26:00"
    "updated_at" => "2019-02-05 08:26:00"
  ]
  #original: array:5 [▼
    "id_tagihan" => 1
    "nomor_dokumen" => "A00001919191"
    "periode_tagihan" => "Januari"
    "created_at" => "2019-02-05 08:26:00"
    "updated_at" => "2019-02-05 08:26:00"
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}

My perbaikans table
public function up()
    {
        Schema::create('perbaikans', function (Blueprint $table) {
            $table->increments('id_perbaikan');
            $table->string('nomor_dokumen_perbaikan', 25)->unique();
            $table->integer('id_tagihan')->unsigned();
            $table->string('teknisi', 30);
            $table->date('tanggal_perbaikan');
            $table->timestamps();
            $table->foreign('id_tagihan)->references('id_tagihan')->on('tagihans');
        });
    }

My tagihans table
 public function up()
    {
        Schema::create('tagihans', function (Blueprint $table) {
            $table->increments('id_tagihan');
            $table->string('nomor_dokumen', 25);
            $table->string('periode_tagihan', 20);
            $table->timestamps();
        });
    }

I have tried to get all data from hasMany table, it works fine, but I don't want all data from the table. I only want to retrieve data based on the id from belongsTo table
I get error with message "Trying to get property 'perbaikan' of non-object"

A: You are looping trough $tagihan but this is not necessary
change:
   @foreach ($tagihan as $data)
   @foreach ($data->perbaikan as $row)

To:
   @foreach ($tagihan->perbaikan as $row)

and remove one of the @endforeach


text:
Q: How to route to a page in a post request that is itself called through an XHR request? If a user clicks a button, then an xhr request is made to go to the POST:
        var xhr = new XMLHttpRequest();   // new HttpRequest instance
        xhr.open("POST", "/registration");
        xhr.addEventListener("load", e => {
            console.log(xhr.responseText)
        });

        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.send(JSON.stringify(this.state));

Here is the POST request.
router.post('/registration', function *(req, res, next) {
console.info("trying to get the user");
//console.log(this.request.body);

let {name, password} = this.request.body

let taken = yield utils.nameTaken(name)

if(taken){
    //redirect to reg page
    console.log("taken!");
    //this.response.redirect("/registration");
    //res.redirect('/');
    console.log(req);

}
else{
    userSchema.createUser(name, password, function(err, user){
    //console.log(err, user);
    });
    //this.response.redirect("/success");
    //redirect to success page
}

})

What I'm trying to do is when taken is true, then the client gets redirected to the route '/' and when taken is false, then the client gets redirected to '/success'. I'm having trouble doing these redirects, any help would be appreciated. Thanks.

A: You can't do it in this fashion, at least not if I'm understanding you correctly. What currently happens it that the browser receives the response (/success or /) as the answer to its XMLHTTP-request. The redirect, however, has already happened at this point. xhr.request.body will contain whatever GET /success and GET / return.
What you probably want to do is simply return a status code (I believe good REST practice would be 403 for a failure, 200 for success) and react to that on the client.


text:
Q: android textview click on a link If I have a textview with spanned text obtained from Html.fromHtml(source), how to make the textview to react when I click on a link? In my textview, link is something like "click here" and this text is a link, it's not a direct link like www.google.com.

A:  android:autoLink="web"

A: Butter to use Linkify
Refer Android Text Links Using Linkify

A: I guess you want to handle span click event by yourself.
There two ways for this:
1)Create new class extends URLSpan
2)Create new class extends LinkMovementMethod
Please see below url, may be help you.
https://stackoverflow.com/a/16182500/596555

A: Add this to your tetView
android:text="@string/Documentation

Add this line to string.xml [ res/values]
<string name="Documentation">Android Activity Lifecycle Documentation
</string>

Add This code to your MainActivity.java
TextView textView = findViewById(R.id.textView);      textView.setMovementMethod(LinkMovementMethod.getInstance());


text:
Q: Understanding cancellation and refund process (i.e. how to handle cancelled but paid orders) So I got banned from #magento on freenode for asking details about this to understand the underlying process flow. :D
I get the problem that:

*

*a product is ordered

*an invoice is send

*a payment is triggered by a payment provider via wire transfer

*a notice comes that the product can't be delivered

*I check if the invoice was paid

*if it wasn't I cancel the order

*now money from the customer arrives

Now I'm stuck as I can click to refund the order but the total amount is zero as I cancelled the order already.
This can happen all the time, and seems to be the case if you google for it, because i.e. the wire transfer just takes some time, the customer mixes up the payments and tells you he hasn't paid yet or something alike. You can't wait to cancel for weeks just to be sure the customer doesn't pay, can you?
What workflow does magento have here? You can't cancel the cancellation, you can't refund the order, you can't tell it that it was "overpaid" so to speak. It seems you can't do anything here.
The only thing I came up with was to mingle through the database and revert the cancellation so I could refund again.
I found a lot of code snippets online to do so, which in my opinion hints at something.
I really like to understand the thinking / process here.

A: Magento cancel order of invoiced items are as follow
Any invoiced orders in Magento cannot be "canceled", but they can be "closed". It sounds like you need to issue a "credit memo", which is refund in Magento.

Brief Regarding Credit Memo
After an order has been paid and invoiced, all of the order, or a portion of it, can be refunded by issuing a credit memo. A credit memo differs from a refund because the amount of the credit is restored to the customer's account where it can be applied to future purchases, rather than returned to the customer as cash. In some cases, a refund can be given at the same time that the credit memo is issued, just as a payment can be made at the time of invoicing.


text:
Q: Adding a secure HTTPS certificate to AWS EC2 Instance I have an application running on an AWS EC2 instance with the domain's nameservers on AWS as well. I have an A record with the public IP.
I've create a secure certificate with ACM and also created an ELB Load Balancer. My domain still doesn't show the HTTPS in front of it.
Can anyone provide some help? Many thanks

A: You cannot install an ACM certificate on an ec2 instance directly, but you can install it on your load balancer and have the load balancer terminate SSL.
Create a target group and register your ec2 instances using port 80.
In your ELB, setup listeners for both port 80 and 443. You'll need to add your ACM cert to your https listener (port 443). Note that the certificate needs to be issued in the same region as your ELB.
The ELB does not handle redirecting insecure traffic to HTTPS, if needed, you will need to update your application to redirect http to https.

A: Have you tried this ?
First, you need to open HTTPS port (443). To do that, you go to https://console.aws.amazon.com/ec2/ and click on the Security Groups link on the left, then create a new security group with also HTTPS available. Then, just update the security group of a running instance or create a new instance using that group.
After these steps, your EC2 work is finished, and it's all an application problem.
Credit to : https://stackoverflow.com/a/6253484/8131036

A: The solution is pretty simple.
First of all, edit the listeners on your ELB and do the following:
443 (HTTPS) => 80 (HTTP) - and apply ACM certificate.
What this essentially is doing is tells the ELB to listen on port 443 (HTTPS) and terminate the certificate and then forward traffic internally over port 80 (HTTP) - the port the instance is listening on.
You can also add port 80 (HTTP) and forward to port 80 (HTTP) (recommended and then set up your application to redirect all users to HTTPS). You can read more about ELB and setting up listeners here Create a Classic Load Balancer with an HTTPS Listener
Second thing you need to do is update Route 53 to point to ELB.
ascisolutions.com. A   ALIAS s3-website-us-west-2.amazonaws.com. You can read more about it here Routing Traffic to an ELB Load Balancer
Let me know if you have more questions in the comments section and I'll do my best to reply.


text:
Q: Python how to find all paths from nltk root node to all leaf node I am currently working with spacy and nltk trees. I am new to these stuff so I am really struggling on them.
Here is the code to print a spacy parsed dependency sentence and form it to an nltk tree.
import spacy
from nltk import Tree
en_nlp = spacy.load('en_core_web_sm')
self.sentence = "My bestfriend is John."
sen = en_nlp(self.sentence)
self.print_pos(sen)
self.print_tree(sen)
sentences = list(sen.sents)
sentence = sentences[0]
# we assume the input is only one sentence
root_node = sentence.root
tree = self.to_nltk_tree(root_node)
#     self.traverse(tree)

#helper function
#https://stackoverflow.com/questions/36610179/how-to-get-the-dependency-tree-with-spacy
def to_nltk_tree(self, node):
    if node.n_lefts + node.n_rights > 0:
       return Tree(node.orth_, [self.to_nltk_tree(child) for child in node.children])
    else:
       return node.orth_

def print_tree(self,sen):
    # print the tree in preety print
     def to_nltk_tree(node):
        if node.n_lefts + node.n_rights > 0:
           return Tree(node.orth_, [to_nltk_tree(child) for child in node.children])
        else:
           return node.orth_

    [to_nltk_tree(sent.root).pretty_print() for sent in sen.sents]

def print_pos(self,sen):
    # print all atttributes in tabular format
    for token in sen:
       print(f"{token.text:{8}} {token.dep_ + ' =>':{10}}   {token.head.text:{9}}  {spacy.explain(token.dep_)} ")

Here are the outputs
My       poss =>      bestfriend  possession modifier
bestfriend nsubj =>     is         nominal subject
is       ROOT =>      is         None
John     attr =>      is         attribute
.        punct =>     is         punctuation
      is
  ____|______
 |    |  bestfriend
 |    |      |
John  .      My

I want to find all paths from root to all leaf nodes. For example, the desired output for the above will be ["John is", "My bestfriend is"]. How would I do that? Also, if I want to filter out some leaves like "." punct, what should I do?