text:
Q: How can I permanently modify OS X's green window button? In older versions of Mac OS X, clicking the green button in a window title bar cause the window to grow in size, usually to grow to the full height and/or width of the screen.
In later versions, the behavior changed. Now clicking the green button causes the window to enter full-screen mode with both the menu bar and Dock hidden. Holding down the Option key while clicking the green button provides the grow-window behavior while changing the icon displayed when hovering.
I would like to revert to the old behavior where clicking the green button grows the window without going into full-screen mode.
Is there a way to permanently modify the behaviour of the green window button in OS X 10.11 (El Capitan)? Or more recent versions?
Perhaps some preference setting written with at command-line tool in Terminal.app?
Might be nice to reverse the behaviors, if possible:

*

*Click to grow window

*Option+click to enter full-screen mode.

The following approaches are not suitable solutions:

*

*Option+click

*Any app that provides a hotkey or drag options

*Spectacle

*BetterTouchTool

*Double-click the title bar

A: The behaviour you want to achieve is not trivially possible on OS X. The behaviour requires modifications to the underlying window management framework.
Individual application developers may be able to achieve this behaviour but this would go counter to Apple's Human Interface Guidelines. Going against these guidelines might risk the application being rejected from the Mac App Store.
Tell Apple
Send Apple your feedback and let them know what you want and, most importantly, why you want this behaviour.

A: rightzoom.app does exactly and just this. I used it under Yosemite, but not yet under Big Sur on M1


text:
Q: Json Deserialization failed failed in .NET 5 (Newtonsoft) when using derived class While trying to deserialize a complex derived object Json, which is actually created by serializing a viewmodel object in .NET 5 MVC. I am getting the base class properties of the derived object becomes nullified. Also most of the list items in the Viewmodel like SelectList, Ienumnerable<> also become nullified. I tried with a simple inheritance scenario also with 2 properties, unfortunately then also it failed.
Can someone explain how to solve this.
Example
public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode = "99999"; // initialize properties to generate sample data

    public Address()
    {

    }
}

// This will be serialized into a JSON Contact object
public class Contact : Address
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime? BirthDate { get; set; }
    public string Phone { get; set; }
    public Address Address { get; set; }

    public Contact()
    {

    }
}
public class ContactMain
{
    public Contact contact { get; set; }

    public ContactMain()
    {
        // initialize array of objects in default constructor to generate sample data
        this.contact = new Contact {
          Id = 7113,
          Name = "James Norris",
          BirthDate = new DateTime(1977, 5, 13),
          Phone = "488-555-1212",
          Address = new Address
          {
            Street = "4627 Sunset Ave",
            City = "San Diego",
            State = "CA",
            PostalCode = "92115"
          }
        };

var jsonString = JsonConvert.SerializeObject(contact);

}

Then trying to deserialze it with
JsonConvert.DeserializeObject<Contact>(jsonString);

Makes all the properties in Address Base class null

A: If you want to use base class property to derived class then you can directly call them by derived class object. Address property from Contact class.
 public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode = "99999"; // initialize properties to generate sample data

    public Address()
    {

    }
}

// This will be serialized into a JSON Contact object
public class Contact : Address
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime? BirthDate { get; set; }
    public string Phone { get; set; }

    public Contact()
    {

    }
}
public class ContactMain
{
    public Contact contact { get; set; }

    public ContactMain()
    {
        // initialize array of objects in default constructor to generate sample data
        this.contact = new Contact
        {
            Id = 7113,
            Name = "James Norris",
            BirthDate = new DateTime(1977, 5, 13),
            Phone = "488-555-1212",
            Street = "4627 Sunset Ave",
            City = "San Diego",
            State = "CA",
            PostalCode = "92115"
        };

        var jsonString = JsonConvert.SerializeObject(contact);

    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solve for two variables I have two variables $b_1$ and $b_0$ that are calculated by the following
$$
b_1 = i - p\\
b_0 = i + p
$$
I would like to be able to be able work the reverse, i.e. to determine $p$ and $i$ if I already have $b_1$ and $b_0$.
I must have fallen out of the stupid side of bed this morning as this looks like it should be simple, but I just cannot get it figured

A: Add and substract the equations to get
$$b_0 + b_1 = 2 i\\
b_0 - b_1 = 2 p$$
Divide by $2$, ready.

A: If you don't know how to "cleverly" approach a problem like this, then you can always use substitution: For example, from the first equation we obtain
$$
i=b_1+p\tag{1}
$$
and by inserting this expression for $i$ into the second equation we get
$$
b_0=i+p=(b_1+p)+p=b_1+2p\;\;\Longrightarrow \;\;p=\frac{b_0-b_1}{2}.
$$
Now that we have found an expression for $p$ we can go back to $(1)$ and insert this expression to get an expression for $i$:
$$
i=b_1+p=b_1+\frac{b_0-b_1}{2}=\frac{b_0}{2}+\frac{b_1}{2}.
$$
Note that we might as well have started by isolating $p$ in $(1)$ and obtained an expression for $i$ first. This will yield exactly the same result.
Of course, it is much easier to just add (or subtract) the two equations from each other as @Raskolnikov suggests, but this requires you get that idea.


text:
Q: How to draw a TBitmap32 transparently on a TBitmap? I am trying to draw a source image (GR32 TBitmap32) that contains some fully transparent and also partially transparent pixels on a normal (TBitmap) image while preserving the transparency in the source image.
I use this:
BMP32.DrawTo(BMP.Canvas.Handle, 0, 0);

but the image is not drawn transparently.

Code:
Everything is pretty basic: I have a background bitmap (Bkg) in which I load, at application start up, an image.
Then in procedure Apply I load a second image from disk (the one with transparency) and I draw the it over the background.
var Bkg: TBitmap;

procedure TfrmPhoto.FormCreate(Sender: TObject);
begin
 Bkg:= LoadGraphEx(GetAppDir+ 'bkg.bmp'); { Load bitmap from file }
 {
 Bkg.Transparent:= TRUE;
 Bkg.PixelFormat:= pf32bit;
 Bkg.TransparentColor:= clPink;
 }
end;

procedure TfrmPhoto.Apply2;
VAR
   Loader: TBitmap;
   BMP32: tbitmap32;
begin
 BMP32:= TBitmap32.Create;
 TRY

  Loader:= TBitmap.Create;
  TRY
   Loader.LoadFromFile('c:\Transparent.BMP');
   BMP32.Assign(Loader);
  FINALLY
   FreeAndNil(Loader);
  END;

  { Mix images }
  BMP32.DrawTo(Bkg.Canvas.Handle, 0, 0);    <----- The problem is here

  imgPreview.Picture.Assign(Bkg);    { This is a TImage where I see the result }
 FINALLY
  FreeAndNil(BMP32);
 END;
end;

A: It worked (but with 2 disadvantages) with TransparentBlt().

*

*I am not happy with the way TransparentBlt handles the semitransparent pixels (the edge of the rotate image). After merging the src image into the background the edges look bad.

*In order to use TransparentBlt, I had to define a color (clPink) in the source image as transparent. This means that if the source image has some pink in it, the result will look really nasty (it will be treated as transparent). Let's pray for non-pink images!
If you find a way to transfer the image (while preserving transparency) directly from Bitmap32 into the background please post and I will accept your answer!
A solution (still a hack) I see here is to process everything in a TBitmap32 and then 'export' the final result as TBitmap. I will try this tomorrow.

Update:
Solution:
This is how to merge two TBitmap32 images while preserving transparency:
 Dst.CombineMode:= cmBlend;
 Dst.DrawMode:= dmBlend;
 Src.Draw(0, 0, Dst);

Dst and Src are TBitmap32 images. It doesn't work with TBitmap.

A: As already suggested by yourself, I would recommend performing blending operations entirely in the TBitmap32 domain! The reason for this is the fact that it offers more choices in regards of blending and it uses MMX/SSE/SSE2 where available (on modern machines always the case). With this one can typically get a notable performance boost in contrast to letting GDI perform the blending.
In particular this is not a good idea as GDI typically does not make use of any SIMD opcodes (MMX/SSE).
It also depends on how much each part changes. For example, typically the background is rather static and need to be transfered into a TBitmpa32 only occassionally on changes (e.g. on VCL style or UI theme changes). With each transfer (GR32 <-> TBitmap and alike) an implict conversion (DIB <-> DDB) might happen, which makes the entire blending an O(n²) operation. So you'd better transfer (with an implicit conversion) to TBitmap32 just once and then perform the blending entirely in the GR32 domain.
On the contrary, if the TBitmap32 is rather static and the TBitmap (or background) changes a lot, it might probably be better to leave GR32 alone and copy the TBitmap32 to TBitmap and perform the blending with GDI. Despite the fact that the GDI blending is slightly slower, you avoid the additional copy. Otherwise your bottleneck will likely be the memory throughput, while processing speed never can touch the limits.

A: It is dmBlend DrawMode of TBitmap32 to turn on the transparency, but it only works between two TBitmap32 bitmaps. Do not use TBitmap32 with transparent images to draw directly on HDC, Canvas or TBitmap. Use dmBlend and DrawTo or BlockTransfer() to draw on another TBitmap32. For example, to draw transparently on a TBitmap, create an intermediary cache TBitmap32:

*

*Copy the image from TBitmap to the cache TBitmap32;

*Apply your transparent image to the cache TBitmap32 using DrawTo or BlockTransfer(), avoid using Canvas or HDC to mix two images because they lose alpha layer information;

*Copy the image back from the cache TBitmap32 to your TBitmap.


text:
Q: How to remove this lines from input group add on, bootstrap
How to remove the lines around the icon like place the icon inside the searchbox I tried background transparent border 0 still not working the border are still there
here's what I did

         <input type="text" name="search" id="search-building" class="form-control" placeholder="Search..." required>

CSS
.input-group-addon{
    border:0;
    background:white;
     pointer-events: none;

  }

A: Your css class rules aren't being applied because of the specificity... to solve it add a parent to your selector..

.input-group .input-group-addon{
    border:0;
    background:white;
     pointer-events: none;

  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

         <input type="text" name="search" id="search-building" class="form-control" placeholder="Search..." required>

A: Check this out.
UPDATED:
Changed as per the discussion below.

.input-group input {
      border-right: none;
}

.input-group .input-group-addon {
  background: inherit;
}

div {
  background: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

         <input type="text" name="search" id="search-building" class="form-control" placeholder="Search..." required>


text:
Q: Only show JSon by key value I got stuck to rendered JSON data by an id, already browse over the several articles but not working.
I had ajax call:
$.ajax({
    url: '../../../get/api/city.json',
    dataType: 'json',
})
.done(function(data){
    console.log(data);
    var HTML = '';
        $.each(data.city, function(i,city){
        HTML += ''+city.city_name+''; });

       $('#title').append(HTML);
    })
.fail(function(){
    alert('failed');
});

And the json output is:
{"city":[
{"id":"4","year":"2014","city_name":"City A"},
{"id":"5","year":"2014","city_name":"City B"},
{"id":"6","year":"2014","city_name":"City C"}]}

My situation I created a html page to render the information for City A, what I want is to filter the above JSON data only rendered the information from city A.
Big thanks for any help from you guys.
Thanks

A: You could add a filter to your $.each to check if the city id is the one you want.
$.each(data.city, function (i, city) {
    if (city.id === 4)
        HTML += '' + city.city_name + '';
});

A: Can prepare a filter with your desired city name and apply it to your data array to filter data preferred by you as in example:
var cities = {
  "city": [{
    "id": "4",
    "year": "2014",
    "city_name": "City A"
  }, {
    "id": "5",
    "year": "2014",
    "city_name": "City B"
  }, {
    "id": "6",
    "year": "2014",
    "city_name": "City C"
  }]
};

//Want only city with this name
var filter = "City A";

console.log(cities.city);

cities.city = cities.city.filter(function(obj) {
  return obj.city_name == filter;
});

console.log(cities.city);

A: Try the following using Array's filter():

var info = {"city":[
{"id":"4","year":"2014","city_name":"City A"},
{"id":"5","year":"2014","city_name":"City B"},
{"id":"6","year":"2014","city_name":"City C"}]};

var res = info.city.filter(function(item){
  return item.city_name =='City A';
});
console.log(res);
var HTML = ''+res[0].city_name+'';
$('#title').append(HTML)
HTML = ''+res[0].id+'';
$('#id').append(HTML);;
HTML = ''+res[0].year+'';
$('#year').append(HTML);

Title:

Id:

Year:

UPDATE:
Once your request server send data, you can use the following code:
$.ajax({
  url: 'http://207.254.40.122/deetab/json.json',
  dataType: 'json',
  crossDomain: true
}).done(function(data){
    console.log(data);// Check here whether sever send data or not
    var res = data.city.filter(function(item){
       return item.city_name =='City A';
    });
   //console.log(res);
   var HTML = ''+res[0].city_name+'';
   $('#title').append(HTML)
   HTML = ''+res[0].id+'';
   $('#id').append(HTML);;
   HTML = ''+res[0].year+'';
   $('#year').append(HTML);
});


text:
Q: $f$ converges then $f'$ converges to $0$? Let $f: \mathbb R \rightarrow \mathbb R$ continuous and differentiable. Assume that
$$
 \lim_{x  \rightarrow \infty} f(x) = y_0 \in \mathbb R
$$
Is it then true that
$$
 \lim_{x \rightarrow \infty} f'(x) = 0
$$ ?

A: Take $f(x) = \frac{1}{x}\sin(x^2)$ which converges to zero as $x \to \infty$ but $f^{'}(x) = \frac{-1}{x^2} \sin(x^2) + 2\cos(x^2)$ does not converge as $x \to \infty$.


text:
Q: Same server, both SSL and non-SSL Is it possible to have both SSL protocol and non-SSL protocol running on the same server in Apache 2.x?
So if I access http://example.com (non-SSL) and https://example.com (SSL) they would both be available.
If so, would I need to create a virtual host? How would this VirtualHost directive look like, could anyone give me an example? (Assuming I already have the certificates)

A: Yes, you simply add another VirtualHost for the same name on port 443 (HTTPS).
Set SSLProtocol to whichever protocols you wish to allow.
<VirtualHost *:80>
    ServerName your-domain.com
    DocumentRoot /var/www/your-domain-root
</VirtualHost>

<VirtualHost *:443>
    DocumentRoot /var/www/your-domain-root
    ServerName your-domain.com
    SSLEngine On
    SSLOptions +StrictRequire
    SSLCertificateFile /path/to/server.crt
    SSLCertificateKeyFile /path/to/server.key
    SSLProtocol TLSv1
</VirtualHost>


text:
Q: Exporting Cassandra table with DataStax Bulk Loader v1.8 complains about connection pool exhaustion I run it with these settings:
dsbulk unload -k keyspace -t table
  --connector.csv.delimiter "^"
  --engine.maxConcurrentQueries=4
  --connector.csv.url
  ...

application complains about connection pool exhaustion --> application gets timeouts on connections to cassandra.

*

*cassandra version 2.13

*cassandra features: 3 nodes - 64 cpu/124Gb ram on each node.

explain on settings dsbulk?

A: It sounds like your cluster is getting overloaded and cannot handle the unload operation.
You will need to throttle DSBulk to lower the amount of requests. Here are some options you can use as starting points to limit the load on your cluster:
    --driver.advanced.continuous-paging.page-size 1000
    --driver.advanced.continuous-paging.max-pages 10
    --engine.maxConcurrentQueries 5
    --executor.maxPerSecond 5
    --executor.maxInFlight 5

For details on these options, see:

*

*DSBulk Driver options

*DSBulk Engine options

*DSBulk Executor options
With these settings, it will take a little longer for the unload operation to complete but it will at least minimise the risk of taking down your cluster. Cheers!


text:
Q: Python Select first word in a string without using methods I have a homework assignment where I have to select the first word in a string. Normally I would do this:
s = "Hello World"
words = s.split()
first_word = words[0]
print(first_word)

For this assignment I cannot use methods or loops to answer the question. Any ideas?

A: Find the index of the first space character, then use string slicing:
s = "Hello World"

print(s[:s.index(' ')])

No loops, but does use the .index() method...
Could also try a recursive function:
s = "Hello World"

def first_word(string):

    if string[0] == ' ':
        return ''
    else:
        new_string = string[0] + first_word(string[1:])
    return new_string

print(first_word(s))

A: As you can't use methods and loops, you could do it using recursion.
def r(a, b=''):
     if len(a) == 0 or a[0] == ' ':
         return b
     return r(a[1:], b + a[0])

s = 'Hello World'
print(r(s))

would print Hello.

A: This could be fine
s = "Hello World"
s.split()[0]

but a way without any method could be
s[0:5]

A: This recursion is very similar to MacieK's:
(edited to allow non space word delimiters)
def hello(s):

    delims = ' ,-'

    if s == '' or s[:1] in delims: return

    print(s[:1], end='')

    hello(s[1:])

hello('Hello, World')


text:
Q: SharePoint 2013 Workflow Authentication Error 401 I'm trying to let a SharePoint 2013 workflow run as a regular user (not a site collection administrator).
When starting the workflow it fails right away with the error:
RequestorId": c0c2fcc9-abfb-6e2b-f229-68417fb5815c. Details: System.ApplicationException: HTTP 401 {"Transfer-Encoding":["chunked"],"X-SharePointHealthScore":["0"],"SPRequestGuid":["c0c2fcc9-abfb-6e2b-f229-68417fb5815c"],"request-id":["c0c2fcc9-abfb-6e2b-f229-68417fb5815c"],"X-FRAME-OPTIONS":["SAMEORIGIN"],"MicrosoftSharePointTeamServices":["15.0.0.4420"],"X-Content-Type-Options":["nosniff"],"X-MS-InvokeApp":["1; RequireReadOnly"],"Cache-Control":["max-age=0, private"],"Date":["Mon, 04 Feb 2013 15:55:21 GMT"],"Server":["Microsoft-IIS\/8.0"],"WWW-Authenticate":["NTLM"],"X-AspNet-Version":["4.0.30319"],"X-Powered-By":["ASP.NET"]} Der HTTP-Antwortinhalt konnte nicht gelesen werden. "Error while copying content to a stream.". bei Microsoft.Activities.Hosting.Runtime.Subroutine.SubroutineChild.Execute(CodeActivityContext context) bei System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) bei

In the ULS logs I can find the error "Permission check failed. asking for 0x10000, have 0x2000000000", coming from "Authentication Authorization" which I find pretty weird (what permissions are 0x10000 etc.).
When I set the user trying to execute the workflow as site collection administrator, the workflow runs through smoothly.
02.04.2013 16:24:43.64  w3wp.exe (0x1594)       0x0E04  SharePoint Foundation Authentication Authorization    ag6al                Medium              OAuth app principal Name=i:0i.t|ms.sp.ext|21c57850-ff6e-4fb6-9aa4-201733bf3f18@6a9b095b-7157-4a94-96f2-a27dd438b36d, IsAppOnlyRequest=False, UserIdentityName=0#.w|testdomain\testoffice11, ClaimsCount=18       c0c2fcc9-abfb-6e2b-f229-68417fb5815c
02.04.2013 16:24:43.64  w3wp.exe (0x1594)       0x12E8  SharePoint Foundation CSOM   agw10   Medium              Begin CSOM Request ManagedThreadId=34, NativeThreadId=4840   c0c2fcc9-abfb-6e2b-f229-68417fb5815c
02.04.2013 16:24:43.66  w3wp.exe (0x1594)       0x12E8  SharePoint Foundation Logging Correlation Data             xmnv                Medium              Site=/   c0c2fcc9-abfb-6e2b-f229-68417fb5815c
02.04.2013 16:24:43.66  w3wp.exe (0x1594)       0x12E8  SharePoint Foundation Authentication Authorization    ag69m                Medium              TenantScopedPerm=0, AllowAppOnlyPolicy=False, AppId=i:0i.t|ms.sp.ext|21c57850-ff6e-4fb6-9aa4-201733bf3f18@6a9b095b-7157-4a94-96f2-a27dd438b36d.    c0c2fcc9-abfb-6e2b-f229-68417fb5815c
02.04.2013 16:24:43.66  w3wp.exe (0x1594)       0x12E8  SharePoint Foundation Authentication Authorization    ajmmu                Medium              Permission check failed. asking for 0x10000, have 0x2000000000             c0c2fcc9-abfb-6e2b-f229-68417fb5815c
02.04.2013 16:24:43.66  w3wp.exe (0x1594)       0x12E8  SharePoint Foundation General               ftd0       Medium                Access Denied. Exception: Es wurde versucht, einen nicht autorisierten Vorgang auszuführen., StackTrace:   bei Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(Exception ex)     bei Microsoft.SharePoint.SPSecurableObject.CheckPermissions(SPBasePermissions permissionMask)     bei Microsoft.SharePoint.Client.SPClientServiceHost.OnBeginRequest()     bei Microsoft.SharePoint.Client.Rest.RestService.ProcessQuery(Stream inputStream, IList`1 pendingDisposableContainer)     bei Microsoft.SharePoint.Client.ClientRequestService.ProcessRestQuery(Stream inputStream)     bei SyncInvokeProcessRestQuery(Object , Object[] , Object[] )     bei System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)     bei System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)     bei System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)     bei System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)     bei System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)     bei System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)     bei System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)     bei System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)     bei System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)     bei System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)     bei System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)     bei System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)     bei System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)     bei System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, Action dequeuedCallback, Boolean canDispatchOnThisThread)     bei System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.CompleteParseAndEnqueue(IAsyncResult result)     bei System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.HandleParseIncomingMessage(IAsyncResult result)     bei System.Runtime.AsyncResult.SyncContinue(IAsyncResult result)     bei System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action dequeuedCallback, AsyncCallback callback, Object state)     bei System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.ProcessHttpContextAsync()     bei System.ServiceModel.Channels.HttpChannelListener`1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)     bei System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)     bei System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()     bei System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()     bei System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)     bei System.ServiceModel.AspNetPartialTrustHelpers.PartialTrustInvoke(ContextCallback callback, Object state)     bei System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequestWithFlow(Object state)     bei System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)     bei System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)     bei System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)  .           c0c2fcc9-abfb-6e2b-f229-68417fb5815c
02.04.2013 16:24:43.66  w3wp.exe (0x1594)       0x12E8  SharePoint Foundation CSOM   afxwb   High                System.UnauthorizedAccessException: Es wurde versucht, einen nicht autorisierten Vorgang auszuführen.     bei Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(Exception ex)     bei Microsoft.SharePoint.SPSecurableObject.CheckPermissions(SPBasePermissions permissionMask)     bei Microsoft.SharePoint.Client.SPClientServiceHost.OnBeginRequest()     bei Microsoft.SharePoint.Client.Rest.RestService.ProcessQuery(Stream inputStream, IList`1 pendingDisposableContainer)  c0c2fcc9-abfb-6e2b-f229-68417fb5815c
02.04.2013 16:24:43.66  w3wp.exe (0x1594)       0x12E8  SharePoint Foundation CSOM   agmjp   High       Original error: System.UnauthorizedAccessException: Es wurde versucht, einen nicht autorisierten Vorgang auszuführen.     bei Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(Exception ex)     bei Microsoft.SharePoint.SPSecurableObject.CheckPermissions(SPBasePermissions permissionMask)     bei Microsoft.SharePoint.Client.SPClientServiceHost.OnBeginRequest()     bei Microsoft.SharePoint.Client.Rest.RestService.ProcessQuery(Stream inputStream, IList`1 pendingDisposableContainer)  c0c2fcc9-abfb-6e2b-f229-68417fb5815c
02.04.2013 16:24:43.66  w3wp.exe (0x1594)       0x12E8  SharePoint Portal Server             Microfeeds        aizmo                Medium              SocialRESTExceptionProcessingHandler.DoServerExceptionProcessing - SharePoint Server Exception [System.UnauthorizedAccessException: Es wurde versucht, einen nicht autorisierten Vorgang auszuführen.     bei Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(Exception ex)     bei Microsoft.SharePoint.SPSecurableObject.CheckPermissions(SPBasePermissions permissionMask)     bei Microsoft.SharePoint.Client.SPClientServiceHost.OnBeginRequest()     bei Microsoft.SharePoint.Client.Rest.RestService.ProcessQuery(Stream inputStream, IList`1 pendingDisposableContainer)] c0c2fcc9-abfb-6e2b-f229-68417fb5815c

I tried giving the user trying to execute the workflow Site Owner permissions, Site Reader or Site Contributor - in all cases the workflow fails. Only a site collection administrator (the user or another admin) can start a workflow.

Edit: I looked into the SPBasePermissions. The error is actually saying "Permission check failed. asking for "Open", have "UseRemoteAPIs"".

A: The problem was related to the OU the users where in.
My main OU was at DOMAIN > MainOU > SubOU - in that OU are all my SharePoint groups and users. Let's take the "SharePoint Users" group as an example in that OU. It has permissions to contribute on the SharePoint.
I now had a different OU at DOMAIN > DifferentOU for test users. I gave these test users permissions on SharePoint by putting them also in the SharePoint Users group.
This is what was causing the problem:
When adding users in the same AD branch (same OU) everything is fine. But once users come from a different parallel branch (different OU), somehow the security doesn't work and I get the said error message.
To solve the problem I only had to run the User Profile Synchronization.


text:
Q: Estimating DIC for a zoib beta regression model I have the data and code below and would appreciate your help to estimate DIC (or AIC) for a beta regression model with zoib:
library(zoib)
data("GasolineYield", package = "zoib")
re.md <- zoib(yield ~ temp | 1 | 1, data=GasolineYield,
joint = FALSE, random=1, EUID=GasolineYield$batch,
zero.inflation = FALSE, one.inflation = FALSE,
n.iter=3200, n.thin=15, n.burn=200)
sample2 <- re.md$coeff
summary(sample2)

Following the package's vignette and the article published by the authors, I implemented the code below to get DIC, but I get an error:
dic.samples(sample2, n.iter=201, thin = 1, type="pD")
Error in nchain(model) : Invalid JAGS model object in nchain

I ran the same code with an object from coda.samples {rjags} documentation and it worked:
data(LINE)
LINE$recompile()
LINE.out <- coda.samples(LINE, c("alpha","beta","sigma"), n.iter=1000)
summary(LINE.out)
dic.samples(LINE, n.iter=201, thin = 1, type="pD")

Then I checked the class of each of the objects above LINE, sample2, re.md, and LINE.out, and the output is:
class(LINE)
"jags"
class(re.md)
"list"
class(sample2)
"mcmc.list"
class(LINE.out)
"mcmc.list"

This suggests that my error is probably because the object sample2 is not of class jags.
Therefore, I would appreciate any ideas on how I can get sample2 in a form that can be accepted by dic.samples  in order to be able to get DIC (or AIC) for my rd.md model.


text:
Q: Generate summary from robot framework log file we are using Jenkins for installation which is there from many years in our product.
But now I want to enhance it, we have some basic tests run for each component, each has its own robot log file placed in a folder.
I want a create a batch file using windows cmd to parse all log files in that folder, and get me the test cases which are failed.
Any idea how it can be done?
Thanks

A: I think, you requirement is rebot option of Robot Framework.
Consider, you have two test suites which are executed separately.

*

*valid_login.txt

*invalid_login.txt

Each test suite create three log files in Robot framework.

*

*report.html

*log.html

*output.xml

First thing, you need to create the unique name for these all logs.
This can be done using :

*

*-r for renaming report.html

*-l for renaming log.html

*-o for renaming output.xml

Example:
pybot -d "F:\robot framework\WebDemo\Logs" -o "invalid_login.xml" -l "invalid_login.html" -r "invalid_login_report.html" invalid_login.robot

In this way, after executing, you will have two set of reports.
Since you want to merge the reports and create the combined report, we will first create only XML log for each test suite.
pybot -d "F:\robot framework\WebDemo\Logs" -o "invalid_login.xml" -l None -r None invalid_login.robot

Above example will create only XML log file in given directory mentioned with -d option.
Once you execute above both test suites, it will create two XML log files.

*

*invalid_login.xml

*valid_login.xml

Now, you can merge the both XML and create combined report using below command.
F:\robot framework\WebDemo>rebot Logs\*.xml
Log:     F:\robot framework\WebDemo\log.html
Report:  F:\robot framework\WebDemo\report.html

F:\robot framework\WebDemo>invalid_login

rebot will take all XML files in Logs directory and create combined Log and Report file.
Check this link for more info !!!
Once you combined the all reports, you can filter the Failed test cases easily in report.html


text:
Q: Sketch a line in NetLogo From it's coefficents How can a draw a line in NetLogo given in the following form:
                                    Ax+By+C=0

That is, A , B and C are given.
CODE:

    to make-line[a]; a is list containing A, B and C and in that order.
    let x 0
    let y((-item 2 A) / item 1 A)
    let y1 0
    let x1((-item 2 A) / item 0 A)
    crt 1[
      set size 0.5 setxy x y
      pen-down
      facexy x1 y1
      while [distancexy x1 y1 > 0.5]
          [
           fd 0.1
          ]
         ]
     end

PROBLEM:
The points tend to be outside the NetLogo boundaries many a lines.
Given the coefficients of a line, is there a way to draw one using any extensions or library functions directly


text:
Q: Count using a category and Median using a category I have two problems here.
The data is as follows:
Col X Col Y
    A 10
    A 12
    A
    A 32
    B 11
    B 31
    B 9
    C 8
    C 7
    C 3
    D 1
    D 3
    D
    D 9

I need to do the following:

*

*Count the entries in Column Y using the Categories in Column X, for ex. A repeats 4 times in Column X but has 3 total corresponding numbers in column Y, i need the 3 count of the numbers in Column Y.

*Calculate the median of those numbers using the category (excluding blanks whenever there are, not to be assumed as 0 by the code), for ex. Median for A is 12, Median for D will be 3.

Please help.

A: So 1 is:
=COUNTIFS(X:X,"A",Y:Y,"<>")
2 is:
=MEDIAN(IF(X:X="A",IF(NOT(ISBLANK(Y:Y)),Y:Y)))
Hold down ctrl + shift when you're using 2 as it's an array formula


text:
Q: which component is responsible for setting regionManager? which component is responsible for setting regionManager?
I am following the hands-on lab on prism on
http://msdn.microsoft.com/en-us/library/ff921141(v=pandp.40).aspx
public HelloWorldModule(IRegionManager regionManager)
    {
        this.regionManager = regionManager;
    }

I am wondering which component is setting regionManager?

A: It's a dependency injection pattern; the Unity framework (UnityBootstrapper to be exact) is setting the regionManager.  You can see the code under Prism.UnityExtensions\UnityBootstrapper.cs in the Prism download:
In the ConfigureContainer method:
RegisterTypeIfMissing(typeof(IRegionManager), typeof(RegionManager), true);

And in the Run method:
RegionManager.SetRegionManager(this.Shell, this.Container.Resolve<IRegionManager>());

You'll notice that the HelloWorldModule inherits IModule which is the Unity Prism interface whose implementation the UnityBootstrapper injects into the class.

If you're not familiar with Dependency Injection, this is its classic pattern; a class requests any external dependencies (IRegionViewRegistry in this case) via its constructor, and the DI framework is responsible for injecting the actual implementations.


text:
Q: Cumulated Products (Multiplications) of Array in Excel I would like to obtain the cumulated products of an array, also calculated through an array formula.
What that means is, assuming I have an array of numeric values, I want to do a row-wise multiplication of all values up to that row. The following screenshot might clarify the task:

I was trying to do it as follows, where the range of 'rates' in the screenshot above is named 'Rates'. I split the vector of n values into an n-times-n matrix where each column includes one more value than the previous one:

Here using the formula:
=(ROW(Rates)<TRANSPOSE(ROW(Rates))+1)*Rates

And then I would have to take the product of each column (value > 0 condition) through an array formula, but I didn't find a way to that yet.
Notes:

*

*I'm using Office 365 (x64), but BYCOL() and BYROW() are not available to me.

*All values of the 'rates' vector are strictly positive.

*I'm trying to avoid VBA to keep the file in .xlsx format since it is often removed from emails otherwise.

*I want to use the table as a template where the 'rates' vector would come in various sizes in the future, hence a dynamic array solution would be best.

I'd appreciate your input.

A: With SCAN:
=SCAN(1,Rates,LAMBDA(κ,λ,κ*λ))
Without some of the newer O365 functions, a non-volatile solution might not be straightforward. A volatile option would be:
=SUBTOTAL(6,OFFSET(INDEX(Rates,1),,,SEQUENCE(ROWS(Rates))))


text:
Q: I'm trying to follow a discord bot tutorial and I'm not sure how to fix an invalid syntax ctx error I'm extremely new to coding, mainly just giving it a shot to attempt to make my own Discord bot. I'm not sure what I'm doing at all, so I've been following different youtube tutorials with varrying degrees of failure. The most recent one keeps saying a I have a syntax error, and I have no idea how to fix this. Here is the code:
1 import os
2 import discord
3 from discord.ext import commands
4
5 bot = commands.Bot(command_prefix="!", intents = discord.Intents.all()
6
7 @bot.command()
8 async def hello(ctx):
9  await ctx.send("Hello")
10 token = os.environ['TOKEN']
11 bot.run (token)

I have already used the secrets function to put the actual token in, and I've done my best to follow the tutorial as closely as possibly, but I am kind of clueless with this stuff so any help would be appreciated.
I've tried editing the text, adding quotations to the hello and removing them when realizing it did nothing to fix the problem. I'm at a loss.


text:
Q: Problem with programmatically changing DCOM settings I'm having a problem with testing a VB.NET program I'm using to programmatically change the DCOM launch / activation and access permissions for an OPC Server application (application is Kepware V5).
I've made a test program based on the following:
https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/21c80f4a-4d5e-4334-a33e-1c94e35fcfb4/verify-and-correct-dcom-setting-using-wmi?forum=windowscompatibility
I'm having no issue with the code and my test application is successfully adding a user (NewTestUser) to the DCOM 'Launch and Activation permissions' and the 'Access permissions' for the Kepware application.
I verify this by checking the 'Launch and Activation permissions' and the 'Access permissions' for the Kepware application in the Windows 'Component Services' DCOM configuration tool shown here:

However when I reboot the machine and I try to connect a local OPC client to the OPC server application (Kepware V5).
I get the following messge in the event log:
The application-specific access security descriptor for the COM Server application C:\Program Files (x86)\Kepware\KEPServerEX 5\server_runtime.exe with APPID
{B3AF0BF6-4C0C-4804-A122-6F3B160F4397}
is invalid. It contains Access Control Entries with permissions that are invalid. The requested action was therefore not performed. This security permission can be corrected using the Component Services administrative tool.
I get the above message despite the fact that I can see all the users (including the newly added user) in the 'Component Services' screen for the application without any sign of anything being wrong.
I can resolve this by changing any one of the NewTestUser values for the settings in the DCOM 'launch and activation permissions' and the 'access permissions' for the Kepware application.
Basically by changing any one of the values and saving the change and then changing the value back to its original value this gets the local OPC comms to work (after reboot).
So it seems that the act of changing the settings (and changing back again) from 'Component Services' resolves the issue.
Being forced to do this defeats the purpose of my program.
Perhaps saving the settings from 'Component Services' is saving a change somewhere else in the registry besides what is shown on the screen?
I'm stuck on this so if anyone has any idea any help would be appreciated.


text:
Q: Get mongo shell BinData as string How do I convert BinData object that contains UTF-8 encoded text to a string?
I'm using MongoDB shell (the mongo command). It's basically Javascript interactive console (I think it's SpiderMonkey), but there is no Buffer object like in Node.js to work with the hex or base64 format that BinData object provides.

A: I can use conversion from BinData to hex and then parse the hex string.
function hex2a(hexStr) {
  var s = '';
  for (let i=0; i<hexStr.length; i+=2)
    s += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
  return s;
}

hex2a(BinData(0,"aGVsbG8=").hex())
// returns "hello"

But that works correctly only with ASCII.


text:
Q: Delete duplicate headers in awk I used used cat to combine several files and they all have the same headers. Is there anyway I can retain the 1st occurrence of the header and delete the succeeding headers inside the concatenated file?
Thanks!
Example:
FirstName, LastName, Phone, Zip
(data)
(data)
(data)
FirstName, LastName, Phone, Zip
(data)
(data)
(data)

A: You can do this:
cp file1 result
tail -q -n +2 file2 file3 file4 >> result

That is, start with the entire contents of file1, then append from the other files starting with line 2 of each.  This way you avoid the need to try to find the extra headers and delete them later.
If you prefer, here's another formulation of the same:
head -1 file1 > result
tail -q -n +2 file1 file2 file3 file4 >> result

A: Try this:
sed -e '2,$s/FirstName, LastName, Phone, Zip//g' -e '/^$/d' Yourfile.txt

You can replace "FirstName, LastName, Phone, Zip" with whatever header you have. From 2nd line to end of file, it will remove the header patter with , then delete the blank lines with /^$/d'

A: I'd do it this way:
sed '1h;2,$G;s/^\(.*\)\n\1$//;/./P;d' filename

A: Here is an awk version.  It will skipp all line with FirstName except line 1
awk 'NR>1 && /^FirstName/ {next}1' file
FirstName, LastName, Phone, Zip
(data)
(data)
(data)
(data)
(data)
(data)

If the header line do changing, we need a pattern to follow.

A: awk way
awk '!a[$0];NR==1{a[$0]++}' file


text:
Q: Menu Dropdown do Bootstrap em site asp.net funciona apenas na página principal, o que fazer para corrigi-lo? O menu dropdown aparentemente funciona na página principal, mas quando estou em outra página e vou utilizá-lo ele não funciona! Já verifiquei se no código HTML está gerando com o jQuery e não vi nada de estranho. O que fazer?

               sis

                        Cadastros

Consulta de Pessoa Fisica

A: Você não precisa colocar o jquery de ativação do dropdown a não ser que queira utilizar algum evento em conjunto com o clique ou qualquer outra coisa - Só com formatação você consegue colocar ele para funcionar. Retire também os js externos não necessários:
http://www.bootply.com/Y60uWy24UY

            sis

          Cadastro

Consulta de Pessoa Fisica

Another action

Something else here


text:
Q: Hide partial background repeat Consider these simple CSS rules:
jsFiddle
div#container {
    width: 50%;
    height: 260px;
    background-image: url('Image.png');
    background-repeat: repeat-x;
}

The problem is that I only want full images. If there is not enough space for another duplicate, it should NOT be shown.
I've never heard that CSS provides a rule for it. So how can I achieve it in JavaScript (jQuery already included)?

A: This is not possible with current CSS rules. You can repeat once, or repeat forever. The alternative is to shrink the size of the containing element to fit the nearest repeating point in either CSS (if you know the width before page load) or JS (if you don't).
Here's the latter implentation using jQuery:
var $container = $("#container");
var bgImg = extractUrl($container.css("background-image"));
var $img = $("", { "src" : bgImg }).hide().appendTo("body");

$container.width(nearest($("#container").width(), $img.width()));
$img.remove();

function extractUrl(input) {
    // remove quotes and wrapping url()
    return input.replace(/"/g, "").replace(/url\(|\)$/ig, "");
}

function nearest(n, v) {
    n = n / v;
    n = Math.floor(n) * v;
    return n;
}

Example fiddle

A: This will work for percentage widths and auto adjusts on sreen resize.
$(window).on('load resize', function () {
    var img = $('');
    img.attr('src', 'http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg').load(function () {
        var height = this.height;
        var width = this.width;
        var divWidth = $('#containerwrap').width();
        var extra = divWidth % width;
        $('div#container').width(divWidth - extra);

    });
});

div#container {
    width: 670px;
    height: 260px;
    margin:0 auto;
    background: url('http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg') left center;
    background-repeat: repeat-x;
}
#containerwrap{
    width:100%;
    height: 260px;
    background-color:#000000;
}

    Test

http://jsfiddle.net/upjkd/14/show

A: As the width is fixed by the server, and the server knows the size of the image - why not construct the image to be correct and forget the repeat, or make the width the appropriate size so it will fit whole number of images?

A: See http://jsfiddle.net/upjkd/10/
var img=document.createElement('img');
img.src="http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg";
document.body.appendChild(img);
var con=document.getElementById('container'),
    numImages=Math.round(con.clientWidth/img.clientWidth);
con.style.backgroundSize=con.clientWidth/numImages+'px';
document.body.removeChild(img);

You can use Math.round(con.clientWidth/img.clientWidth) to determine the number of repetitions of the image, and then use con.style.backgroundSize=con.clientWidth/numImages+'px' to be sure that the number of images is an integrer (only full images).


text:
Q: How can my Maven project run both JUnit and TestNG without TestNG trying to run JUnit tests? I have a Maven project in which I am required to execute both JUnit and TestNG tests. My pom.xml has setup the Maven Surefire plugin as follows:
<!-- ... -->
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.19.1</version>
  <configuration>
    <argLine>-Xmx1024m</argLine>
    <threadCount>1</threadCount>
  </configuration>
  <dependencies>
    <dependency>
      <groupId>org.apache.maven.surefire</groupId>
      <artifactId>surefire-testng</artifactId>
      <version>2.19.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.surefire</groupId>
      <artifactId>surefire-junit47</artifactId>
      <version>2.19.1</version>
    </dependency>
  </dependencies>
</plugin>
<!-- ... -->

Unfortunately, when I execute my unit tests using Surefire, all tests are correctly executed, but TestNG appears to be trying to execute the JUnit tests a second time, and an exception like the following is appearing in the logs.
org.testng.TestNGException:
Failure in JUnit mode for class com.hotwire.api.pricing.impl.PricingConfigIT: could not create/run JUnit test suite:
Cannot find JUnit method class junit.framework.TestSuite$1.warning
at org.testng.junit.JUnitTestRunner.runFailed(JUnitTestRunner.java:239)
at org.testng.junit.JUnitTestRunner.start(JUnitTestRunner.java:232)
at org.testng.junit.JUnitTestRunner.run(JUnitTestRunner.java:213)
at org.testng.TestRunner$1.run(TestRunner.java:672)
at org.testng.TestRunner.runWorkers(TestRunner.java:1003)
at org.testng.TestRunner.privateRunJUnit(TestRunner.java:703)
at org.testng.TestRunner.run(TestRunner.java:610)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:87)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1170)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1095)
at org.testng.TestNG.run(TestNG.java:1007)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:132)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:198)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:94)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:147)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)

How can I prevent this exception from polluting my logs?

A: I thought that I would share my answer because it took a little while to figure out and my particular problem is somewhat different than the problems of others who have encountered this particular stack trace.
The solution is to add the following XML element to Surefire's configuration in the pom.xml file.
<configuration>
  <!-- pre-existing config -->
  <properties>
    <property>
      <name>junit</name>
      <value>false</value>
    </property>
  </properties>
</configuration>

This is documented further in the Surefire documentation on running JUnit and TestNG tests together.


text:
Q: Why are new dependencies not picked up by Play 2.3.4 project in Eclipse? I updated my project to include some dependencies with the following lines in build.sbt:
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.33"
libraryDependencies += "org.springframework" % "spring-jdbc" % "4.1.1.RELEASE"

classes_managed was added to the classpath, but the directory does not exist and the libs are not present.
I cleaned the project, removed all errors (including all references to the classes in the managed libs), compile, but still the directory and libs are missing.
SBT does not seem to want to download the libs... not sure what I am doing wrong.

A: Any dependency managed by sbt ends up in ~/.ivy2/cache (it's configurable).
When you declare a project's dependency with libraryDependencies you should execute update (explicitly) or any other command to build up your project assembly like package or assembly that is going to pull them down (via update implicitly).
One caveat might be that you may've changed build.sbt without reloading a sbt session that makes the changes with no effect on the build. You should do reload to re-read the build definition or close sbt and start over.
A very helpful command to see what libraryDependencies are in use is show libraryDependencies. It's going to show you all the dependencies sbt knows about.
Once it's done, run eclipse command that prepares the files for the IDE. Do project reload in Eclipse and all should be fine.
It equally applies to sbt or Typesafe Activator (and partially IntelliJ IDEA).


text:
Q: Finding Median Mysql Trying to find the median for an array in a MYSQL database.
Currently, I am grabbing my data like so:
$middleMonth = "SELECT Day, COUNT(Day) AS totalNumber FROM finalbaby GROUP BY Day ORDER BY COUNT(Day) DESC LIMIT 1, 300";
$middleResult = mysql_query($middleMonth);

I am then putting it into an array like so.
$names=array();
while($row = mysql_fetch_assoc($middleResult)) {
$names[] = $row['Day'];

I am then trying to find the median of that array:
            sort($names);
            $count = count($names);
            $middleval = floor(($count-1)/2);
                if($count % 2) {
                    $median = $names[$middleval];
                } else {
                    $low = $names[$middleval];
                    $high = $names[$middleval+1];
                    $median = (($low+$high)/2);
                }

        return $median;

        }

        var_dump($names);

I am not getting any errors, but it crashes my application.
Any suggestions on what I am doing wrong?

A:
are you closing the while in your second code black before your third code block?

answered:

I close the while in my last }

Fail... close while in second code block before running code in third code block... this will find the median only once instead of trying to find the median every time you set a name from a mysql returned row. The first time, the count of names would be 1 and then you subtract 1 = 0 and divide by two. This will give you 0. Then you try to get the remainder of 0 and 2. This throws off the rest of your code. Try this:
$middleMonth = "SELECT Day, COUNT(Day) AS totalNumber FROM finalbaby GROUP BY Day ORDER BY COUNT(Day) DESC LIMIT 1, 300";
$middleResult = mysql_query($middleMonth);
$names=array();
while($row = mysql_fetch_assoc($middleResult)) {
    $names[] = $row['Day'];
}
sort($names);
$count = count($names);
$middleval = floor(($count-1)/2);
if($count % 2) {
    $median = $names[$middleval];
} else {
    $low = $names[$middleval];
    $high = $names[$middleval+1];
    $median = (($low+$high)/2);
}
echo $median;
var_dump($names);

//previous code
//if this code is inside function then return if not then print
//return $median;
//if this code is inside function then the return above will cancel this var_dump
//var_dump($names);

Also please remember

Warning!
  This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.


text:
Q: Combining results in second table when Joining two tables I have these two tables that I can't change, and I am trying to query and combine some data together from both of them. What I would ideally like to do is to combine omit rows where FieldTime2 is 0, when there are more than two results for the same FieldID. If FieldTime2 is 0 and there is only one result, then I want the row displayed.
Could you possibly count the FieldID in Table2 and assign a number if count is greater than 1, or something like that?
Table 1
ID  FieldID  FieldTime
------------------------
 1   A        10
 2   B        15
 3   C        20

Table 2
 ID  FieldID  FieldTime2
------------------------
 1   A        0
 2   A        15
 3   B        0
 4   C        10

Desired Output:
FieldID  FieldTime  FieldTime2
------------------------------
  A      10         15
  B      15         0
  C      20         10

My Output:
FieldID  FieldTime  FieldTime2
------------------------------
      A      10         0
      A      10         15
      B      15         0
      C      20         10

CODE:
SELECT
    m.FieldID,
    m.FieldTime,
    n.FieldTime2,

from Table1 m
   Join Table2 n
       ON m.FieldID = n.FieldID

Where n.FieldTime > 0

A: The simplest solution that comes to mind is to use a LEFT JOIN query, like this:
SELECT
    m.FieldID,
    m.FieldTime,
    COALESCE(n.FieldTime2, 0) as FieldTime2,

from Table1 m
  left Join Table2 n
       ON m.FieldID = n.FieldID and n.FieldTime2 > 0

Where n.FieldTime > 0

if there are multiple non-zero records in the Table2 and only one is desired then the query will be a bit complex:
with n as (
select *,
ROW_NUMBER() OVER(PARTITION BY FieldID ORDER BY FieldTime2 DESC) rn
from Table2
)
SELECT
    m.FieldID,
    m.FieldTime,
    COALESCE(n.FieldTime2, 0) as FieldTime2,

from Table1 m
  LEFT Join n
       ON m.FieldID = n.FieldID and n.rn = 1

Where n.FieldTime > 0

A: Based on your data sample, and the assumption that there will be only 1 FieldTime with a value > 0 you could simply use MAX() to resolve your problem:
SELECT
    m.FieldID,
    m.FieldTime,
    MAX(n.FieldTime2),
FROM Table1 m
JOIN Table2 n ON m.FieldID = n.FieldID
WHERE n.FieldTime > 0
GROUP BY m.FieldID, m.FieldTime

Of course this solution will not render the correct output if there could be multiple FieldTime records that have a value > 0 in which case you could solve your problem using a UNION:
--cases with one record:
SELECT
    m.FieldID,
    m.FieldTime,
    n.FieldTime2
FROM Table1 m
JOIN Table2 n ON m.FieldID = n.FieldID
Where m.FieldID in
(
   SELECT FieldID
   FROM Table2
   HAVING COUNT(FieldID) = 1 -- only one record exists
)
UNION
--cases with multiple records
SELECT
    m.FieldID,
    m.FieldTime,
    n.FieldTime2
FROM Table1 m
JOIN Table2 n ON m.FieldID = n.FieldID
Where m.FieldID not in --make sure we select the rest of the records
(
   SELECT FieldID
   FROM Table2
   HAVING COUNT(FieldID) = 1
) AND n.FieldTime2 > 0 -- make sure to exclude the 0 records.

Please note that this is not tested, so expect typos, poor performance or mistakes. :)


text:
Q: Serve remote url with node.js stream I have a video stored in amazon s3.
Now I'm serving it to the client with node.js stream
return request(content.url).pipe(res)
But, the following format is not working with safari.
Safari is unable to play streamed data. But, the same code works for chrome and firefox.
I did some research and found out
chrome's request content-range param looks like

[0-]

But, safari does the same with content ranges

[0-10][11-20][21-30]

Now if the content was stored in my server, I could have break the file in chucks with
fs.createReadStream(path).pipe(res)

to serve safari with it's requested content range
As mentioned in this blog https://medium.com/better-programming/video-stream-with-node-js-and-html5-320b3191a6b6
How can I do the same with remote url stored in s3?
FYI, It's not feasible to download the content temporarily on server and delete it after serving. As, the website is supposed to receive good traffic.

A:
How can I do the same with remote url stored in s3?

Don't.
Let S3 serve the data.  Sign a URL to temporarily allow access to the client.  Then, you don't have to serve or proxy anything and you save a lot of bandwidth.  An example from the documentation:
var params = {Bucket: 'bucket', Key: 'key'};
var url = s3.getSignedUrl('getObject', params);
console.log('The URL is', url);

...As, the website is supposed to receive good traffic.

You'll probably also want to use a CDN to further reduce your costs and enhance the performance.  If you're already using AWS, CloudFront is a good choice.


text:
Q: Null Check operator used on a null value.//chat is available for every user Why in this code,** chat** is for every user i want only the user who send and who he want to send but this chat  is available for every user .
And when i add reciever add it create this error Null Check operator used on a null value
However I have  reciever id: G3BXTZzjanWd4vwg4iMBv0VvkEh1
And sender id is G3BXTZzjanWd4vwg4iMBv0VvkEh1
Suppose I have reciever id
widget.id;

Here is the code without reciever id can any one solve my issue using reciever id as widget.id
StreamBuilder(
stream:FirebaseFirestore.instance.collection("messages").orderBy("Date",descending: false).snapshots(),
                  builder: (builder,AsyncSnapshot<QuerySnapshot>snapshot){
  print(snapshot.data!.docs.length);
if(!snapshot.hasData){
  return Center(child: CircularProgressIndicator(),);
}
  return ListView.builder(
      itemCount: snapshot.data!.docs.length,
      itemBuilder: (itemBuilder, index) {
        final message = snapshot.data!.docs[index]["message"];
        final senderId = snapshot.data!.docs[index]["senderid"];
        final currentUser = FirebaseAuth.instance.currentUser;
        final isMe = senderId == currentUser!.uid;
        final alignment = isMe ? MainAxisAlignment.end : MainAxisAlignment.start;
        final messageTextStyle = isMe ? TextStyle(color: Colors.white) : TextStyle(color: Colors.black);
        final messageColor = isMe ? Colors.blue : Colors.grey.shade300;
        return Row(
          mainAxisAlignment: alignment,
          children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 10, horizontal: 8),
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
              decoration: BoxDecoration(
                color: messageColor,
                borderRadius: BorderRadius.only(
                  topLeft: isMe ? Radius.circular(20) : Radius.circular(0),
                  topRight: isMe ? Radius.circular(0) : Radius.circular(20),
                  bottomLeft: Radius.circular(20),
                  bottomRight: Radius.circular(20),
                ),
              ),
              child: Text(
                message,
                style: messageTextStyle,
              ),
            ),
          ],
        );
      });
                  }),

     IconButton(
                    onPressed: ()async {
                      print("ID=="+widget.id);
                      if (messagecontroller.text.isNotEmpty) {
                        FirebaseFirestore.instance.collection("messages").add({
                          "senderid":FirebaseAuth.instance.currentUser!.uid,
                          "recieverid":"null",
                          "Date":DateTime.now(),
                          "message":messagecontroller.text.toString(),

                        }).whenComplete(() {

                          Fluttertoast.showToast(msg: "Send message to ${widget.name}........."
                              ,
                              backgroundColor: Colors.grey,
                            timeInSecForIosWeb: 1
                          );
                        });
                        messagecontroller.clear();
                      }
else{
  Fluttertoast.showToast(msg: "Please Enter text to send message to ${widget.name}"
  ,
  backgroundColor: Colors.red
  );
                      }

                    },
                    icon: Icon(Icons.send),
                    color: Colors.grey,
                  ),

A: You're loading the chat messages with (lines wrapped for readability):
FirebaseFirestore.instance
  .collection("messages")
  .orderBy("Date",descending: false)
  .snapshots()

So that loads all messages, regardless of the ender and/or receiver.
If you only want to load messages for a specific sender/receiver pair, you'll want to use a query:
FirebaseFirestore.instance
  .collection("messages")
  .orderBy("Date",descending: false)
  .where("senderid", isEqualTo: "G3BXTZzjanWd4vwg4iMBv0VvkEh1")
  .where("recieverid", isEqualTo: "G3BXTZzjanWd4vwg4iMBv0VvkEh1")
  .snapshots()

You'll of course want to match the conditions and values to fit with your actual code.

Note that you have taken a rather relational data model approach here by storing the chat messages for all users in collection (like you'd do in a single table in SQL).
While this may work, there are many other possible data models. Consider reading up on NoSQL data modeling and watching the excellent Get to know Cloud Firestore video series to learn more about your options.


text:
Q: Human max speed in open space Suppose you are an astronaut forgotten in the middle of nowhere, between our solar system and proxima centauri's. Now, you are out of fuel. I heard that with some kind of movements, someone in free space can actually acquire velocity, i.e. accelerate. Kind of like when you played swing as kid, acquiring more velocity with swinging legs back and forth. My first question is:

*

*What is the maximum acceleration from one such optimal movement?

*Then, is there a limit to the attainable speed through repeating such movements frenetically?

*Finally, as a bonus, how much time to get back to earth with optimal trajectory?
Sorry for the question list but I think they are linked.
Newtonian as well as curved spacetime answers are appreciated and welcome.

A: You cannot change your linear or angular momentum in open space at all. You need something to transmit it to. if you swing your legs your body will rotate in the opposite direction while you swing, and stop when you stop swinging. If you are out of fuel there is no way to accelerate. Only by releasing mass you could change momentum, as Bender well shows you, if there is nothing external with which you could interact.
As for the max. speed, there is none (if you consider non relativistic speeds). You can go as fasta as you're going in the beginning unless you interact with something.

A: You can't just acquire velocity (and hence momentum) without an equal and opposite momentum going to something else.  So you are wrong that there are things you can do to acquire velocity.  Unless you want to leave parts of yourself behind or are capable of stealing momentum from, say, an electromagnetic field.
However, if you are an extended body in a curved spacetime that is capable of moving your parts around, it is potentially possible to translate yourself, even though you don't pick up a velocity.  The effect is quite small, and you can search for "swimming through spacetime" for details.
Unlike a velocity build up you'd have to do each translation from scratch, and the less curvature, the less of an effect. Every analysis I've seen assumes you have perfectly rigid parts, and can freely move them however you want. Real human parts are not perfectly rigid and it will require effort to move them, if you were an astronaut caught light years away from earth the translations would be very small, and you'd stop translating when you stopped moving your limbs so you would surely die before you made it anywhere close to Earth, and once you died you'd stop travelling (this is different than picking up velocity where your corpse might some day arrive).


text:
Q: Creating Movie using im.convert in r I'm trying to create a movie out of jpg/png images in R. I have basically stored snapshots of a sankey diagram from googleVis package and trying to convert it into a movie.. the code that i use is:  (package animation)
im.convert("image*.jpg",output="anim.gif")

I used 10 images image1:image10. However the animation is stuck at the first image itself.
what is wrong?


text:
Q: i++ vs. ++i in a JavaScript for loop Because of JSLint, I almost always use i += 1 to increment a JavaScript for loop, but for quick and dirty scripts, I use i++ instead.
However, I see a lot of for loops in other people's code in which they increment i by doing ++i instead.
As far as I know, there is no difference in meaning between i++ and ++i, and jsPref shows no difference in performance.
As such, I'm wondering where the convention of doing ++i comes from and why people tend to do it.
Does anyone know why a lot of JS coders tend to prefer ++i over i++ when incrementing the counter in a for loop?
Thanks.

A: Way back in the day (we're talking IE6/7 here!), I recall benchmarking both forms and found that there was a small performance improvement with ++i instead of i++. My (unproven) theory was that a non-optimizing JS engine had to do a tiny bit more work in the i++ case: it had to save the previous value in case it would be used - and being a non-optimizing engine it didn't realize that the value would in fact not be used and didn't need to be saved.
However, with modern browsers there is no significant difference. If anything, i++ seems to be a tiny bit faster in many browsers.
Here are some tests of a variety of different loops:
http://jsperf.com/mikes-loops/5
Look for the results for "Traditional Loop" (this uses ++i) and "Traditional Loop with i++".
Regarding JSLint's requirement that one should never use ++i or i++ but only use i += 1 instead, that is simply insane and over-controlling, like so many other things in JSLint.
Personally I recommend JSHint instead. It is less dogmatic, much more practical, and easier to customize to your own style.

A: In JS and PHP it does not make any difference, I think even in Java it does not make any difference but in pure c when compiler is not optimizing code it does, and that is why a lot of people use ++i because they are used to it from c.
EDIT:
This is an answer for JS if you want history of pre and post increment searc C/C++ pre/post increment. Or see comments on @Orvev's answer.

A: There is a difference, however not when used in a for loop.
In an expression, i++ evaluates to the previous value of i, and then i is incremented. ++i increments first, and evaluates then.
For this reason, some programmers prefer to write ++i in their for-loops — either because they're used to it, or because they feel it is "more right" somehow.
edit: More probable is the solution Overv proposed: a relict from C.

A: The difference is that i++ returns the value of i before incrementing and ++i the value of i after incrementing. There is no difference if you ignore the return value, e.g. in:
for (var i = 0; i < 10; i++) {

}

The habit of using ++i over i++ comes from C, where people were worried that storing the old value for i in i++ would incur a performance penalty.


text:
Q: Training Mode: NPC on control option When I go in training mode I know that somehow you are able to make the NPC do an action when it's on the control option. I just don't know how.

A: Simply press start and in the menu you can change the CPU Behavior. If you want to control the CPU manually you have to plug-in another controller.


text:
Q: BotBuilder and Azure AD B2C I've set up my bot to work with Azure AD using this official sample "Microsoft.Bot.Sample.AadV2Bot"
Now, I would like it use a Azure B2C tenant that I've got configured in my Azure subscription, but I don't have a clue of how to do that.
I've already checked the docs, but I'm really lost. I've checked in my Bot Settings page, under OAuth Connection Settings but it doesn't show Azure AD B2C in any of the available options:

A: Publish the bot as a .NET application and register it under your B2C tenant.


text:
Q: How can I avoid using .net Core DI container? It seems like microsoft is making it super hard if not impossible to avoid using their .net core DI container.
I am migrating several solutions and don't want to replace the custom DI container that I use across my solutions.
Currently I can run without registering any service but as soon as I declare an interface in any controller's constructor, core tries to resolve using their DI container which is very very annoying.
Anybody has any success overriding this behavior,


text:
Q: Can a browser plugin lazy load images? Before spending time learning the plug-in architecture I was hoping someone could let me know if what I want to do is even possible and possibly offer some guidance.
I've never written a browser plug-in before but I have am an experience programmer who is pretty good with JavaScript which I understand is what at least chrome extensions use. I have written a small app for the Samsung TV platform.
One webpage I visit on a regular basis loads a lot of images on a page and I don't want to wait until the developers improve the site. I'm hoping I could build a Chrome or Firefox extension that can identify when I'm viewing a page on that domain and prevent images from loading until some user interaction.
I was hoping when I changed the content settings in Chrome to not show images that there would be some way to individually load images (maybe a "show this image" in context menu, but there wasn't. Nothing came up when trying to search for an existing extension either.
Is it possible to have an extension manipulate the DOM to prevent the page from making requests for the images? I'm thinking replacing the src attribute with a local image as a placeholder, then changing it back depending on user interaction.


text:
Q: Is there a way I can detect internet connection with Firebase in Unity? I am working on a mobile game, where I would like to know if the player has internet connection or not.
I tried doing it with the following methods:

*

*Unity's internetReachability property, but it doesn't work, since - as they wrote out in the docs too - it doesn't actually detect if the player has internet connection

*Pinging a website that is on 24/7 (e.g Google), but it is bad since if there are thousands of users, it will load Google servers

*Now I'm trying to get a result by retrieving data from my Firebase database every X secs, and if it doesn't load, there is no connetction: the problem is, even if there is no internet connection, it doesn't crash/give any error

Is there a way I can achieve what I want with Firebase?
Please note that if the player has no internet connection, they should not be able to click on any of the game functions, because it will cause bugs, so I would like to check for connection continuously. When there is no connection I disable the GUI so that the player can not cause bugs)

A: If you're using the Firebase Realtime Database, it has a built-in mechanism to show you when the app is connected to the database servers. By listening to the .info/connected node, you can detect this state and update your UI.
Note that this is not just detecting an internet connection, but whether the app is connected to the database backend. So in cases where the user may have an internet connection, but can't connect to the database backend, the flag may be false.


text:
Q: I created .env file for my Api and when I fetch data it shows 'Request failed with status code 403' (Axios Error) Error Message

AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

useEffect(() => {
        const fetchData = async () => {
            try {
                const data = await axios.get(process.env.REACT_APP_API_URL + "/products", {
                    headers: { Authorization: "bearer" + process.env.REACT_APP_API_TOKEN, }
                })
                console.log(data)

            } catch (err) {
                console.log(err)

            }`your text`
        }
        fetchData();
    }, [])

in my .env file(it is inside root)
//I changed the version of axios but it didn't work
REACT_APP_API_TOKEN =d497def4a0c937df0c7ee1514a2975f3ab433df1557bda09405350247ff23425f1c47fabe1dbcb5433c89be91344f7557a2fe0060da7fa006570bf82ae7bb65c81f5aa469dbaaf1576ab8a28f4a65892653aebb394581423495c951c90e697d67fe1c5d08dfa10a6b834d3e06cdc37d54b837d1ec10aebabb9fb86d9adfb1600
REACT_APP_API_URL = http://localhost:1337/api

A: Not entirely sure, but did you just forgot a space in the way you're setting you're Header here ? Shouldn't it be :
headers: { Authorization: "bearer " + process.env.REACT_APP_API_TOKEN, }


text:
Q: How to use jquery to show an element after JSON data is sent back to page On page 1, user clicks an image and a pop-up window allows an image file upload. The PHP page running this echo's back a json_encoded string that will include a variable called 'id'.
Here is an example of the response string:
"{"state":200,"message":null,"result":"..\/0images\/listimg\/mod\/20141215064959.jpeg","id":"570"}"

When the pop-up modal closes, I would like an element (that was previously hidden on page 1) to now be displayed. The element is:
<div class="edit_right">

My logic is to show the element if an 'id' is sent as JSON data, thus if ID is not null, element will show.
The JS I am troubleshooting is
    <script>
        $(document).ready(function(){
            $(".edit_right").hide();
        });
    $('#modal').on('hidden.bs.modal', function () {
        function handleResponse(data){
    console.log(data);
    }
        $.getJSON(crop-avatar.php)
            .done(function(data) {
             if (data.id !== null){
              $(".edit_right").show();
             } else {
            $(".edit_right").hide();
            }
         });
       })
    </script>

and is located right before the end body tag. This script doesn't work, the element is always hidden. How can I correct this?

A: You need to pass the URL into $.getJSON() so it knows what page to retrieve the data from, and I don't know why you're passing data to handleResponse(), it has no effect in that function.

A: I think the data that returns in handleResponse is a json string so you don't have to do additional getJSON on that.
Do
function handleResponse(data){
console.log(data);
}

If it shows a json string then you can take it from there.

A: you are not calling $.getJson with a parameter

A: from jQuery docs:
$.getJSON( "ajax/test.json", function( data ) {
    // Do something
});

so what you need to do is:
function handleResponse(data){
   $.getJSON('path/to/your/php-file.php').done(function(data){
        // Do something
    })
}

Also don't forget to call handleResponse()!


text:
Q: Verilog Full Adder Unexpected Behavior I am trying to do a very basic hardware module/test bench to get the hang of Verilog. I have tried to implement a full adder.
If I am not mistaken, you have three input, immediate addends a and b and a carry in from the 2^n-1 place.
The outputs are sum and carry out (which might serve as a carry in to another module in a basic adder or whatever the not carry-lookahead is called.)
If I am not mistaken the output logic is
sum = (a&b) | (a&cin) | (b&cin) //or all three, which is covered by any of these
cout = a ^ b ^ cin
Here is the full adder module
module FullAdder(
a,
b,
cin,
sum,
co
);

input a;
input b;
input cin;
output sum;
output co;

//wire a;
//wire b;
//wire ci;
wire sum;
wire co;

//At least two
assign co = (a & b) | (a & cin) | (b & cin);

//one or three
assign sum = a ^ b ^ cin; //(a & ~b & ~cin) | (~a & b & ~cin) | (~a & ~b & cin) | (a & b & cin);

endmodule

And here is the test bench
module HalfAdderTB();
reg a_in;
reg b_in;
reg cin_in;
wire s_out;
wire cout_out;

FullAdder DUT(
        a_in,
        b_in,
        cin_in,
        s_out,
        cout_out
        );

initial begin
        a_in = 1'b0;
        b_in = 1'b0;
        cin_in = 1'b0;
        #20

        a_in = 1'b0;
        b_in = 1'b0;
        cin_in = 1'b0;
        $display("a: %d, b: %d, cin: %d", a_in, b_in, cin_in);
        $display("s: %b, cout: %b", s_out, cout_out);
        #20

        a_in = 1'b0;
        b_in = 1'b0;
        cin_in = 1'b1;
        $display("a: %d, b: %d, cin: %d", a_in, b_in, cin_in);
        $display("s: %b, cout: %b", s_out, cout_out);
        #20

        a_in = 1'b0;
        b_in = 1'b1;
        cin_in = 1'b0;
        $display("a: %d, b: %d, cin: %d", a_in, b_in, cin_in);
        $display("s: %b, cout: %b", s_out, cout_out);
        #20

        a_in = 1'b0;
        b_in = 1'b1;
        cin_in = 1'b1;
        $display("a: %d, b: %d, cin: %d", a_in, b_in, cin_in);
        $display("s: %b, cout: %b", s_out, cout_out);
        #20

        a_in = 1'b1;
        b_in = 1'b0;
        cin_in = 1'b0;
        $display("a: %d, b: %d, cin: %d", a_in, b_in, cin_in);
        $display("s: %b, cout: %b", s_out, cout_out);
        #20

        a_in = 1'b1;
        b_in = 1'b0;
        cin_in = 1'b1;
        $display("a: %d, b: %d, cin: %d", a_in, b_in, cin_in);
                                                                                2,1            4%
 a_in = 1'b1;
        b_in = 1'b1;
        cin_in = 1'b0;
        $display("a: %d, b: %d, cin: %d", a_in, b_in, cin_in);
        $display("s: %b, cout: %b", s_out, cout_out);
        #20

        assign a_in = 1'b1;
        assign b_in = 1'b1;
        assign cin_in = 1'b1;
        $display("a: %d, b: %d, cin: %d", a_in, b_in, cin_in);
        $display("s: %b, cout: %b", s_out, cout_out);
        #20
        $finish;
end
endmodule

My output looks like this
a: 0, b: 0, cin: 0
s: 0, cout: 0
a: 0, b: 0, cin: 1
s: 0, cout: 0
a: 0, b: 1, cin: 0
s: 1, cout: 0
a: 0, b: 1, cin: 1
s: 1, cout: 0
a: 1, b: 0, cin: 0
s: 0, cout: 1
a: 1, b: 0, cin: 1
s: 1, cout: 0
a: 1, b: 1, cin: 0
s: 0, cout: 1
a: 1, b: 1, cin: 1
s: 0, cout: 1
I believe the logic statements in my code match those of the boolean equations I wrote up top. I am confident in my logic. I cannot seem to figure out what is wrong with the Verilog. Have I missed something with the timing and input of the test bench to the Full Adder?

A: Your code is fine, but you are getting this strange result due to $display statement. Your code will work fine, if you use $strobe instead of $display. You could also use $monitor to display the results. The reson is that display statement executes immediately so that your outputs will not yet be updated with the new values, whereas strobe will execute only at the end of a time instant, so that your outputs would have been updated by then. monitor is used to automatically display values, whenever the values see a change.
Since you are just starting on verilog, I would suggest you to go through this link to understand how various display statements work in verilog and also to go through this link to understand the order of execution of statements in a particular time instant, so that you can plan your code better


text:
Q: Drag_and_drop does nothing I'm having no luck at all getting ActionChains actions to work in Chrome, specifically drag_and_drop, and I'm not finding any workarounds.
In my case, I'm dealing with an issue where a table of data will only appear once an element is dragged into a certain field. If I try to do this with ActionChains, the program simply does nothing and hangs.
This is using selenium in python.
I'm in Chrome Version 75.0.3770.100
Here's a snippet of example code that should recreate the situation:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

import time
import re

### Start Process
# create a new Chrome session
driver = webdriver.Chrome()
driver.implicitly_wait(30)
driver.maximize_window()
driver.get('https://www.w3schools.com/html/html5_draganddrop.asp')

dragged = driver.find_element_by_xpath('//*[@id="drag1"]')
dropped = driver.find_element_by_xpath('//*[@id="div2"]')
ActionChains(driver).drag_and_drop(dragged, dropped).perform()

This code should just drag the logo from the left box to the right, but it does nothing.
Edit: Here's what gets returned in the shell:
 DevTools listening on ws://127.0.0.1:54994/devtools/browser/a9093d6c-8ee0-4140-84fe-dd3009412fbc
 [14976:20964:0710/120727.552:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -100
 [14976:20964:0710/120727.576:ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -100
 Press any key to continue . . . [14976:20964:0710/120736.634:ERROR:ssl_client_socket_impl.cc(947)]
 handshake failed; returned -1, SSL error code 1, net_error -100

A: @pcalkins Got it! here's the working code! I just moved that last line in the string that declared the variables into the function call so I could change it in different situations. Thanks so much!
from selenium import webdriver

#javaScript function to drag and drop
simulateFunction = str("function simulateDragDrop(sourceNode, destinationNode) {\n" +
"    var EVENT_TYPES = {\n" +
"        DRAG_END: 'dragend',\n" +
"        DRAG_START: 'dragstart',\n" +
"        DROP: 'drop'\n" +
"    }\n" +
"\n" +
"    function createCustomEvent(type) {\n" +
"        var event = new CustomEvent(\"CustomEvent\")\n" +
"        event.initCustomEvent(type, true, true, null)\n" +
"        event.dataTransfer = {\n" +
"            data: {\n" +
"            },\n" +
"            setData: function(type, val) {\n" +
"                this.data[type] = val\n" +
"            },\n" +
"            getData: function(type) {\n" +
"                return this.data[type]\n" +
"            }\n" +
"        }\n" +
"        return event\n" +
"    }\n" +
"\n" +
"    function dispatchEvent(node, type, event) {\n" +
"        if (node.dispatchEvent) {\n" +
"            return node.dispatchEvent(event)\n" +
"        }\n" +
"        if (node.fireEvent) {\n" +
"            return node.fireEvent(\"on\" + type, event)\n" +
"        }\n" +
"    }\n" +
"\n" +
"    var event = createCustomEvent(EVENT_TYPES.DRAG_START)\n" +
"    dispatchEvent(sourceNode, EVENT_TYPES.DRAG_START, event)\n" +
"\n" +
"    var dropEvent = createCustomEvent(EVENT_TYPES.DROP)\n" +
"    dropEvent.dataTransfer = event.dataTransfer\n" +
"    dispatchEvent(destinationNode, EVENT_TYPES.DROP, dropEvent)\n" +
"\n" +
"    var dragEndEvent = createCustomEvent(EVENT_TYPES.DRAG_END)\n" +
"    dragEndEvent.dataTransfer = event.dataTransfer\n" +
"    dispatchEvent(sourceNode, EVENT_TYPES.DRAG_END, dragEndEvent)\n" +
"}; ")

### Start Process
# create a new Chrome session
driver = webdriver.Chrome()
driver.implicitly_wait(30)
driver.maximize_window()
driver.get('https://www.w3schools.com/html/html5_draganddrop.asp')

#call javascript dragdrop function
#here, drag1 and div2 are the page-specific IDs of the item to drag and the place to drop it, respectively.
driver.execute_script(simulateFunction + "var toDrag =document.getElementById('drag1'); var toDrop = document.getElementById('div2'); simulateDragDrop(toDrag, toDrop);")


text:
Q: Indices of matching of rows between matrices Let n be a positive integer. We have a matrix B that has n columns, whose entries are integers between 1 and n. The aim is to match the rows of B with the rows of permutations(n), memorizing the indices in a vector v.
For example, let us consider the following. If
permutations(3)=
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1

and
B=
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3
[3,]    3    1    2
[4,]    2    3    1
[5,]    3    1    2

Then the vector v is
1 1 5 4 5

because the first two rows of B are equal to the row number 1 of permutations(3), the third row of B is the row number 5 of permutations(3), and so on.
I tried to apply the command
 row.match

but the latter returns the error:
Error in do.call("paste", c(x[, , drop = FALSE], sep = "\r")) :
second argument must be a list

A: One way is to use match,
match(do.call(paste, data.frame(B)), do.call(paste, data.frame(m1)))
#[1] 1 1 5 4 5

A: One possible way is to turn your matrices into dataframes and join them:
A = read.table(text = "
1    2    3
1    3    2
2    1    3
2    3    1
3    1    2
3    2    1
")

B = read.table(text = "
1    2    3
1    2    3
3    1    2
2    3    1
3    1    2
")

library(dplyr)

A %>%
  mutate(row_id = row_number()) %>%
  right_join(B) %>%
  pull(row_id)

# [1] 1 1 5 4 5


text:
Q: React Slick Sync - functional component React Slick has got good examples of how to get it going, this one however is in class component, any idea of how to fix the same when making it a functional component
https://react-slick.neostack.com/docs/example/as-nav-for
import React from "react";
import Slider from "react-slick";

export default function SyncSlider() {
  const [nav1, setNav1] = React.useState(null)
  const [nav2, setNav2] = React.useState(null)
    let slider1 = []
    let slider2 = []

    React.useEffect(() => {
        setNav1(slider1)
        setNav2(slider2)
    }, [slider1, slider2])

    return (

Slider Syncing (AsNavFor)

First Slider

        <Slider
          asNavFor={nav1}
          ref={slider => (slider1 = slider)}
        >

1

2

3

4

5

6

        </Slider>

Second Slider

        <Slider
          asNavFor={nav2}
          ref={slider => (slider2 = slider)}
          slidesToShow={3}
          swipeToSlide={true}
          focusOnSelect={true}
        >

1

2

3

4

5

6

        </Slider>

    );

}

Problem looks like is here:
    let slider1 = []
    let slider2 = []

The sliders show up but do not sync, any thoughts, inputs, solutions on getting this working?

A: Simple and functional solution (without UseEffect and UseRef) :
import React, { useState } from 'react';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';

export default function SyncSlider() {
  const [nav1, setNav1] = useState();
  const [nav2, setNav2] = useState();

    return (

Slider Syncing (AsNavFor)

First Slider

      <Slider asNavFor={nav2} ref={(slider1) => setNav1(slider1)}>

1

2

3

4

5

6

      </Slider>

Second Slider

      <Slider
        asNavFor={nav1}
        ref={(slider2) => setNav2(slider2)}
        slidesToShow={3}
        swipeToSlide={true}
        focusOnSelect={true}
      >

1

2

3

4

5

6

      </Slider>

  );
}

Demo : Stackblitz

A: i had your problem and now its solved for me , this code will work 100% :D

*

*delete let slider 1 and let slider 2

*you need empty dep in useEffect

*the refs that is used in setstates is undefined for slider so you
need to write like this:
setNav1(slider1.current)
and
setNav2(slider2.current)

*refs in sliders should be just like this ref={slider1}

and here is my code that is still working perfectly for me
 export const ProductGallery = () => {
  const [nav1, setNav1] = useState(null);
  const [nav2, setNav2] = useState(null);
  const slider1 = useRef(null);
  const slider2 = useRef(null);

  useEffect(() => {
    setNav1(slider1.current);
    setNav2(slider2.current);
  }, []);

  return (

        <Slider asNavFor={nav2} ref={slider1}>

1

2

3

4

5

6

        </Slider>

Pagination slider

        <Slider
          asNavFor={nav1}
          ref={slider2}
          slidesToShow={3}
          swipeToSlide={true}
          focusOnSelect={true}
        >

1

2

3

4

5

6

        </Slider>

  );
};

A: The @burgrandy 's answer may cause error (for example while page scroll)

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

And @ali khakbazan 's answer has a problem, that sync works only in one direction, so that only first carousel influences second, but not vice versa.
Also, both answers a overcomplicated and use unnecessary code.
So I propose to use simplier code, that works without bugs:
export default function SyncSlider() {
  const slider1 = useRef(null)
  const slider2 = useRef(null)

  return (

Slider Syncing (AsNavFor)

First Slider

      <Slider
        asNavFor={slider2.current}
        ref={slider1}
      >
        {list1}
      </Slider>

Second Slider

      <Slider
        asNavFor={slider1.current}
        ref={slider2}
      >
        {list2}
      </Slider>

  );
}

A: You almost have it. To fix your code, switch the asNavFor properties - the first slider should have asNavFor={nav2}, and the second slider should have asNavFor={nav1}.
import React from "react";
import Slider from "react-slick";

export default function SyncSlider() {
  const [nav1, setNav1] = React.useState(null)
  const [nav2, setNav2] = React.useState(null)
    let slider1 = []
    let slider2 = []

    React.useEffect(() => {
        setNav1(slider1)
        setNav2(slider2)
    }, [slider1, slider2])

    return (

Slider Syncing (AsNavFor)

First Slider

        <Slider
          asNavFor={nav2}
          ref={slider => (slider1 = slider)}
        >

1

2

3

4

5

6

        </Slider>

Second Slider

        <Slider
          asNavFor={nav1}
          ref={slider => (slider2 = slider)}
          slidesToShow={3}
          swipeToSlide={true}
          focusOnSelect={true}
        >

1

2

3

4

5

6

        </Slider>

    );

}

A: I did this and it working as expected for me:
const NavigationCarousel = props => {

    const [topNav, setTopNav] = useState(null);
    const [bottomNav, setBottomNav] = useState(null);

  let _topSlider = [],
    _bottomSlider = [];

  useEffect(() => {
    setTopNav(_topSlider);
    setBottomNav(_bottomSlider);
}, [_topSlider, _bottomSlider]);

  return (

      <Slider
        asNavFor={bottomNav}

        ref={slider => {
          _topSlider = slider;
        }}
      >
        {topNavElements}
      </Slider>

      <Slider
        asNavFor={topNav}

        ref={slider => {
          _bottomSlider = slider;
        }}
        slidesToShow={slidesToShowBottomNav}
        swipeToSlide={true}
      >
        {bottomNavElements}
      </Slider>

   );
}
export default NavigationCarousel;

topNavElements and bottomNavElements are being passed in from the parent.

A: Just use current object from ref while call API that should fix all the problem.
exp:
export default function HeroCarousel() {
   const slider = React.useRef<Slider>();
   const next = () => slider.current.slickNext();
   const previous = () => slider.current.slickPrev();

  return (

      <Slider
        ref={slider}
      >
        {img1}
        {img2}
        {img3}

      </Slider>

       <svg onClick={previous} className="mt-1 mb-6" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 20">
          <path d="M10.59 20L0 10 10.59 0 12 1.33 2.82 10 12 18.67 10.59 20z"></path>
        </svg>
         <svg onClick={next} className="mt-1 mb-3" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 20">
           <path d="M0 18.67L9.18 10 0 1.33 1.41 0 12 10 1.41 20 0 18.67z"></path>
         </svg>

  );
}


text:
Q: How to calculate factorial in Theano Here is a simple example.
import theano
v = theano.tensor.scalar("variable")
factorial = ?
# Calculate factorial of v , like numpy.math.factorial(v), but it didn't work,
# Actually it should be a integer as a parameter of numpy.math.factorial function
result = theano.function([v], factorial)

There is few useful information on Internet. Something I found like
http://matthewrocklin.com/blog//work/2013/08/14/SymPy-Theano-part-4
which told me it belonged to "the future work", which means there is no solution for this problem.
How could that possible? I mean is there no body need calculate factorial in your theano project?
I had this problem when I designed a RBM with Poisson conditional possibility which needs calculate factorial of visible units in the energy function.

A: I have found the answer that we use gamma function to solve the factorial problem.
:( Sorry for bothering everybody!
Here is the detail:
https://groups.google.com/forum/#!msg/theano-users/ytqep8AickA/cE7QeJZxXzUJ
So here should be:
import theano
v = theano.tensor.scalar("variable")
factorial = theano.tensor.gamma(v)
# Calculate factorial of v , like numpy.math.factorial(v), but it didn't work,
# Actually it should be a integer as a parameter of numpy.math.factorial function
result = theano.function([v], factorial)

A: def factorial(x):
    y = x-1
    temp = x*y
    it = y-1
    for i in range(it):
        y -= 1
        temp = temp*y
    print temp

Here is the edited solution without the Boolean operators. I know you found another answer but this may be helpful to you as well as others in the future.


text:
Q: Selecting distinct keys and their counts from a dictionary series in python I have a pandas dictionary series, that takes the values like
   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}

I want to create a dictionary out of it based on the key and its occurrence in series, like:
{AA:3,BB:2,CC:1,CD:1}

A: I doubt there is a "built-in" solutiuon for this, so you'd have to manually iterate and count each key in every dictionary.
import pandas as pd
from collections import defaultdict

ser = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

count = defaultdict(int)

for d in ser:
    for key in d:
        count[key] += 1

print(count)
# defaultdict(<class 'int'>, {'CC': 1, 'BB': 2, 'AA': 3, 'CD': 1})

You could also use Counter, however this looks rather "forced" in this situation:
import pandas as pd
from collections import Counter

total = Counter()

ser = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

for d in ser:
    total.update(d.keys())

print(total)
# Counter({'AA': 3, 'BB': 2, 'CD': 1, 'CC': 1})

A: Turn your series in to a series of lists of keys, sum those creating a single list of keys, and use a Counter:
In [23]: pd.Series([{'AA':25,'BB':31},{'CC':45,'AA':3},{'BB':3,'CD':4,'AA':5}])
Out[23]:
0           {'AA': 25, 'BB': 31}
1            {'AA': 3, 'CC': 45}
2    {'CD': 4, 'AA': 5, 'BB': 3}
dtype: object

In [24]: series = _

In [34]: from collections import Counter

In [35]: Counter(series.apply(lambda x: list(x.keys())).sum())
Out[35]: Counter({'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1})

Or using generator expressions and flattening:
In [37]: Counter(k for d in series for k in d.keys())
Out[37]: Counter({'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1})

A: counter = dict()
for item in series:
    for key in item:
       counter[key] = counter.get(key, 0) + 1

A: Maybe it's a bit late but this is another way of doing it by using pandas built-in functions.
s = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

#convert dict to a dataframe and count non nan elements and finally convert it to a dict.
s.apply(pd.Series).count().to_dict()
Out[651]: {'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1}


text:
Q: Should we assign local object references to null in a finally block? Should we reference Objects to null in finally block while Objects are in local scope of method? What are the performance issues resolved by doing so?
code:
Map<String, Map<String, String>> getData(Map<String, String> params) {
    StringBuilder query = new StringBuilder(); // Construct query using it
    ResultSet rs = null;
    try {
        rs = DataUtil.getData(query);
        while(rs.next) {
            // store data in return Map
        }
    } catch(ConnectionException ce){
        ce.printStackTrace();
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        rs = null;
        query = null;
    }
}

Here, freeing up rs and query seems to fulfill no purpose as they are automatically valid for garbage collection after method execution. Any help would do great.

A: No we should not. It makes the code a lot harder to read and in most cases (for example your example) it does absolutely nothing, as GC will start after the scope anyways.
In general we should let Java handle its Garbage Collection and should not try to make it more efficient by writing strange code.

A: There is no need to do so. There is no benefit at all. Local variables are not reachable once the execution gets out of the method. GC will be done on all objects which are not reachable. This is no where related to performance issues.

A: No don't do this because it doesn't mean anything when object is out of scope. All the java objects deallocation will be handled by Garbage Collector automatically when there is no owner or reference to that object in heap.
Finally is very handy because it'll get executed whether there occurs an exception or not in your code. Use finally when you want to perform some important resource management work like closing an opened database connection etc. HTH

A: There are edge cases where this can matter quite a lot: it can make the difference between a running program and an OutOfMemoryException. Consider this code:
long[] hugeAry = new long[Integer.MAX_VALUE]; // barely fits on the heap
... work on hugeAry;
hugeAry = null;
int[] intHugeAry = new int[Integer.MAX_VALUE];
... work on this one

Commenting out hugeAry = null will easily cause an OOME. The cases can get even more bizarre than this—check out this related topic on SO.
But, don't get me wrong: in 99.9% of cases, nulling out locals (in finally or otherwise) does not matter.