text:
Q: How to set one setting as slot deployment setting for azure web app using powershell I need specify one app setting as "deployment slot setting" so as to assign different value in Prod and Staging slots and keep the value stick to slot when swapping the slots. I know I can do it on azure portal as below screen shot. But how to do it using powershell?

I tried the powrshell cmd Set-AzWebAppSlot:
Set-AzWebAppSlot -AppSettings $newAppSettings -Name $webAppName -ResourceGroupName $resourceGroupName -Slot "Staging"
But the settings set with above command are not marked as "Deployment slot setting"

A: If you want to configure an app setting or connection string to stick to a specific slot (not swapped),
use Set-AzWebAppSlotConfigName:
Set-AzWebAppSlotConfigName -ResourceGroupName <group-name> -Name <app-name> -AppSettingNames <setting-name1>,<setting-name2>,...

Reference link: https://learn.microsoft.com/en-us/azure/app-service/configure-common?tabs=ps#configure-app-settings


text:
Q: Is it possible to trace back 403 error during ajax request in Django Rest Framework? I'm trying to make an ajax call with DRF and each time receive:
[20/Oct/2017 13:35:24] "OPTIONS /test/ HTTP/1.1" 403 82

I can't understand the reason of this error(I disable csrf by decorators and by middleware). Is it possible to raise exception instead of 403 response in Django to find out which middleware and which code line return 403 error?

A: 403 is forbidden. It may be happened because of the permission class you used. If you are using function based view(FBV) add decorator and set permission to AllowAny, if its class based view(CBV) use permission class to AllowAny . for examole
FBV
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

# ...

@api_view(['GET'])
@permission_classes((AllowAny,))
def test_view(request, format=None):
    # ...
    # you code
    # ...
    return Response(content)

CBV
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

# ...

class TestView(APIView):

    permission_classes = (AllowAny,)

    def get(self, request, format=None):
        # ...
        # you code
        # ...
    return Response(content)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reloading navigation properties in EF6 I have read a lot of questions of stackoverflow regarding reloading navigation property using Context.Entry(entity).Collection(p=>p.Property).Load() but in my case it doesn't give me the updated values from database.
LazyLoading and ProxyCreation options are set to their default values, which I have read they are ON by default.
I have an object of entity Test which I have fetched from database using eager loading with all the related properties using below method:
var test = Repository.GetById(testId, null, true, new Expression<Func<Test,object>>[] {
    bt=>bt.Baselining,
    ct=>ct.Baselining.BaselineTestCase,
    dt=>dt.Baselining.BaselineTestCase.Baseline,
    ft=>ft.Baselining.Transaction,
    gt=>gt.Baselining.Transaction>Select(x=>x.Fields)
});

public virtual T GetById<T>(int id, Func<T,bool> where = null, bool trackChanges = false, params Expression<Func<T,object>>[] includeProps)
{
    T item = null;
    IQuerable<T> dbQuery = Context.Set<T>();

    if(includeProps != null)
        foreach(Expression<Func<T,object>> navProp in includeProps)
            dbQuery = dbQuery.Include<T,object>(navProp);

    if(where == null)
    {
        if(!trackChanges) item = dbQuery.AsNoTracking().FirstOrDefault(t=>t.Id == id);
        else item = dbQuery.FirstOrDefault(t=>t.Id == id);
    }
    else
    {
        if(!trackChanges) item = dbQuery.AsNoTracking().Where(where).FirstOrDefault(t=>t.Id == id);
        else item = dbQuery.Where(where).FirstOrDefault(t=>t.Id == id);
    }
    return item;
}

I am trying to reload Baselining.Transaction.Fields using
Repository.Reload(test);
Repository.Reload(test.Baselining.BaselineTestCase);
Repository.Reload(test.Baselining.BaselineTestCase.Baseline);
Repository.ReloadNavigationProperties(test.Baselining, x=>x.Transaction);
foreach(var tq in test.Baselining.Transaction)
    Repository.ReloadNavigationProperties(tq, x=>x.Fields);

Repository methods goes something like:
public virtual void ReloadNavigationProperties(TEntity,TElement>(TEntity entity, Expression<Func<TEntity,ICollection<TElement>>> navProp) where TEntity : class where TElement : class
{
    Context.Entry(entity).Collection(navProp).Load();
}

public virtual T Reload<T>(T entity) where T : class {
    Context.Entry(entity).Reload();
    return entity;
}

I have debugged the above ReloadNavigationProperties execution using SQL Profiler and it does go to database and generates a SQL query with joins as well, but my object is not updated even after the reload.
After failing to reload navigation properties with above method, I came to this trivial approach, which works...
foreach(var tq in test.Baselining.Transaction)
    foreach(var tqfs in tq.Fields)
        Repository.Reload(tqfs);

Because I have approx 100 TransactionQueryFields for each TransactionQuery and this nested foreach goes 100 times to reload each field and its very very slow and it should be slow...
Here are the entities
public class Test
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int id {get;set;}
    public virtual Baselining Baselining {get;set;}
    public virtual ICollection<TestExecutionResult> TestCaseResults {get;set;} = new List<TestExecutionResult>();
}

public class Baselining
{
    public Baselining() {}
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int id {get;set;}
    public DateTime BaseliningDate {get;set;}
    public virtual BaselineTestCase BaselineTestCase {get;set;}
    public virtual ICollection<TransactionQuery> Transaction {get;set;} = new List<TransactionQuery>();
}

public class BaselineTestCase
{
    public BaselineTestCase() {}
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int id {get;set;}
    public virtual Baseline Baseline {get;set;}
    public virtual ICollection<Baselining> Baselinings {get;set;} = new List<Baselining>();
    public Baselining LastBaselining {
        get {return Baselinings.OrderBy(x=>x.BaseliningDate).LastOrDefault(); }
    }
}

public class TransactionQuery : TransactionItem
{
    public TransactionQuery() {}
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public override int id {get;set;}
    public virtual Baselining Baselining {get;set;}
    public virtual ICollection<TransactionQueryField> Transaction {get;set;} = new List<TransactionQueryField>();
}

public class TransactionQueryField : TransactionItem
{
    public TransactionQueryField() {}
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public override int id {get;set;}
    public bool Compare {get;set;}
    public bool Critical {get;set;}
}

public abstract class TransactionItem : BaseEntity<int> {
    public string TestResultCode {get;set;}
}

public abstract class BaseEntity<T> {
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual T Id {get;set;}
}

I want to understand why eager loading with navigation properties is not loading the updated data. Because according to my understanding, if I eager load anything it should make a round-trip to database and fetch updated data. But even eager loading with reload, it doesn't gives me updated values.
I am sorry if I didn't explain it properly, although I will appreciate any help regarding how to load my fields faster may be with one single db round-trip.

A: This is just an hypothesis but I think the reason for which your navigation properties are not reloaded is tracked entities.
I have already experienced something like this and about the Load method the doc says:

Loads the collection of entities from the database. Note that entities
  that already exist in the context are not overwritten with values from
  the database.

When you call the GetById, you set the parameter trackChanges on true. From now on, all the eager-loaded entities are tracked.
As I said, I am not sure if this is the problem but you could try setting the state of all your tracked entities to EntityState.Detached.


text:
Q: get number with specific digit with out press on "enter" key int getGuess()
{
    int number = 0;
    int  i = 0;
    printf("Enter your guess\n");
    for (i = 1; i<=FOUR;i++)
    {
        number = number*TEN + getche();
    }
    printf("\n");
    return number;
}

I did this code, I know that this is a function but in the function that I called to this function I print the value, and it does not work as I expected.
I this is what I enter 2431 and this the real value 55759.
well how could I can get integer number and without press on enter?

A: When you ask for input, the program stops. The system needs to know when the input stops and this is usually the enter key. When the input is provided, the program starts again. This is the default C behaviour. Professional developers write their own input driver to control this start/stop situation.


text:
Q: DevExpress vs Aspose.pdf I need to choose a tool for an upcoming project in dotnet.
My requirement is to generate, sign, edit pdf reports.
The report will contain sections, subsections, tables, nested tables, images, header, footer, table of content etc.
I would like to know which tool is better in which aspect.

A: The Aspose.pdf api is a powerful tool, but it is just API.
DevExpress XtraReports tool has a visual designer for report layout so you can "draw" your own complex layouts, embed the report designer into your application (or website) and export resulting document into the pdf file with two lines of code:
var report = new MyReport();
report.ExportToPdf(stream);

A: Aspose.PDF for .NET API can be used to achieve all of your mentioned requirements. All product features are well documented and API references are available as well. Free support and Paid Support is also available for the API. You may request for a free, 30 day temporary license to test if this product satisfies your requirements. This is some brief information about the API and you may decide which option suits you well after testing and comparing both of these. You may visit respective website for further information.
PS: I work with Aspose as Developer Evangelist.


text:
Q: Trace of Sobolev function on boundary as limit of traces on interior hypersurfaces Consider a cylinder $C_{R,T} = D_R \times (0,T)$ in $\mathbb{R}^n$, where $D_R$ is a ball of radius $R$ in $\mathbb{R}^{n-1}$ and where $x$ parametrizes the ball $D_R$ and $t$ parametrizes the interval $(0,T)$.  Then the Sobolev trace theorem says that we can define the trace or boundary value at $t=0$ of each function $f \in W^{1,p}(C_{R,T})$ as some function $Tf \in W^{1-1/p,p}( D_R)$.
In motivating the result, one can easily show using the Fundamental Theorem of Calculus (see e.g. Giusti, Direct Methods in the Calculus of Variations, p.106-107) that if $f$ is smooth in $C_{R,T}$ and if $\{t_n\} \to 0$, the trace $Tf$ is the limit in $L^p(D_R)$ of the functions $f_n(x) \equiv f(t_n,x)$.
My question: Is it also true that $Tf$ is the limit of the $f_n$ in $W^{1-1/p,p}(D_R)$?  After all, by the trace theorem they all belong to $W^{1-1/p,p}(D_R)$.


text:
Q: How can I log Get/Patch/Post statements being sent from my .NET library project? I'm not sure there is anything wrong with my code, but I have a dll .net 4.8 library file that is hooked up to an ERP system that makes REST calls to a third party web based app that is unix-based. We are troubleshooting an issue regarding a strange error but something else came up where they said they are getting a lot of GET statements from the dll for URLs that require PATCH/POST and those urls (specifically one) doesn't have functionality set up for a GET statement.
Is is possible that the .NET objects are sending underlying HTTP calls?
So basically, I would like to log all of the REST statements that are being sent to verify, if possible, where they are coming from. I've combed my code and there is literally one entry point to this statement and I am sending a PATCH and the resource url doesn't require anything to be sent in the body except an empty string.
So is there a way to log all the HTTP calls going out from my project? See code below for my routine.

I've looked up how to log and I mostly get results for web projects, but this is a dll project and I'm not sure if those suggestions will work for this.

try
                {
                    CVToken curToken = CVGlobalRestCalls.GetToken(Session);
                    HttpClient httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", curToken.Token);
                    httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    var jSettings = new JsonSerializerSettings();

                    HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), string.Format("{0}/readytosend/{1}/complete", Globals.GetRESTURL(Session), JobID));
                    request.Content = new StringContent(JsonConvert.SerializeObject(string.Empty, Formatting.Indented, jSettings), Encoding.Default, "application/json-patch+json");

                    HttpResponseMessage response = httpClient.SendAsync(request).Result;
                    CVJob cvCompletedJob = JsonConvert.DeserializeObject<CVJob>(CVGlobalRestCalls.GetResponseContent(response));
                    outFile.WriteLine(string.Format("Invoice Group {0} has been pushed to CV", JobID.ToString()));

                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format(" {0}", ex.Message));
                }


text:
Q: How to hide pdf importer popup in word automation When I open a PDF file with Word automation, it show a dialog that ask me to confirm the convertion (With a "do not show again" checkbox).

Word will now convert your PDF to an editable Word document. This may
  take a while. The resulting Word document will be optimized to allow
  you to edit the text, so it might not look exactly like the original
  PDF, especially if the file contained lots of graphics.

How to hide this dialog ?
var application = new Microsoft.Office.Interop.Word.Application();
application.Visible = false;

try { application.ShowStartupDialog = false; }
catch { }
try { application.DisplayAlerts = WdAlertLevel.wdAlertsNone; }
catch { }

var doc = application.Documents.Open(
    inputFilePath,
    ConfirmConversions: false,
    ReadOnly: true,
    AddToRecentFiles: false,
    Revert: true,
    NoEncodingDialog: true);

PS : ConfirmConversions:true add an other dialog.

A: The solution is to edit office registry.
Software\Microsoft\Office\{version}\Word\Options : DisableConvertPdfWarning
The code below add or edit the registry key and restore state when disposing.
public class WordPdfImportWarningRemover : IDisposable
{
    private const string RegistryDirectoryFormat = @"Software\Microsoft\Office\{0}\Word\Options";
    private const string RegistringKeyName = "DisableConvertPdfWarning";
    private object _oldValue;
    private RegistryValueKind _oldValueKind;
    private bool _keyExists;
    private bool _registryExists;

    public WordPdfImportWarningRemover()
    {
        EditRegistry("16.0");
    }

    public WordPdfImportWarningRemover(string version)
    {
        if(version == null)
            throw new ArgumentNullException(nameof(version));

        EditRegistry(version);
    }

    private void EditRegistry(string version)
    {
        RegistryKey officeOptions = Registry.CurrentUser.OpenSubKey(string.Format(RegistryDirectoryFormat, version), true);
        if (officeOptions != null)
        {
            using (officeOptions)
            {
                _registryExists = true;
                var keys = officeOptions.GetValueNames();
                if (keys.Contains(RegistringKeyName))
                {
                    _keyExists = true;
                    _oldValue = officeOptions.GetValue(RegistringKeyName);
                    _oldValueKind = officeOptions.GetValueKind(RegistringKeyName);
                }
                else
                {
                    _keyExists = false;
                }
                officeOptions.SetValue(RegistringKeyName, 1, RegistryValueKind.DWord);
                officeOptions.Close();
            }
        }
        else
        {
            _registryExists = false;
        }
    }

    public void Dispose()
    {
        if (_registryExists)
        {
            RegistryKey officeOptions = Registry.CurrentUser.OpenSubKey(string.Format(RegistryDirectoryFormat, "16.0"), true);
            if (officeOptions != null)
            {
                using (officeOptions)
                {
                    if (_keyExists)
                    {
                        officeOptions.SetValue(RegistringKeyName, _oldValue, _oldValueKind);
                    }
                    else
                    {
                        officeOptions.DeleteValue(RegistringKeyName, false);
                    }

                    officeOptions.Close();
                }
            }
        }
    }
}

The office version can be found with this function
private static string FindWordVersion()
{
    var application = new Microsoft.Office.Interop.Word.Application();
    try
    {
        string version = application.Version;
        return version;
    }
    finally
    {
        application.Quit(SaveChanges: false);
    }
}


text:
Q: How to display dynamic raster (lidar) data on a Web map? I have some high quality LiDAR data. I need to process it dynamically, and update a field (not elevation field) depending on my input and elevation at that point. Once this is done, I need to display this raster data on Web Map (Bing Map, Google Map etc.) as real time as possible.
Here is what i have been able to do till now:
I have come up with some scripts using ArcGIS Python Lib, that process my lidar clips, add a field , update that field according to the input coming in. So now i basically have all the points on raster classified into 3 categories every 5 mins. If i view this raster in arcGIS i can view nice 3 colored raster overlapped on a base map.
But now i need to render these raster clips on a Web map. My first though was to polygonize these classified clips and display the polygons on a JavaScript Map. But polygonization takes a lot of time, and thus its eliminated.
Now Other option I have is to to use GeoServer's Raster rendering capabilities to display the images. Then use this WMS i created, to overlap it on Bing Maps.
This is where i am stuck. I have no clue how to automatically get Rasters that Geoserver supports, like Geotiff, jpg200o etc from my ADF files, render them on open layers first, then try to overlap them on bing maps.
If someone knows of any good tutorial that does this kind of rendering of dynamically changing rasters on map , will be great if you could point me to it.
Also if there are some other better approaches to get this kind of system in place, Please suggest. I am open to almost any solution.
Thanks
PS: I am pretty good at web programming, web services,databases  and scripting etc. But new to working with Lidar and Geo-Rasters.

A: GeoServer can supply your Web Application Network KMZ - in real-time.
There is a very good 'Visualize Lidar in Google Earth' page here
http://www.cs.unc.edu/~isenburg/googleearth/
(Martin Isenburg & Jonathan Shewchuk)
key point is:
"we create the 10 by 8 tiling of 10 feet contours gilmer.kmz (c,d) in only 20 minutes using less than 100 MB of main memory and no temporary disk space from 357 LAS files (provided by West Virginia View) that contain a total 156 million LIDAR points.
Once your data is ready you can then use the Network KMZ from Geoserver
Example of Google Earth on the web with this Network KML is:
http://code.google.com/apis/earth/documentation/samples/kmlnetworklink_example.html


text:
Q: Was there a P4 model with double-pumped 64-bit operations? I recall that one of the interesting features of the initial P4 micro-architecture was it's double-pumped ALU. I think Intel called it something like the Rapid Execution Unit, but basically it meant that each execution unit in the ALU was effectively running at twice the frequency, and could handle two simple ALU operations in a single cycle, even if they were dependent.
This feature disappeared at some point (before or at the same time as the P4), but was there ever a 64-bit P4 with a double dumped ALU? The 64-bit variants of the P4 came out in 2004, about four years after the initial 32-bit release, but it isn't clear to me if the double-speed ALU had disappeared by then. It seems like the width-pipelined approach used to double the speed would be difficult for 64-bit which is what piqued my curiosity.
Since one may still need to support some (evidently quite old) 64-bit P4 hardware, knowing the ALU behavior is interesting for optimization.

A: I found the Intel Optimization Manual 2005 that covers both 32-bit and 64-bit NetBurst processors. Refer to Table C-8 on page C-17. According to the first comment on this blog post, the 32-bit Northwood's model is 02h and the 64-bit Nocona's model is 03h. The table shows that ADD/SUB/AND/OR/XOR have a throughput of 0.5 cycles on both processors, but a latency of 0.5 cycles on Northwood and 1 cycle on Nocona. This means that double-pumping is supported on Nocona, but only if the back-to-back instructions are not dependent. The rest of the table also shows that some instructions that were not double-pumped on Northwood were double-pumped on Nocona.

Summary: There is ample evidence that shows that some NetBurst-based processors (whether released or canceled) could perform at least 2 64-bit ALU operations per cycle using either 2 32-bit staggered ALUs or at least a single 64-bit staggered ALU (which would be enabled by smaller feature sizes such as 90nm at that time).

Figure 7 of the original paper1 on Intel Pentium 4 Willamette2 processor discusses how the double-pumped3 ALU works in some detail (at the logic design level).

The figure shows a single 32-bit staggered ALU unit. This confirms that the ALU can perform two fully dependent (both input operands are dependent) simple ALU operations in three fast cycles (where a fast cycle is one half of the main clock cycle). The result of the operation itself is available after 2 fast cycles (1 main cycle), but the new flags are only available after the third fast cycle (1.5 main cycles). Note that there are two such ALUs on ports 0 and 1, both are staggered. So the design could execute 2 dependency ALU chains with 4 operations per slow cycle throughput.
That paper was published in 2001. Intel has published another paper4 in 2005 that discusses in great detail at the circuit level how the staggered integer core in the Intel Pentium 4 Prescott5 processor. It's not clear to me whether the paper discusses the 64-bit version of Prescott or the 32-bit version. However, this paper clearly states that the staggered ALU units can only perform additions, Boolean operations, shifts, and rotations (the other paper discussed the design of pre-Prescott cores in which the two fast ALU units did not support shifting and rotating). The other important difference is this statement from the paper:

There are two distinct 32-bit FCLK execution data paths staggered by
  one clock to implement 64-bit operations.

So it seems that the two fast ALU units on ports 0 and 1 are staggered together, enabling 64-bit fast integer operations such as additions. Therefore, the design could execute either two 32-bit dependency ALU chains with 4 operations per slow cycle throughput or one 64-bit dependency ALU chain with 2 operations per slow cycle throughput. This is even more powerful than a single staggered 64-bit ALU that can do only 64 bit operations, not 32-bit ones. The is most probably the design used in the 64-bit variants of the NetBurst microarchitecture.
Another6 paper7 from Intel confirms that Intel was indeed able to design a double-pumped 64-bit ALU. I quote from the paper:

In this paper,  we  describe  a  single-cycle  integer  ALU
  fabricated  in  90nm dual-Vt CMOS  technology operating  at  4GHz  in
  the  64b  mode, with  a  32b  mode  latency  of  7GHz  (measured  at
  1.3V,  25◦C).

The paper doesn't mention whether this design has actually being used in any particular processor. But considering that the paper was published in 2004, there is a good chance that all of the 64-bit NetBurst cores (whether released or canceled) used the design.
There are many 64-bit NetBurst-based processors that have released by Intel. For example, see this list for the server-grade processors. One of the cores is called Nocona. There is some experimental evidence that the design mentioned earlier (2 staggered 32-bit ALUs) was actually used in Nocona. Refer to these slides used in some course taught in CMU in 2008 on code optimization. The slides compare between the performance of Nocona (64-bit NetBurst), Intel Core (also 64-bit), and AMD Opteron (also 64-bit and apparently implements the same 64-bit staggered ALU design). This is the code used in a loop:
x = x + d[i];

where all elements are 32-bit integers (unfortunately, 64-bits have not been used).
On slide 35, you can see the 32-bit integer addition throughput achieved on Nocona and Opteron. Since each operation requires a load and Nocona only supports a single load per cycle, Nocona's performance maxed out at around 1 operation per cycle. Opteron, however, which supports two loads per cycle, was close to the theoretical maximum of 2 operations per cycle. This experiment of course does not take advantage of staggering, but only of the fact that there are two 32-bit simple ALUs.
However, later in the slides, SSE3 is used instead of scalar integer registers. The results for all of the three processors are shown on slide 44. With SSE3, there will be only one 128-bit load per 4 elements. Nocona can perform a 64-bit load from the L1D per cycle (see the article cited below), while Core can perform a single 128-bit L1D load per cycle. However, Core has a feature called Advanced Digital Media Boost (ADMB) that enables it to perform 4 32-bit addition per cycle. That same paper also mentions that pre-Core architectures supported only 2 32-bit SSE3 ALU operations per cycle. But if there are two 32-bit staggered ALUs in Nocona, the low SSE3 throughput implies that an SSE3 operation makes use of only one of the staggered ALUs. ADMB can be implemented in two ways. Either by expanding each ALU to 64-bits and keeping them staggered and utilizing both ALUs to perform 2 64-bit ALU operations per cycle. Another possibility is expanding each ALU to 128-bit and eliminate staggering.
There is a patent filed by Intel in 1998 and granted in 2001 on the staggered execution of an instruction, any instruction basically, not just ALU operations. That patent is still active. There is a lot of discussion there on how staggered execution can be useful for 128-bit SIMD instructions. Based on this patent, it's very possible that Intel Core uses two 64-bit staggered ALUs to achieved its throughput. Each of the 64-bit ALUs can actually be made using two staggered 32-bit ALUs shown in the figure above.
In 2002, Intel filed a patent for a generic staggered ALU design. It was generic in the sense that it was not about any specific ALU operation or the number of clock cycles or the clock period. The interesting thing here is that one of the figure there shows a staggered 64-bit ALU design! That was in 2002. The patent also discusses some of the challenges in designing staggered ALUs.
The patent says that it was both granted and abandoned on the same day in 2006. Then after few months, another identical patent application was filed.
This article shows that Potomac (another server-grade Pentium 4) is 64-bit architecture and supports 4 64-bit per cycle.  Yamhill and Jayhawk were canceled by Intel. (There is an error in the article: Nocona is a 64-bit CPU.)

(1) In case the link goes down, the paper is titled "The Microarchitecture of the Pentium® 4 Processor" and  authored by Glenn Hinton, et al.
(2) Also known as the first-gen Pentium 4.
(3) Also known as staggered ALU.
(4) In case the link goes down, the paper is titled "Low-Voltage Swing Logic Circuits for a Pentium® 4 Processor Integer Core" and  authored by Daniel J. Deleganes, et al.
(5) Also known as the third-gen Pentium 4.
(6) In case the link goes down, the paper is titled "A 4GHz 300mW 64b Integer Execution ALU with Dual Supply Voltages in 90nm CMOS" and  authored by Sanu K. Mathew, et al.
(7) In case the link goes down, the paper is titled "HIGH-PERFORMANCE ENERGY-EFFICIENT DUAL-SUPPLY ALU DESIGN" and  authored by Sanu K. Mathew, et al.


text:
Q: Webview runtime setup while wpf app installation I am deploying my wpf exe file using VS 2019 setup project. I am using webview2 in my wpf and I am able to see the result however my client machine is not able get any result .
Is there any way apart from what is mentioned in webview runtime documents mentioned by Microsoft.
Any simple way to install webview while user is installing the wpf setup ?

A: You can refer Webview distribution
There are 2 way to get the root cause,

*

*just check app.exe.Webview2 folder is generated in your exe folder path.

*is webviewloder.dll is present or not ?

and if you want simple way to install the webview2 while installation then just download the microsoftWebviewSetup.exe and include the exe file in your custom action
steps:

*

*create a setup project

*in application folder add your wpf exe and webview2 exe

*right click on project -> View -> custom action

*open the custom action -> Install -> add the webView2.exe

*run the setup.exe it will install the webviewruntime also


text:
Q: CSS. Flexbox. Можно ли добиться такого поведения? Можно ли с Flexbox добиться такого поведения?

Разумеется, с media-queries.
Из проблем столкнулся с тем, что не смог задать элементам свойство, чтобы они были на второй строке. Подогнать ширину не получается из-за блоков фиксированной ширины.

A: Да. Использовать order для переупорядочивания и flex-grow для расширения. Не уверен, но может понадобиться добавить лишний элемент в разметку (или использовать псевдоэлемент контейнера) для форсирования перевода строки.
https://jsfiddle.net/rw8o4tc8/3/

html, body { margin: 0; }

body {
  background: white;
  display: flex;
  flex-wrap: wrap;
  text-align: center;
  min-width: 240px;
}

.a, .e { background: aquamarine; } /* top */
.b, .d { background: burlywood; } /* bottom */
.c, .f { background: silver; } /* center */

.a, .b, .d, .e { flex-grow: 1; }
.c { width: 100px; }
.f { width: 50px; }

@media all and (max-width: 480px) {
  .a, .c, .e {order: -1; }
  body:before { content: ""; width: 100%; }
  .b { order: 1; }
  .f { order: 2; }
  .d { order: 3; }
}

sizable top

sizable bottom

100px

sizable bottom

sizable top

50px


text:
Q: How do I update the wpColorPicker palette after initialization? Once the customizer color picker is initialized, how can the color palette be updated? The palette can be set through the js options before it's initialized using something like:
jQuery.wp.wpColorPicker.prototype.options.palettes = ["#303f9f", "#5c6bc0", "#e8eaf6", "#ffffff"];

Updating the options after the picker is initialized has no effect on the palettes. I'm guessing the picker needs to be reinitialized but can't seem to figure out how to do that inside of the customizer using wpColorPicker.


text:
Q: keep the extra whitespaces in display of pandas dataframe in jupyter notebook In jupyter notebook, extra whitespaces  in dataframe are removed. But sometime that is not preferred, e.g.
df=pd.DataFrame({'A':['a   b','c'],'B':[1,2]})
df

The result I get:
|   | A   | B |
|---|-----|---|
| 0 | a b | 1 |
| 1 | c   | 2 |

But I want:
|   | A     | B |
|---|-------|---|
| 0 | a   b | 1 |
| 1 | c     | 2 |

Is it possible? Thanks

A: It's actually HTML: pandas dutifully write all the spaces into the HTML markup (the front end format used by Jupyter Notebook). HTML, by default, collapses multiple adjacent whitespaces into one. Use the style object to change this:
df.style.set_properties(**{'white-space': 'pre'})

You unfortunately can't change the default render style of a DataFrame yet. You can write a function to wrap that line:
def print_df(df):
    return df.style.set_properties(**{'white-space': 'pre'})

print_df(df)


text:
Q: Python Multicast not working between two different computers I have a server and client communicating through multicast using a python script. When I put my scripts on the same computer, they behave appropriately; that is they can send and receive data between each other. The computer is running Windows 10.
When I put one script on the computer and one script on a raspberry pi, my computer doesn't receive any multicasts except for it's own sent messages. The raspberry pi receives everything.
Can anyone tell me why my computer isn't receiving the data from the raspberry pi? There probably is a setting on my computer I need to enable or maybe I need to configure something in my script?
The code I use is below:
import socket
import struct

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007

def _send_socket(message):
    # Create socket to send validation on shooting
    send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    dev = "eth0" + "\0"
    #sock2.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, dev)
    send_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
    send_socket.sendto(message, (MCAST_GRP, MCAST_PORT))
    send_socket.close()

def _recv_socket(recieve_socket):
    data = recieve_socket.recv(10240)
    return data

def run():
    recieve_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    recieve_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    recieve_socket.bind(('', MCAST_PORT))
    mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
    recieve_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while(True):

        data= _recv_socket(recieve_socket)
        if data:
            _send_socket("Sending something back")


text:
Q: how to install a Windows 10 on Ubuntu or burn Windows 10 into USB I tried to burn windows 10 into usb and dvd even try to install Windows 10 on Ubuntu it's not work please help me i tried many time

A: Windows-To-Go
You can use Rufus, https://rufus.ie/ or Universal USB Installer, https://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/,  to install Windows-To-Go on a USB. It is a simple but long process, best to let run overnight. It results in a Full install of Windows 10 on USB. It has nothing to do with Ubuntu.


text:
Q: Unable to change image's EXIF info? I want to change an image's EXIF info (its orientation to ExifInterface.ORIENTATION_ROTATE_270). I am using this code:
val inputStream: InputStream? = mActivity.contentResolver.openInputStream(imageURI)
val exif = ExifInterface(inputStream!!)

exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_ROTATE_270.toString())
exif.saveAttributes()

Unfortunately, this code has no effect. Why?

A: I would expect that code to be throwing an IOException based on the ExifInterface source code. All you gave ExifInterface is an InputStream; ExifInterface has no way to write to one of those. You will need to:

*

*Use the InputStream to copy the image to a file that you control (e.g., in getCacheDir() on Context)

*Use ExifInterface with that file to make your desired changes

*Use openOutputStream() on ContentResolver to get an OutputStream back to the original content

*Copy the contents of your modified file to that OutputStream


text:
Q: Can't Copy/Paste to VM Today, I just setup a new VM, from here.
https://www.vmware.com/go/downloadplayer
So, I set it up and everything seems to be working fine.  I can definitely login with my password, but I can't copy/paste anything from my laptop to the new VM.  I tried to run this code: 'sudo apt-get install open-vm-tools'.  That, supposedly will allow me to copy/paste.  However, when I enter that, I'm prompted for my password on the VM.  I enter it, and get a message that it's not correct.  I've done this 3x; the password is definitely correct, or I couldn't even login to the VM.  Can someone tell me what's going on?  All I want to do is copy/paste.  That's it.  Thanks.

A: You have to enable Copy and Paste in VMWare settings, e.g. like that.


text:
Q: Ubuntu Openstack: Does the default Landscape Installer provide High Availibilty I am looking at deploying Ubuntu Openstack in a production environment via the Landscape Autopilot. I am unable to locate documentation detailing its default configuration which would assist me in answering questions like "is HA built in".
Can anyone point me towards reliable sources of information?

A: The currently released version does not support HA. That's coming shortly in an upcoming release.

A: The Landscape Autopilot will install Ubuntu OpenStack, as defined in the Ubuntu OpenStack reference architecture. This is also in the process of a major update, so I can't point you to a source of relevant documentation, but I can promise that both that and documentation for the Autopilot installer are in progress, and I will add links to this answer when they are finished.


text:
Q: Does Swift 2 work on iOS 8? When building with Xcode 7 beta using Swift 2, can iOS 8 devices be used as deployment targets?
I remember that swift runtime gets embedded as dynamic framework so each app uses its own version of swift instead of iOS's version of swift, but I can't be sure.
On a related note, as of July 12, can you submit app to app store containing Swift 2?


text:
Q: XSD: default value of a missing element Is it possible to define a default value for a missing element in an XML Schema. I have the following snippet:
<xs:element name="protocol" nillable="false" minOccurs="0" default="ftp">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:enumeration value="ftp"/>
      <xs:enumeration value="webdav"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

If I have in the XML file
<protocol>ftp</protocol>

or
<protocol>webdav</protocol>

it validates and I obtain the right value.
If I have in the XML file
<protocol></protocol>

it also validates and I obtain the default value of ftp.
My searches show that default attribute values apply when attributes are missing, and default element values apply when elements are empty. Is it possible to have a default value for a missing element?
Regards
rambius

A: No. XSD doesn't provide for that.
You can specify the default value of an element.
But once it is missing (when that's allowed by the content model of its parent),
any requests to that element will return either empty string or null (or just an error).
The missing element is non-existent element!
For attributes it is possible, because attributes are far simpler.
All attributes of an element effectively constitute an unordered set of named simple values. There is no some kind of attribute tree (with the variable structure at that) attached to the parent element.
But with elements things are far more complex.
If something "default" about missing elements were allowed, that would cause lots of ambiguities. For instance, some kind of "default content" would have to be specified then,
which would be some sequence of elements evoked automatically in place of emptiness...
or even a number of possible "default contents" each evoked when only some elements are specified explicitly and others must supplement them implicitly (by default).
....
Well, if you think further on, the things are getting mind-boggling complex.
Another language would have to be created then! But for what purpose?

A: call this function
def _get_(x):
  if x is not None:
     return(x.text)
  else:
    # print('Setting Blank')
     return ''
_get_(parent.find('childtag'))


text:
Q: AngularJS locale with ES6 and Webpack I got a problem, I work on a project with intertionalization. I'm using AngularJS 1.5, ES6, and Webpack, I also use ng-translate for the different text.
I installed AngularJS-i18n for manipulate numbers and date and AngularJS-dynamic-locale for set the $locale language when I change the website's language with npm.
The problem, I don't know how to load AngularJS locale from the node_modules in my config.js. I did this:
export default function configApp(thmDynamicLocaleProvider) {
   tmhDynamicLocaleProvider.localeLocationPattern('../../../node_modules/angular-i18n/angular-locale_{{locale}}.js');
}
configApp.$inject = ['thmDynamicLocaleProvider'];

I set the good URL, but I don't know why, the app returns a 404 error. And I don't know how can I load this in webpack ot others...

A: If you use webpack i suggest you to use import() function. It will split the locales to chunks which will be invoked in the runtime by request. But this method has a one restriction. You can't implement dynamic way to necessary chunks. So when you'll get info from somewhere on the client side regarding current locale, you are able through switch operator to choose what to import.
For example,
function GetLocaleInfo(locale) {
    switch(locale) {
        case 'en':
            import('angular-i18n/angular-locale_en.js').then((en) => {
                setLocale(en);
            });
        case 'ru':
            import('angular-i18n/angular-locale_ru.js').then((ru) => {
                setLocale(ru);
            });
       }
}

I'll pay a little bit more attention that import function in using on async way should have only string content. It doesn't support dynamic value cause on build step webpack check these ways to build proper chunks of code in the build directory.
Here is you would find more info about code splitting on the webpack


text:
Q: Method to get these JSON entries I am working in javascript with JSON payloads like below, and I am curious about the best way to get all entries of each element. For example, how could I get all entries of "o4" in some order (-159, -257)?
{
  data: {
    '1613152800': {
      i0: -264,
      i1: 297,
      i2: -260,
      i3: 270,
      i4: -159,
      i5: 0,
      i6: -7,
      i7: 145
    },
    '1613153400': {
      i0: 261,
      i1: -239,
      i2: 125,
      i3: -214,
      i4: -257,
      i5: 3,
      i6: -237,
      i7: -128
    }
  }
}

This example has two main entries '1613152800' and '1613153400', but in reality there will be hundreds of those.
I won't know the main entry id's before hand either, so the '1613152800' and '1613153400' will always be unknown. I can't rely on
var json = JSON.parse(data);
console.log(json.data['1613152800'].i4);

for example.
Thanks!

A: You can take Object.values and map it:

const obj={ data: { '1613152800': { i0: -264, i1: 297, i2: -260, i3: 270, i4: -159, i5: 0, i6: -7, i7: 145 }, '1613153400': { i0: 261, i1: -239, i2: 125, i3: -214, i4: -257, i5: 3, i6: -237, i7: -128 } }}

const getEntries=(obj, key)=> Object.values(obj.data).map(({[key]:v})=>v);

console.log(getEntries(obj,'i4'));

A: You can loop through the properties in your data object:
var json = JSON.parse(data);
var ids = [];
for(var id in json.data) {
  ids.push(id);
}

Now you have an array of the "id" objects. You can access the objects by their indices:
console.log(ids[0].i4);


text:
Q: Issue with Gifted Chat, the messages jump up the screen on text input I'm using Gifted Chat for react native, but I'm getting strange behavior. When keyboard is down, messages are fine. When I tap on the keyboard to have it come up, it's also fine.. but the moment I start typing, the messages jump up. The only way to get them back again is to close the keyboard. Here is how it looks:

What am I doing wrong here? Here is the code:
<KeyboardAvoidingView
      style={{ flex: 1 }}
      behavior="padding"
      keyboardVerticalOffset={Platform.select({
        ios: () => 0,
        android: () => 100
      })()}
    >
      <GiftedChat
        handleChoosePhoto={handleChoosePhoto}
        forceGetKeyboardHeight
        showUserAvatar
        renderChatFooter={renderChatFooter}
        isAnimated
        scrollToBottom
        onInputTextChanged={e => emitTyping(user._id, otherUser, e)}
        showAvatarForEveryMessage
        messages={messages}
        onSend={msg => onSend(msg)}
        user={user}
      />
</KeyboardAvoidingView>

This component is returned as a functional component, not wrapped in anything else and not in conflict with anything else. The strange thing is that if I get rid of behavior="padding", it doesn't jump... but then the TextInput element is not visible.

A: I fixed this by removing forceGetKeyboardHeight

A: You don't need KeyboardAvoidingView in giftedChat the component handles it's own keyboard so just remove that component


text:
Q: php > SimpleXMLElement > '&' Symbol I am having problems using the & in xml strings created by php's SimpleXMLElement. For example the following:
<?php
$xml = new SimpleXMLElement("<?xml version='1.0' encoding='UTF-8'?><links></links>");
$xml->addChild("url","https://www.somewhere.com?a=1&b=2");
echo $xml->asXML();
?>

gives me when run:
<?xml version="1.0" encoding="UTF-8"?>
<links><url>https://www.somewhere.com?a=1</url></links>

I have already tried:
...
$xml->addChild("url","https://www.somewhere.com?a=1&b=2");
...

and got:
...
<links><url>https://www.somewhere.com?a=1&b=2</url></links>

how do I get:
...
<links><url>https://www.somewhere.com?a=1&b=2</url></links>

A: You can't. That is illegal XML: the & character must be escaped (XML specification).


text:
Q: How to proof variance of the sum $x+y$ is the sum of variance $\sigma_x^2$ of $x$ and the variance $\sigma_y^2$ of $y$? Show that the variance of the sum $x + y$ of the random variable $x$ and the random variable $y$ is the sum of the variance $\sigma_x^2$ of $x$ and the variance $\sigma_y^2$ of $y$?
My attempt:
Is my first time doing statistics and there are alot of terms i am quite unfamiliar with.
Random variable: Value of a variable result from a random experiment: e.g. (the score when a die is rolled once)
Variance($\sigma^2$) : Average of squared deviations from the mean or square of standard deviation?
I know variance of sum $x + y$ means $var(x+y) = $E(x+y)^2 -$(E(x+y))^2$
But what does sum of the variance $\sigma_x^2$ of $x$ and the variance $\sigma_y^2$ of $y$ means?
Edited:
My 2nd attempt:
Var(x + y ) = E$(x+y)^2$ - $(E(x+y)^2)$ = E($x^2$ + 2xy +$y^2$) - [($Ex)^2$ + 2ExEy + ($Ey)^2$ ] = [E$x^2$ - (E$x)^2$ ] + [E$y^2$ - (E$y)^2$ ] + 2[Exy - ExEy] = Var x + Var y + 2cov (x,y)
Now i assume(not sure is it correct) sum of the variance $\sigma_x^2$ of $x$ and the variance $\sigma_y^2$ of
$y$
= var ($\sigma_x^2$ ) + var($\sigma_y^2$)
= E($\sigma_x^2$ ) -[E($\sigma_x)]^2$ +  E($\sigma_y^2$ ) -[E($\sigma_y)]^2$
Since var(x) = $\sigma_x^2$,
=E(E($x^2)$ - $[E(x)]^2$) - [$E^2$ ((E($x^2)$ - $[E(x)]^2$)) + E(E($y^2)$ - $[E(y)]^2$) - [$E^2$ ((E($y^2)$
I did not further solve it because i realise is wrong as the above does not have an expression that has an xy expression. So where have i done wrong?

A: The variance of $X$ is $E\left[\big(X - E[X]\big)^2\right]$ so here we are looking at
$$E\left[\big((X+Y) - E[X+Y]\big)^2\right] \\= E\left[\big((X-E[X])+(Y-E[Y])\big)^2\right]  \\ = E\left[\big(X - E[X]\big)^2\right] +E\left[\big(Y - E[Y]\big)^2\right] +2E\left[\big(X - E[X]\big)\big(Y - E[Y]\big)\right]  $$
You actually want the result to be the two left terms.  The right-hand term cancels out if and only if the covariance is $0$, which will happen when $X$ and $Y$ are independent or in a few other special cases


text:
Q: Checking if a valid zip code matches a state/city and outputting "unknown" if not in a label I've created a program that pulls the corresponding state/city from a database based on the zip code entered, but I need help with outputting an "error" if a non-valid, non-corresponding zip code is entered in the form of the world "Unknown" put in both the state/city labels.
I've tried a bunch of if statements but to no avail.
private void BtnLookup_Click(object sender, EventArgs e)
{
    String cnStr;
    SqlConnection cn = new SqlConnection();

    cnStr = "Data Source=000.00.000.00;Initial Catalog=.  ;User ID=.  ;Password=.  ";

    //Assigns Connection string to the connection object
    cn.ConnectionString = cnStr;
    //Open the connection to the SQL Server
    cn.Open();

    //This statement creates the command object and passes in the SQL statement
    //then associates the command to the cn connection object

    SqlCommand cmd = new SqlCommand("select distinct state, city from tblZipcodes where zip = @ZipCode", cn);

    cmd.Parameters.Add(new SqlParameter("@ZipCode", SqlDbType.NVarChar) { Value = txtZip.Text });

    SqlDataReader rdrZip = cmd.ExecuteReader();

    while (rdrZip.Read())
    {
        String myString = rdrZip["state"].ToString().Trim();
        String myString2 = rdrZip["city"].ToString().Trim();

        lblState.Text = myString;

        lblCity.Text = myString2;

    }

    cn.Close();
}

if a non-valid zip is entered then put unknown in the state/city labels

A: One option is to check whether your query returns result or not by using SqlDataReader.HasRows

Gets a value that indicates whether the SqlDataReader contains one or more rows.

And you can implement it like,
if (rdrZip.HasRows)
{
    while (rdrZip.Read())
    {
        String myString = rdrZip["state"].ToString().Trim();
        String myString2 = rdrZip["city"].ToString().Trim();

        lblState.Text = myString;
        lblCity.Text = myString2;

    }
}
else
{
    lblState.Text = "Unknown";
    lblCity.Text = "Unknown";
}


text:
Q: Subsetting a function variable within another variable I have the following function that performs a step-wise linear regression, and it works well with numerical and integer values, although, when I have factors as independent variables, I get the following error:

Error in [.data.frame(d, , names(resul0)) : undefined columns selected

The layout of the function:
stepfor(bird$Richness, data.frame(GARDENSIZE, Site, season), alfa = 0.2)

I have figured out a way that splits the factors into columns and assigns them respective values following the comments, given by this:
   x <- function(x) {x %>%
            select(where(negate(is.numeric))) %>%
            map_dfc(~ model.matrix(~ .x -1) %>%
                        as_tibble) %>%
            rename_all(~ str_remove(., "\\.x"))
}

Though, I'm not sure how I can include it into the function below, so that x can be implemented with the function below by calling it stepfor likeso:
stepfor(bird$Richness, data.frame(x(bird)), alfa = 0.2)

I just want to know how to include the function x within the function below to have it work like above. And if there aren't any factors in the data, then set the function as FALSE so it doesn't return an error like x is missing.
Here is my function:
stepfor<-function (y = y, d = d, alfa = 0.05)
{
    pval <- NULL
    design <- NULL
    j = 1
    resul0 <- summary(lm(y ~ ., data = d))$coefficients[, 4]
    d <- as.data.frame(d[, names(resul0)][-1])
    for (i in 1:ncol(d)) {
        sub <- cbind(design, d[, i])
        sub <- as.data.frame(sub)
        lm2 <- lm(y ~ ., data = sub)
        result <- summary(lm2)
        pval[i] <- result$coefficients[, 4][j + 1]
    }
    min <- min(pval)
    while (min < alfa) {
        b <- pval == min
        c <- c(1:length(pval))
        pos <- c[b]
        pos <- pos[!is.na(pos)][1]
        design <- cbind(design, d[, pos])
        design <- as.data.frame(design)
        colnames(design)[j] <- colnames(d)[pos]
        j = j + 1
        d <- as.data.frame(d[, -pos])
        pval <- NULL
        if (ncol(d) != 0) {
            for (i in 1:ncol(d)) {
                sub <- cbind(design, d[, i])
                sub <- as.data.frame(sub)
                lm2 <- lm(y ~ ., data = sub)
                result <- summary(lm2)
                pval[i] <- result$coefficients[, 4][j + 1]
            }
            min <- min(pval, na.rm = TRUE)
        }
        else min <- 1
    }
    if (is.null(design)) {
        lm1 <- lm(y ~ 1)
    }
    else {
        lm1 <- lm(y ~ ., data = design)
    }
    return(lm1)
}

Reproducible code:
bird<- structure(list(season = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L), .Label = c("Summer",
"Winter"), class = "factor"), Richness = c(20L, 17L, 18L, 19L,
11L, 15L, 17L, 15L, 15L, 9L, 13L, 14L, 12L, 18L, 30L, 30L, 17L,
25L, 32L, 32L, 29L, 29L, 27L, 18L, 25L, 24L, 15L, 18L, 23L, 22L,
25L, 22L, 22L, 23L, 17L, 22L, 7L, 15L, 16L, 20L, 24L, 21L, 22L,
39L, 17L, 17L, 13L, 26L, 25L, 20L), GARDEN_SIZE = structure(c(1L,
1L, 2L, 2L, 3L, 3L, 2L, 2L, 2L, 2L, 3L, 3L, 2L, 3L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 3L, 3L, 2L, 2L,
1L), .Label = c("L", "M", "S"), class = "factor"), Site = structure(c(1L,
1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L), .Label = c("R", "S", "U"), class = "factor")), row.names = c(NA,
50L), class = "data.frame")

A: Consider this:

stepfor<-function (y = y, d = d, alfa = 0.05)
{

    # split the incoming data to give non-numeric the factor treatment:
    x1 <- d %>% select(where(negate(is.numeric))) %>%
        map_dfc(~ model.matrix(~ .x -1) %>%
                    as_tibble) %>%
        rename_all(~ str_remove(., "\\.x"))
    x2 <- d %>% select(where(is.numeric))

    d <- cbind( x1, x2 )

    pval <- NULL
    design <- NULL
    j = 1
    resul0 <- summary(lm(y ~ ., data = d))$coefficients[, 4][-1]
    d <- as.data.frame(d[, names(resul0)])

    # rest of function body as is

}

eg. move the [-1] from the 5th line to the 4th to remove the intercept term earlier. The reamining coefficients shouldnow match the ones you have in your data.frame and names(resul0) should all exist in your data.frame
There is a problem with your approach to tackle this. You do:
d <- as.data.frame( d[, names(resul0) ] [-1] )
This code tries to look up all of the names(resul0) inside the d data.frame. This includes the intercept term, and this therefore fails. (And at this point its too late to remove the intercept afterwards as the damage has already been done)
You need to remove the intercept before looking up the names inside d. Then the name-error won't happen.
The body of the x function can be inserted in there, quite straight forward.


text:
Q: Build Kubernetes from Source on a Windows machine Is it possible to build Kubernetes from source code on a windows machine?
As per development environment setup mentioned in https://github.com/kubernetes/community/blob/master/contributors/devel/development.md only supported OSs are Linux and MAC
Running build/run.sh shows below:
Unsupported host OS.  Must be Linux or Mac OS X.

A: The simple answer is yes. Kubernetes source is in Go and there is Go compiler for Windows.
Another question would be, is it possible to be built easily? And that would be a 'no'  (as of this writing) since you have already seen by running build/run.sh. So it's not supported by K8s officially.


text:
Q: Will huge amount of callbacks break script or continue whenever enough RAM is available? I have a function that fetches thread (gmail conversation) ids from database and then asks Google API for all data for each thread id. Once it receives a thread object, it stores it to database. This works fine for my inbox which has ~1k messages. But I am not sure if it would work for accounts with over 100k messages.
Now what I am asking, once a machine runs out of memory, will it break or will it continue executing callback functions whenever enough RAM is available again? Should I modify this code to do this part-by-part (rerun whole script at some points and continue with fresh RAM from where it last ended?)
function eachThread(auth) {
  var gmail = google.gmail('v1');

  MongoClient.connect(mongoUrl, function(err, db){
    assert.equal(null, err);
    var collection = db.collection('threads');
    // Find all data in collection and convert it to array
    collection.find().toArray(function(err, docs){
      assert.equal(null, err);
      var threadContents = [];
      // For each doc in array...
      for (var i = 0; i < docs.length; i++) {
        gmail
        .users
        .threads
        .get( {auth:auth,'userId':'me', 'id':docs[i].id}, function(err, resp){
          assert.equal(null, err);
          threadContents.push(resp);
          console.log(threadContents.length);
          console.log(threadContents[threadContents.length - 1].id);
          var anotherCollection = db.collection('threadContents');
          anotherCollection.updateOne(
            {id: threadContents[threadContents.length - 1].id},
            threadContents[threadContents.length - 1],
            {upsert:true},
            function(err, result){
              assert.equal(null, err);
              console.log('updated one.');
          });
          if (threadContents.length === docs.length) {
            console.log('Length matches!');
            db.close();
          }
        });//end(callback(threads.get))
      }//end(for(docs.length))
    });//end(find.toArray)
  });//end(callback(mongo.connect))
}//end(func(eachThread))

A: You will not run out of memory if you will not get everything and push it to array. Also I would not instantiate objects that are the same on every element inside the loop.
Here is example of code that will not run out of memory, however it is fire-and-forget meaning that you will not get callback when it's finished etc. If you wish to do that you will need to use promises/async.
// Fire-and-forget type of function
// Will not run out of memory, GC will take care of that
function eachThread(auth, cb) {
  var gmail = google.gmail('v1');

  MongoClient.connect(mongoUrl, (err, db) => {
    if (err) {
      return cb(err);
    }

    var threadsCollection = db.collection('threads').find();
    var contentsCollection = db.collection('threadContents');

    threadsCollection.on('data', (doc) => {
      gmail.users.threads.get({ auth: auth, 'userId': 'me', 'id': doc.id }, (err, res) => {
        if (err) {
          return cb(err);
        }

        contentsCollection.updateOne({ id: doc.id }, res, { upsert: true }, (err, result) => {
          if (err) {
            return cb(err);
          }
        });
      });
    });

    threadsCollection.on('end', () => { db.close() });
  });
}

A:
Now what I am asking, once a machine runs out of memory, will it break or will it continue executing callback functions whenever enough RAM is available again?

If you run out of memory, the OS will kill your process. In Linux you will see an OOM (Out of Memory). So yes, it'll break.
In these scenarios, you may consider using either streams or generators so you keep in memory just the chunk of data you need to process.
In your case MongoDB provides streams on find method https://mongodb.github.io/node-mongodb-native/2.0/tutorials/streams/
Something like this should work:
var collection = db.collection('threads');
var cursor = collection.find()

cursor.on('data', function(doc) {
  gmail
  .users
  .threads
  .get( {auth:auth,'userId':'me', 'id': doc.id}, function(err, resp) {
    ...
  })
})

A: Replacing your for loop by async.mapLimit is enought to add the part by part functionality. I've also taken the liberty to move the anotherCollection creation alongside collection, since opening the connection once is better than opening it hundre if not thousands of times.
I've also replaced your assert.equal by callback(err). async's function will understand that it should stop everything, and it allow you to cleanly exit instead of throwing a exception.
EDIT:
As @chernando remarked, using collection.find().toArray will import the whole collection into RAM. A better way of doing the part by part would be to stream the data, or to ask the DB to give the data by chunk.
This version assume you have enought RAM to get collection.find().toArray working without issue.
I will probably come back later with a adaptation of the tool I talked about in the comments when I ll have the time.
var async = require('async');

function eachThread(auth) {
  var gmail = google.gmail('v1'),
      limit = 100; //Size of the parts

  MongoClient.connect(mongoUrl, function(err, db){
    assert.equal(null, err);
    var collection = db.collection('threads'),
        anotherCollection = db.collection('threadContents');
    // Find all data in collection and convert it to array
    collection.find().toArray(function(err, docs){
      assert.equal(null, err);
      var threadContents = [];
//Change here
      async.mapLimit(docs, limit, (doc, callback) => {
        gmail
        .users
        .threads
        .get( {auth:auth,'userId':'me', 'id':docs[i].id}, function(err, resp){
          if(err) {
            return callback(err);
          }
          threadContents.push(resp);
          console.log(threadContents.length);
          console.log(threadContents[threadContents.length - 1].id);
          anotherCollection.updateOne(
            {id: threadContents[threadContents.length - 1].id},
            threadContents[threadContents.length - 1],
            {upsert:true},
            function(err, result){
              if(err) {
                console.error(err);
              } else {
                console.log('updated one.');
              }
              callback(err);
          });
        });//end(callback(threads.get))
//Change here
      }, (error) => {
        if(error) {
          console.error('Transfert stopped because of error:' + err);
        } else {
          console.log('Transfert successful');
        }
      });//end(async.mapLimit)
    });//end(find.toArray)
  });//end(callback(mongo.connect))
}//end(func(eachThread))


text:
Q: Counter Not Working Correctly The following code looks up a text file to see if there are any matches. For example, a line may be "charlie RY content" and the next line may be "charlie content". However, the counter seems to be off and isn't counting correctly.
file = open("C:/file.txt", "rt")
data = file.readlines()
dictionary = dict()
counter = 0
count = 0
setlimit = 10 #int(input("Please enter limit for N. Then press enter:"))
parameter = ["RY", "TZ"]
for j in data:
    user = j.split()[0]
    identify = j.split()[1]
    for l in identify:
        #l = a[1:2]
        if user not in dictionary.keys() and identify not in parameter:
            count = 1
            data = dictionary.update({user:count})
            break
            #print(user, count,"<-- Qualifies")
        elif user in dictionary.keys() and identify not in parameter:
            data = dictionary.update({user: count})
            count += 1
            break
print(dictionary)

As seen in the code, it looks for either RY or TZ and ignores this line and if a line without this condition is met, the counter will increase by one.
Sample Data:
charlie TZ this is a sentence
zac this is a sentence
steve RY this is a sentence
bob this is a sentence
bob this is another sentence

Expected Output:
{zac:1, bob:2}

A: If you wish to augment the count,
count += 1

must come before
dictionary.update({user: count})

In other words,
elif user in dictionary.keys() and identify not in parameter:
    count += 1
    dictionary.update({user: count})
    break

Note that dictionary.update(...) modifies dictionary and returns None.
Since it always returns None, there is no need to save the value in data.

Alternatively, as pointed out by Martijn Pieters, you could use
for j in data:
    ...
    if identify not in parameter:
        count += 1
        dictionary[user] = count

Note that you don't need to handle the assignment in two different cases.
The assignment dictionary[user] = count will create the new key/value pair if user is not in dictionary, and it will assign the new value, count, even if it is.
Note that the single count variable is getting increased by one whenever the conditional is True for any user.
If you want the dictionary[user] to increase by one independently for each user, then use
for j in data:
    ...
    if identify not in parameter:
        dictionary[user] = dictionary.get(user, 0) + 1

dictionary.get(user, 0) returns dictionary[user] if user is in dictionary, otherwise it returns 0.

Another alternative is to use a collections.defaultdict:
import collections
dictionary = collections.defaultdict(int)
for j in data:
    ...
    if identify not in parameter:
        dictionary[user] += 1

With dictionary = collections.defaultdict(int),
dictionary[user] will be assigned the default value int() whenever user is not in dictionary. Since
In [56]: int()
Out[56]: 0

dictionary[user] is automatically assigned the default value of 0 when user is not in dictionary.

Also, user in dictionary is more idiomatic Python than user in dictionary.keys(), though they both return the same boolean value. In fact, you already use this idiom in
when you say identify not in parameter.
While we're on the topic of idioms, it is generally better to use a with-statement to open files:
with open("data", "rt") as f:

since this will guarantee that the file handle f gets closed automatically for you when Python leaves the with-statement (either by reaching the end of the code inside the statement, or even if an exception is raised.)

Since identify is assigned string values such as 'TZ', the loop
for l in identify:

assigns values such as T, then Z to the variable l.
l is not used inside the loop, and there is no apparent reason to be looping over the characters in identify. Therefore, you probably want to remove this loop.

Testing for membership in a set is on average a O(1) (constant speed) operation, while testing for membership in a list is O(n) (the time generally increases with the size of the list.) So it is better to make parameter a set:
parameter = set(["RY", "TZ"])

Instead of calling j.split twice,
user = j.split()[0]
identify = j.split()[1]

you only need to call it once:
user, identify = j.split(maxsplit=2)[:2]

Note that both these assume that there is at least one whitespace in j.
If there isn't, the original code snippet will raise IndexError: list index out of range, while the second raises ValueError: need more than 1 value to unpack.
maxsplit=2 tells split to stop splitting the string after (at most) two splits are done. This could save some time if j is a large string with many split points.

So putting it all together,
import collections
dictionary = collections.defaultdict(int)
setlimit = 10 #int(input("Please enter limit for N. Then press enter:"))
parameter = set(["RY", "TZ"])
with open("C:/file.txt", "rt") as f:
    for line in f:
        user, identify = line.split(maxsplit=2)[:2]
        if identify not in parameter:
            dictionary[user] += 1

dictionary = dict(dictionary)
print(dictionary)

A: In addition to what @unutbu said, you need to NOT reset count or continue incrementing it for other users!
        if user not in dictionary.keys() and identify not in parameter:
            dictionary[user] = 1
            break
            #print(user, count,"<-- Qualifies")
        elif user in dictionary.keys() and identify not in parameter:
            dictionary[user] += 1
            break

Without this change, @unutbu answer would still have incorrect counting logic from OP. For example, for this input:
charlie TZ this is a sentence
zac this is a sentence
steve RY this is a sentence
bob this is a sentence
bob this is another sentence
zac this is a sentence
zac this is a sentence
bob this is a sentence

your original logic would give the results:
{'bob': 4, 'zac': 3}

when both should be equal to 3.

for l in identify: probably is not needed and actually likely interferes with the results.

TO SUMMARIZE: Your code could look like this:
file = open("C:/file.txt", "rt")
dictionary = dict()
setlimit = 10 #int(input("Please enter limit for N. Then press enter:"))
parameter = ["RY", "TZ"]
for j in file:
    user, identify = j.split()[:2]
    if identity in parameter:
        continue
    if user in dictionary.keys():
        dictionary[user] += 1
    else:
        dictionary[user] = 1
file.close()
print(dictionary)

A: You have been given other answers that cover your current approach. But it should be noted that python already has a collections.Counter object that does the same thing.
Just to demonstrate using a Counter (note: this uses Py3 for * unpacking):
In []:
from collections import Counter
parameter = {"RY", "TZ"}
with open("C:/file.txt") as file:
    dictionary = Counter(u for u, i, *_ in map(str.split, file) if i not in parameter)

print(dictionary)

Out[]:
Counter({'bob': 2, 'zac': 1})


text:
Q: How to generate random networks for comparison with my network? I have a network of 361 nodes and 695 edges. I want to prove that my network is statistically significantly different from a random network. Small-world connectivity is a key parameter that has been tested to prove whether a network is real or random. As per this question, I would like to generate multiple random networks and get an average across all the networks that I generate.
My question is: Should I use the same number of nodes and edges over all the random networks that I generate?

A: In most cases it depends on what exactly you mean by random, i.e., which null hypothesis you want to test. This again depends on your application, network acquisition, and underlying question.
Two examples:

*

*Suppose:

*

*Your measurement process dictates a fixed set of nodes.

*Two nodes are connected in your network whenever some measure specific to those two nodes exceeds some threshold.

*You want to find out whether your measure is actually meaningful and not just yields random results – specifically with respect to the thresholding process.

A reasonable null hypothesis in this situation would be that your measure returns independent numbers from some distribution. On the network level, this means that whether an edge exists or not is independent from the existence of other edges. The probability with which some edge exists depends only on the aforementioned distribution and the threshold. Hence the ensemble of networks that comply with this null hypothesis is the ensemble of Erdős–Rényi random networks having the same edge density and number of nodes.

*Suppose:

*

*Your network's nodes are individual persons.

*Edges represent friendship (measured in some reasonable manner).

*You want to find out whether this network actually has some intricate structure like cliques or whether each person selects their friends at random.

A reasonable null hypothesis in this case would be that your network's structure is determined entirely by the degrees of its nodes, i.e., the number of friends each person has (reflecting their social activity). The corresponding random networks are more constrained than Erdős–Rényi random networks and methods of obtaining this ensemble are a little bit more complicted (see Maslov and Sneppen or Artzy-Randrup and Stone).
So, in these cases (as in many others) you should use the same numer of nodes and edges, but that's not necessarily the only feature to preserve in your ensemble. What exactly makes sense depends on your application. It may even make sense to test several null models to detect some trivial influences on your measurements.


text:
Q: How to change values in an array using for loop Just two questions in regards to this code.

*

*How do I iterate through the array and actually change the values in the array.

*Why does the foreach keep giving me an out of bounds exception. It works fine for the usual for loop (int i = 0; i < anArray.length; i++), but I havn't used this foreach before?

package experimental;

import java.sql.Array;

public class foreachExp {

    public int[] anArray = {1, 2, 3, 4, 5,};

    public void foreachArray() {
        for (int i : anArray) {
            anArray[i] = i + 1;
        }
    }
}

A: for-each does not work based on array index but implements an iterative solution, the int i variable will be representative of a single element of data from your supplied array. So in the loop, you effectively call:
anArray[1] = 1 + 1;
anArray[2] = 2 + 1;
anArray[3] = 3 + 1;
anArray[4] = 4 + 1;
anArray[5] = 5 + 1;

As you can see, anArray[5] would be out of bounds, as the length of the array is only 5 long (0-4)
If you want to change the values, you do not use a for-each loop (could hackily do it using a Box of some sort, but with an array it would be silly to).
So with an array, this would be the advisable solution:
for (int i = 0; i < anArray.length; i++) {
    anArray[i]++;
}

As you have already mentioned

A: When you write
for (int i : anArray) {

i refers to the value itself, not the index. So asking for array[5] gives you an out of bounds exception (valid indices are 0 to 4).
You can instead use a normal for loop:
for (int i=0; i<anArray.length; ++i) {
    anArray[i]++;
}

A: The fundamental difference between a for loop and an enhanced-for loop is that the enhanced-for loop actually binds the values of the array to the variable itself.
So, your enhanced-for is pulling this on each iteration:

*

*i = 1

*i = 2

*i = 3

*i = 4

*i = 5 // this is the size of your array

Enhanced for loops aren't meant for changing values.  You would use a normal for loop for that.


text:
Q: React error with create-react-app command I have been facing a weird situations while creating a react app via command line on windows 10. I get the following error when I run create-react-app command. I am using node v8.9.4 and npm v6.4.0.
Creating a new React app in D:\react\myreactapp.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

npm ERR! Unexpected end of JSON input while parsing near '...^1.0.1","line-numbers'

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\USER\AppData\Roaming\npm-cache\_logs\2018-08-26T11_04_03_908Z-debug.log

Aborting installation.
npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting myreactapp / from D:\react
Done.

A: It may have to do with the project name you gave it. Try using dragon-case, i.e. only lower case and hyphens.  So instead of
$ create-react-native-app myApp

use
$ create-react-native-app my-app

or from the error message, could it be that after the app name (myreactapp) you added a space and then pressed the back-slash instead of Enter, before pressing Enter again?
Also, try: npm cache clean --force
and if that doesn't do the trick: yarn cache clean
It may have been caused by a missing linebreak in the React-Native installation instructions in the Readme (that has been fixed since), between npm install and npm start causing users to do npm install npm start - which was installing npm itself with all its tests. See issue: https://github.com/facebook/react-native/issues/20015.
In any case it would be good if you ran react-native info and told us the result.


text:
Q: How to fetch exact match using where clause in PowerShell? Get-HotFix | Where-Object HotfixID -eq "KB97690"
if ($?) {
    Write-Output "success"
} else {
    Write-Output "F"
}

The above code result, how to check exact match hotfixid, if it hotfixid not matching fully it should fail.
But they above code however its through success.

A: You are misusing $?. This automatic variable contains the execution status of the last operation. Even if Get-HotFix | Where-Object HotfixID -eq "KB97690" has no result, the execution itself suceeds. That means, if($?) is $true for your script. You might be searching for a thing like:
$matchedUpdates = Get-HotFix | Where-Object {$_.HotfixID -eq "KB97690"}
if ($matchedUpdates) {
     Write-Host "I found at least one item for it."
}

There are many other ways to achieve what you are trying. Here we use the fact, that PowerShell equals an object / array with items to $true if provided to an if-statement and to $false if it's $null.

A: Other method:
Get-HotFix -Id "KB97690" -ErrorAction Ignore | %{"I found at least one item for it."}


text:
Q: Is Monocross ready for professional use on an iOS device? When creating a simple app with Monocross (using MonoTouch) and compiling for an iOS device I get some bad warnings, like this:
Warning MT4112: The registrar found a generic type: MonoCross.Touch.MXTouchViewController`1. Registering generic types with ObjectiveC is not supported, and will lead to random behavior and/or crashes. (MT4112).
I've read all I can find about using MonoTouch with generics on an iOS device and it's mostly not supported. My app currently works on an actual device, but the warnings worries me.
I guess my question is, what is the state of Monocross when you get these warnings even with the simplest of apps? Is it still not ready for professional use or are the warnings not relevant for the way generics is used in Monocross?
I can also add the following from Xamarin.iOS docs:
"Xamarin.iOS does not currently support creating generic subclasses of the NSObject class"
Which is exactly what Monocross does, with for example the MXTouchTableViewController class.

A: There is some history to this: creating generic subclasses of NSObject has never been a supported scenario, but unfortunately MonoTouch never enforced, nor warned about this fact. So people of course ended up doing exactly this.
Then one day I had to track down something that looked like a true heisenbug, and it turned out (after many hours of frustrating debugging) to be because the project in question was using generic subclasses of NSObject. The exact details are not important, but that's when the warning was added to MonoTouch.
My point here is people have been using generic subclasses of NSObject for a long time, without running into any problems. If you test your app extensively (which you should do anyway), don't worry about this.
But if you do run into strange and inexplicable behavior, we'll most likely ask you to fix these warnings before looking into any claims that you've found a bug in MonoTouch.


text:
Q: How to detect Active Setup in MSI i have a MSI installation package that is installed as SYSTEM User and adds an active setup entry to the registry. This setup makes sure when a new user(new = that has not executed this setup until now) is logging on msiexec adds all missing registry entries.
In the MSIEXEC i need to do a net use to mount the users home directory. This cannot be done as system user and needs to be done in the user context.
However i seem to be completely unable to detect that the setup is currently running on the user context. Thats why i thought it would be nice to give additional parameters to the StubPath in the active setup entry. I tried NETUSE=1. This however did nothing. The setup just ignored this parameter and uses the parameter given during installation. So NETUSE stays 0.
Any ideas what kind of condition i could use for my custom net-use action?

A: Why is an MSI mounting a users home directory?  I would write a small utility to do all this work and just have the MSI put it in the Run registry key.  Install once per machine as System and then when the user logs in the utility gets called and does whatever per-user work you need to have done.
If the installer legitimately needs to populate per user registry data then that is fine to continue the active setup pattern.

A: You can try to use your own custom action configured to run only when the LogonUser property is different tan SYSTEM.


text:
Q: Update Git password after changing GitHub password I know this question has been asked many times but none of the answers helped me, I've updated my password account on GitHub and now can't push anything on my GitHub repository.
I don't understand what I have to do to re-configure Git with my GitHub account, I'm pretty new to Git ...

A: Are you on OS X? If so, you may need to reset your local credential storage to the new password. See: https://help.github.com/articles/updating-credentials-from-the-osx-keychain/

A: If you are a Windows user, you can try to find a file named password and delete it, which maybe located in path: c:/user/(your name)/appdat/local/source tree(or some other client name)/.
I have been there and know your feeling.


text:
Q: Best practise to provide styling options in liferay ADTs I am using an ADT to display i.e. a table. I want to implement an option so people who configure the ADT can for example tick a checkbox and then the table changes so that a specific column is disabled.
Is this only possible via config files or is there an option to put this into the frontend?
Why would I want this? Because I have multiple systems and the column shall only be visible on some systems.
Thank you all for suggestions!


text:
Q: To limit number of items to be displayed in react predictive input Implementing React from couple of months. I used 'react-predictive-input' for predicting items from the pre-defined list on onchange event.
With "large" data sets (500/1000 items) the AutoComplete component becomes very slow especially when typing the first 3 characters because it will render many items in the dropdown slowing the entire interface, even using a maxHeight for the component.
Do we have any attribute as 'max-items' to show from the list?
Below is the snippet of code :
 <Autocomplete
         id="items"
         placeholder="My Items"
         data={this.props.items}
         onSelected={this.onItemSelected.bind(this)} />

Function is invoked if item is selected
 onItemSelected(value){
         console.log(`${value} was selected`);
     }

List of items
static defaultProps = {
  items:[
   'car','Bicycle','Truck','Green Van'............................1000items]
};

Text prediction works fine, speed and display are becoming an issue to handle.

A: I used Material UI Autocomplete for retrieving the use cases mentioned in the question. Link for reference here.


text:
Q: Behavior of Nullable.GetNullableType method I have some C# code to detect if a type is nullable, and to get the underlying type if so:
...
    Log.DebugFormat("type is {0}", type.FullName);
    Type underlyingType = Nullable.GetUnderlyingType(type);
    if (underlyingType != null)
    {
        Log.DebugFormat("underlying type is {0}", underlyingType);
    }
    else
    {
        Log.DebugFormat("underlying type is null");
    }
...

Unfortunately, it does not seem to work. Here's some output if the type is a nullable int:
...
    type is System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]&
    underlying type is null
...

I have seen similar code snippets that seem to work, so am not sure why mine is not working. One thing I notice is that the type name has an & at the end - could this be significant?
Thanks for your help!

A: Here's how to replicate your issue:
void Main()
{
    Type type;

    type = this.GetType().GetMethod("Method").GetParameters()[0].ParameterType;

    Console.WriteLine("type is {0}", type.FullName);
    Type underlyingType = Nullable.GetUnderlyingType(type);
    if (underlyingType != null)
    {
        Console.WriteLine("underlying type is {0}", underlyingType);
    }
    else
    {
        Console.WriteLine("underlying type is null");
    }
}

public void Method(out int? value)
{
    value = 42;
}

I get this:
type is System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]&
underlying type is null

The give away is the & at the end of the name. This means it's an out parameter. So, your type isn't just a int?, it's an out int?.
You need to call .GetElementType() on your type for this to work as expected.
If I do this:
type = this.GetType().GetMethod("Method").GetParameters()[0].ParameterType.GetElementType();

Then the output is:
type is System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
underlying type is System.Int32


text:
Q: How to include github markdown files into maven site Github recommends that Markdown-formatted files like README.md, LICENCE.md or CONTRIBUTORS.md are created in the root of the project. On the other hand, those files would be valuable content for automatically generated maven sites.
What would be the best practice to include those files into the generated site report?
One Idea I had was copying them into src/site/markdown and removing them again after successful site generation (to avoid SCM pollution).

A: I solved this problem for the file README.md in a Git repository using the approach you outlined in your question, that is copying README.md from the root directory to ${baseDir}/src/site/markdown. I used maven-resources-plugin to copy the file. Instead of removing the copied file after the site is generated (to avoid SCM pollution), I added it to .gitignore as Bruno suggested.
A detailed description of the solution follows.
In section project.build.plugins of pom.xml:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <executions>
        <execution>
            <!-- Copy the readme file to the site source files so that a page is generated from it. -->
            <id>copy-readme</id>
            <phase>pre-site</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <outputDirectory>${basedir}/src/site/markdown</outputDirectory>
                <resources>
                    <resource>
                        <directory>${basedir}</directory>
                        <includes>
                            <include>README.md</include>
                        </includes>
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>

In .gitignore:
# Copied from root to site source files by maven-resources-plugin
/src/site/markdown/README.md

You can see the corresponding commit here.

A: The contributors should be put into the pom. The license file should be part of the project usually LICENSE.txt as sibling to pom.xml file as Apache suggested. The README.txt is suggested by Apache as well. README.md is usually only valuable for GitHub to render this during the display of the repository.


text:
Q: clang 5.0 pdb support as of 2017 Here it is explained that clang now knows how to produce .pdb files (http://blog.llvm.org/2017/08/llvm-on-windows-now-supports-pdb-debug.html).
As far as I understand, at least clang with Microsoft linker is now expected to produce .pdb files equivalent to those produced by the msvc toolchain.
It is explained here how you can use mainstream Visual Studio 2017 to debug an "external" binary, that is one not built using projects/solutions (https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-debug-an-executable-not-part-of-a-visual-studio-solution).
I have compiled a simple hello world application with clang -g main.c -o main.exe which produced a .pdb file as expected.
However, when I try to step into it, Visual Studio complains that the .pdb file does not contain line number information.
In contrast, compiling with cl /EHsc /Zi main.c allows to debug with Visual Studio normally.
I am currently trying to understand if clang ecosystem is already good enough for developing on Windows, and will appreciate if somebody can explain:

*

*What is the difference between .pdb files produced by stable clang and msvc?

*Is there any difference between link and lld for that matter?

*Are things going to change in clang 6.0?

A: This works for me:
clang -g -gcodeview main.c -o main.exe

The option -gcodeview tells Clang to generate debugging information in Microsoft's CodeView format.
Visual Studio can then read the resulting .pdb without problems.
Another option would be to use clang-cl, which you can pass /Zi to, or MIEngine, which should allow you to use non-CodeView debugging information in Visual Studio.
I haven't tried neither of those, though.

For the record, this was my main.c:
#include <stdio.h>

int main() {
    getc(stdin); // pause to allow attaching the debugger
    return 0;
}

I used Clang 6.0.0.


text:
Q: Set path for Terminator to lookup for plugins In my work place we have Terminator installed on our machines but we do not have write access outside of our home folders. By default, terminator looks for pluings at /usr/share/terminator/terminatorlib/plugins, which I cannot use. I tried to copy my plugin to ~/.config/terminator/plugins/ but terminator doesn't load anything from that location.
How can I tell terminator to look in that folder, as well as the default one? Perhaps some entry in the config file, but I couldn't find anything in the documentation.
Edit:
As was asked in the comments, here is the output of apt-cache policy"
terminator:
  Installed: 0.97-2ubuntu0.1
  Candidate: 0.97-2ubuntu0.1
  Version table:
 *** 0.97-2ubuntu0.1 0
        500 http://de.archive.ubuntu.com/ubuntu/ trusty-updates/universe amd64 Packages
        100 /var/lib/dpkg/status
     0.97-2 0
        500 http://de.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages

A: Check the opened files with
strace -e open,access terminator 2>&1  | grep plugins

If your folder isn't in the output, something is wrong. And you should read the man page
man terminator_config

But in the meantime you have recognized it themselves. ;)

Terminator has two plugin folders. The system-wide folder /usr/share/terminator/terminatorlib/plugins and an user folder ~/.config/terminator/plugins.
I have tested the installation of plugins in the home folder with the plugin Terminator Editor Plugin:

*

*My terminator without this plugin

*Close all terminator  sessions

*Create the plugin folder
mkdir -p ~/.config/terminator/plugins

*Download the plugin
wget -P ~/.config/terminator/plugins https://raw.githubusercontent.com/mchelem/terminator-editor-plugin/master/editor_plugin.py

You should now see something like this
% ls -laog ~/.config/terminator/plugins
total 20
drwxrwxr-x 2 4096 Nov 19 14:39 .
drwxrwxr-x 3 4096 Nov 19 14:27 ..
-rw-rw-r-- 1 3438 Nov 19 14:39 editor_plugin.py

*Start terminator

*Check the content in ~/.config/terminator/plugins, you should see something like this:
% ls -laog ~/.config/terminator/plugins
total 32
drwxrwxr-x 2 4096 Nov 19 14:32 .
drwxrwxr-x 3 4096 Nov 19 14:27 ..
-rw-rw-r-- 1 3438 Nov 19 14:32 editor_plugin.py
-rw-rw-r-- 1 3811 Nov 19 14:32 editor_plugin.pyc

*Open Preferences > Plugins

*Activate the plugin EditorPlugin

A: The answer was explained in man terminator_config.
From man man terminator_config
Normally the config file will be ~/.config/terminator/config, but it may
be overridden with $XDG_CONFIG_HOME (in which case it will be
$XDG_CONFIG_HOME/terminator/config)

It turned out in my machine the default location for config is not $HOME/.config but $XDG_CONFIG_HOME/.config. Once I moved the plugin to that location, terminator immediately locate it.


text:
Q: How to get and display AJAX post JSON response on web page using JavaScript or jQuery? I want to display JSON Response on the response on web page. Once user logged in it should show username on the web page. The AJAX post method  returns the JSON data. Please let me know to how to accept the json data and how to display it. at backend side I have following code.
This is my AJAX JSON data response
{
"userId": 79,
"userName": "ruchika@gmail.com",
"password": null,
"firstName": "Ruchika",
"lastName": "S",
"phoneNumber": "123456789",
"emailAddress": "ruchika@gmail.com",
"gender": "FEMALE",
"dateOfBirth": null,
"status": null,
"addressLine1": "1267 Vicente Dr",
"addressLine2": "Apt 155",
"state": "CA",
"city": "Sunnyvale",
 "zipCode": "94087"
 }

once user loogged in I want to show username, first name and last name on the webpage.
//this is my interface implementation file
 @Override
public User getByUserName(String userName) {
    User user = new User();
    String GET_USER_ID = "select user_id,first_name,last_name,user_name,email_address,phone_number,date_of_birth,gender,address_line1,address_line2,state,city,zipcode from user WHERE user_name=:userName";
    SqlParameterSource sqlParameter = new MapSqlParameterSource().addValue("userName", userName);
   // user  =(User)getNamedParameterJdbcTemplate().query(GET_USER_ID, sqlParameter, new BeanPropertyRowMapper(User.class));

  //user data sending here in the JSON format

    return   getNamedParameterJdbcTemplate().query(GET_USER_ID,sqlParameter, new ResultSetExtractor<User>() {
        @Override
        public User extractData(ResultSet resultSet) throws SQLException, DataAccessException {
            User user = new User();
            while (resultSet.next())
            {

                    user.setUserId(resultSet.getLong("user_id"));
                    user.setFirstName(resultSet.getString("first_name"));
                    user.setLastName(resultSet.getString("last_name"));
                    user.setUserName(resultSet.getString("user_name"));
                    user.setEmailAddress(resultSet.getString("email_address"));
                    user.setPhoneNumber(resultSet.getString("phone_number"));
                    user.setDateOfBirth(resultSet.getDate("date_of_birth"));
                    user.setGender(Gender.valueOf(resultSet.getString("gender")));
                    user.setAddressLine1(resultSet.getString("address_line1"));
                    user.setAddressLine2(resultSet.getString("address_line2"));
                    user.setState(resultSet.getString("state"));
                    user.setCity(resultSet.getString("city"));
                    user.setZipCode(resultSet.getString("zipcode"));

            }
            return user;
        }
    });
   // return  user;
}

// this is my cotroller file
@Controller
public class LoginController {

@Autowired
private LoginService loginService;
@Autowired
private UserService userService;

private boolean loggedInResult;

@RequestMapping(value = "/v1/login", method = RequestMethod.POST)
public @ResponseBody
User signIn(@RequestBody LoginRequestDto loginRequestDto,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {

    User user = null;
    String userName = loginRequestDto.getEmailAddress();

    String password = loginRequestDto.getPassword();

    loggedInResult = loginService.validateUser(userName, password);

    if (loggedInResult==true)
    {
        response.setStatus(200);

        return userService.get(userName);

    }
    else
    {
         response.sendError(403);
    }
    return user;
 }
}

// this is my javascript file
function Logincheck()
{

var u1 =document.getElementById("Username_loginfrm").value;
var p1=document.getElementById("Password_loginfrm").value;

var JSONObject= {
    emailAddress:u1,
    password:p1
};

$.ajax({
    type: "POST",
    url: "http://localhost:8080/shareonwheels/v1/login",
    data: JSON.stringify(JSONObject),
    contentType: "application/json",

    success: function (response) {
        alert("User has been login successfully.");

        loginSuccessRedirect();
    },
    error: function (response) {

        alert("Invalid User");

        loginFailRedirect();
        document.getElementsByName('Username_loginfrm').focus();

    }

});
}

A: You can use
$("#divid").html(response);
where response is a JavaScript variable containing response of the REST call.


text:
Q: Please help me free this dynamically allocated array row = n + 1;
col = n + 1;
//used n+1 and i=-1 to avoid segmentation faults

board = malloc(row*sizeof(char *));
for(i=-1;i<row;i++)
{
    board[i] = malloc(col*sizeof(char));
    if(board[i] == NULL)
    {
        printf("Out of memory");
            exit(EXIT_FAILURE);
    }
}

for(i=-1; i < n+1; ++i)
{
    free(board [i]);
}
free(board);

When I try to free this array in run time, my compiler goes berserk, please explain, thank you.

A: arrays cannot have negative index in C.
at the line: for(i = -1; i < row;  i++)
I am very sure, there is an off by one error here, where free is freeing one extra block that was not malloc()ed at the end, and you must be getting a segfault error.

A: malloc returns void pointer, you must cast it. Also minimum index is zero in C.
    board = (char**)malloc(row*sizeof(char *));
    for(i=0;i<row;i++)
    {
        board[i] = (char*)malloc(col*sizeof(char));
        if(board[i] == NULL)
        {
        printf("Out of memory");
            exit(EXIT_FAILURE);
        }
    }