text:
Q: IDL syntax error caused by getenv(), a path error I am using exofast code in IDL, I set environment exactly as the developer describe it but when I ru the code for fitting I get this errors:
path = filepath('',root_dir=getenv('EXOFAST_PATH'),subdir=['examples','hat3'])
                            ^
% Syntax error.
  At: /usr/local/ITTVIS.IDL.v7.0.6.LINUX-TBE/idl706/EXOFASTv2/examples/hat3/fithat3.pro, Line 3

           prefix=path+'fitresults'+path_sep() +'HAT-3b.Torres.', maxsteps=maxsteps, $
                                              ^
% Syntax error.
  At: /usr/local/ITTVIS.IDL.v7.0.6.LINUX-TBE/idl706/EXOFASTv2/examples/hat3/fithat3.pro, Line 8

I don't know what is the problem in my environment. any help?


text:
Q: How do you swap bytes/words for a whole buffer I have socket message trying to parse I have whole byte buffer of message whose bytes have been word and byte swapped coming across sockets.  I have methods that can do this swapping for 2 shorts or long value. But I was thinking I should really do this on the whole byte array first and then my parsing routines will work. Is there any byte buffere tools for swapping bytes/words for a whole buffer????????????

A: You can use ByteBuffer.order(endianess)
socket.getChannel().read(byteBuffer); // More or less

byteBuffer.order(ByteOrder.BIG_ENDIAN);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);

This will use LSB or MSB first (least/most significant byte first). There still are main frames where 4-bytes words have a still different order. But here it should be just what you wanted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Subqueries in neo4j 3.5 (for Pagination) I am trying to implement a pagination using neo4j 3.5 and I realized that subqueries (such as Call {}) is not supported in this version. The common approach for pagination in this particular version is (cypher pagination total result count):
// -------------------------------------
// FIRST QUERY
// -------------------------------------
MATCH (x:Brand)
WITH count(*) as total

// -------------------------------------
// SECOND QUERY
// -------------------------------------
MATCH (o:Brand)
WITH total, o
ORDER BY o.name SKIP 5 LIMIT 5
WITH total, collect({uuid:o.uuid, name:o.name}) AS brands
RETURN {total:total, brands:brands}

This works if the block where we get the count is just a single type. I have a complex query that has nested matches like:
MATCH (px:Type1)-[:Relationship1]->(pvx:Type2 { prop:'somevalue'})-[:Relationship2]->(bx:Type3)
     MATCH (px)-[:Rel3]->(ptx:Type4)
// and so on

To get the value of this complex query, I had to enclose the query inside "apoc.cypher.run", which I was able to successfully get with this:
CALL apoc.cypher.run("MATCH (x:Type1) return count(*) as total", {})
YIELD value
return value.total

Is there a way to pass the result of this apoc.cypher.run to the second query, so I may be able to return the total number of records, as a variable in the second query?

A: Something like this?
CALL apoc.cypher.run("MATCH (x:Type1) return count(*) as total", {})
YIELD value AS total
WITH total
MATCH (o:Brand)
WITH total, o
ORDER BY o.name SKIP 5 LIMIT 5
WITH total, collect({uuid:o.uuid, name:o.name}) AS brands
RETURN {total:total, brands:brands}


text:
Q: Functions with Variable Numbers of Arguments: Outer Vector Product I am trying to write a function that takes a column vector of variable dimension as an input and returns the outer product matrix as an output.
What I have tried:
OuterVectorProduct[x__] := MatrixForm[Outer[Times, x, x]]

However, this obviously returns wrong results.
Thanks!

A: Here is a simple example that will get you started,
x = {x1, x2, x3};
y = {y1, y2};

(xy = KroneckerProduct[x, y]) // MatrixForm

(* get 3x2 matrix output *)

(yx = KroneckerProduct[y, x]) // MatrixForm

(* get 2x3 matrix output *)

The parentheses are important --- compare the FullForm of the resulting "matrix" if you leave them out.
Edit:
In answer to your specific Qn,
OuterVectorProduct[x_] := KroneckerProduct[x, x]

which will work for a vector x for any value of Dimensions[x].


text:
Q: C# Including reference dll within my project Referencing dll within my project is not too clear form me

*

*When including dll Reference to my project does that mean that when moving the release .exe to another PCs will allow it to run ? or do I have to move the dll Reference too with my project ?

*if Yes then what the best approche to do it ?
dll Reference is too ambiguous thinks im my mind please if someone can help me to understand it specifically the point above
thanks

A: When including dll Reference to my project does that mean that when moving the release .exe to another PCs will allow it to run ?
No this was the old time but with .net one of the main goal was to avoid the dll hell
or do I have to move the dll Reference too with my project ?
yes you have to move all dll in your release folder after compiling was done
if Yes then what the best approche to do it ?
the best approach it depends on what you are targetting
you can just zip the release folder and copy it to your target machine  I think it is the best one for you to get started


text:
Q: Using result from a function to access a julia array I'm new to julia and have a problem.  I have an array, y.
y = rand (5, 10)
y [1. 1] = 0

Running this gives me an error
for j=1:d
    x_filt [j, 1] = y [j, findfirst (y [j, :])]
end

ERROR: syntax: missing separator in array expression

But this doesn't
for j=1:d   # fix to 1st obs if 1st tick is missing
    temp = findfirst (y [j, :])
    x_filt [j, 1] = y [j, temp];
end

Can someone explain how to make the first version work?  Or at least explain why it doesn't?
Thanks!

A: First, I guess you meant y[1, 1] = 0? I get an error if I use y [1. 1] = 0.
Julia has space sensitive syntax in some contexts, notable inside brackets [].
Some examples:
julia> max(1, 2)
2

julia> max (1, 2)
2

julia> [max(1, 2)]
1-element Array{Int64,1}:
 2

julia> [max (1, 2)]
1x2 Array{Any,2}:
 max  (1,2)

julia> [1 + 2]
1-element Array{Int64,1}:
 3

julia> [1 +2]
1x2 Array{Int64,2}:
 1  2

In your first example, the call to findfirst in
x_filt [j, 1] = y [j, findfirst (y [j, :])]

is interpreted as two space-separated items, findfirst and (y [j, :])]. Julia then complains that they are separated by a space and not a comma.
In your second example, you were able to circumvent this since the call to findfirst in
temp = findfirst (y [j, :])

is no longer in a space sensitive context.
I would recommend that when writing Julia code, you should never put a space between the function name and parenthesis ( in a function call or the variable and bracket [ in indexing, because the code will be treated differently in space sensitive contexts. E.g., your first example without the extra spaces
for j=1:d
    x_filt[j, 1] = y[j, findfirst(y[j, :])]
end

works fine (provided that you define d and x_filt appropriately first).


text:
Q: How can i append  tags after a text element? I am parsing a HTML file with BeautifulSoup and got stuck with
 tags.
I want to append
 tag after inserting a list element, but it didn't work.
What is the easiest way to do this?
soup = BeautifulSoup(open("test.html"))
mylist = [Item_1,Item_2]
for i in range(len(mylist)):
    #insert Items to the 4. column

This is the default HTML:

     1. Column

     2. Column

     3. Column

     4. Column

     5. Column

     6. Column

     7. Column

     8. Column

     Text in first column

     1

     37

     38

     38

This is the HTML i want to make

     1. Column

     2. Column

     3. Column

     4. Column

     5. Column

     6. Column

     7. Column

     8. Column

     Text in first column

    Item_1

    Item_2

     1

     37

     38

     38

A: To append a tag, first create it with the new_tag() factory function, like so:
soup.td.append(soup.new_tag('br'))

Consider the following program. For every table cell (that is, every td) in the html, it appends a
 tag and some text to the cell.
from bs4 import BeautifulSoup

html_doc = '''

     data1

     data2

'''

soup = BeautifulSoup(html_doc)
mylist = ['addendum 1', 'addendum 2']
for td,item in zip(soup.find_all('td'), mylist):
  td.append(soup.new_tag('br'))
  td.append(item)
print soup.prettify()

Result:

     data1

     addendum 1

     data2

     addendum 2


text:
Q: Compiling model file takes for ever with xcode 7.2 I have updated my Xcode to 7.2 and projects with core data could not be compiled any more.Compile stuck on "Compiling x of x data models".Any idea?
Running Xcode Version 7.2 (7C68) & OS X 10.11.2 (15C50) El Capitan

A: Same here, been experiencing this issue fairly frequently with the latest (7.2 7C68) Xcode build. This one is frustrating but seems a restart is the only reliable solution currently.


text:
Q: Show number of days item is created How do I show the (whole) number of days the item was created and display it in other coulmumn named : active days. I want the counter to stop after the item is closed

A: You can use moment.js
Moment will allow you to use something called .fromNow()
You can pass your date into moment: moment('15/08/2017').fromNow('DD'); which should return: 1 day.
Pretty cool library and worth a check!
Also worth a mention that it can recognise most if not all date and time formats. You may need to use a locale depending on your timezone but should do the job nicely.
Hope this helped?

A: You can follow the post here.
Basically we cannot use Calculated column as it only gets updated when the item is updated. You may need to write a schedule job/workflow to calculate the number of days based on today's date and item creation date and status of the item i.e. "Closed".
The timer job should run daily to calculate the number of days and update the result in another SharePoint field. I generally implement timer job using C# Server Side Console program and read the items in the list one by one.

A: Use the DATEDIF function to perform this calculation.
=DATEDIF([Column1], [Column2],"d")


text:
Q: How hard is it to tamper with a strong named assembly? Assume I have a .NET assembly which is strong named. Only I have access to the private key. I then distribute the assembly to some client system.
How hard is it for the client to modify the assembly? Ie: what would they need to do to modify my assembly?

A: Strong-naming does not prevent modifying the assembly, but it does prevent other applications which reference a strong-named assembly from inadvertently using a modified version.

A: It's no different from modifying a non-strongly typed assembly. The only real difference is that they would have to run the strong name utility (sn.exe) in order to use the modified assembly.

A: As others have said, its very easy.
One technique you can use is to use the public key (or token) of your assembly to encrypt important information (such as algorithm parameters, connection strings, etc) in your assembly. This way if the public key has been changed or removed, the decryption will fail and your assembly would no longer run correctly. Obfuscators such as Crypto Obfuscator use this technique as one part of the protection.


text:
Q: Group array within group data php After generating group array from an associative array, now the array is in the following format. And to make this group array I have used the following code:
foreach($upcoming_data_arr as $key => $item)
        {
            $arr[$item['year']][$key] = $item;
        }

Array
(
    [2018] => Array
        (
            [0] => Array
                (
                    [id] => 6
                    [year] => 2018
                    [month] => 11
                )

            [1] => Array
                (
                    [id] => 5
                    [year] => 2018
                    [month] => 12
                )

            [2] => Array
                (
                    [id] => 4
                    [year] => 2018
                    [month] => 11
                )

            [3] => Array
                (
                    [id] => 3
                    [year] => 2018
                    [month] => 11
                )
        )
)

Now I need another group array according to month within year group. And in this case group data array will be like following:
 Array
    (
        [2018] => Array
            (
                [11] => Array
                    (
                        [0] => Array
                            (
                            [id] => 6
                            [year] => 2018
                            [month] => 11
                            )

                        [1] => Array
                            (
                            [id] => 4
                            [year] => 2018
                            [month] => 11
                            )

                        [2] => Array
                           (
                            [id] => 3
                            [year] => 2018
                            [month] => 11
                            )

                    )

                [12] => Array
                    (
                        [0] => Array
                           (
                           [id] => 5
                           [year] => 2018
                           [month] => 12
                           )
                    )
            )
    )

How we will get this output?

A: Add one more "dimension" when you are creating an array identified by $item['month'] and let php decide last "dimension" key by []:
foreach($upcoming_data_arr as $key => $item) {
    $arr[$item['year']][$item['month']][] = $item;
}


text:
Q: Java JNA call to function "InitiateSystemShutdown" in dll Advapi32 don't work I have this call to the function "InitiateSystemShutdown" of the Advapi32 dll with java jna but it didn't work:
public interface JNAApiInterface extends StdCallLibrary {

    JNAApiInterface INSTANCE = (JNAApiInterface) Native.loadLibrary("Advapi32", JNAApiInterface.class);

    public boolean InitiateSystemShutdown(String machine, String message, short timeout, boolean forceAppClose, boolean rebootAfterShutdown);

}

public class JNABucket {
     public static void main(String args[]) {

          System.setProperty("jna.library.path", "C:\\Windows\\System32");
          JNAApiInterface jnaLib = JNAApiInterface.INSTANCE;

          jnaLib.InitiateSystemShutdown(null, null, (short)0, true, true);
     }
}

The error is:
 Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up
    function 'InitiateSystemShutdown': No se encontró el proceso especificado.
    at com.sun.jna.Function.<init>(Function.java:179)
    at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:430)
    at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:410)
    at com.sun.jna.Library$Handler.invoke(Library.java:205)
    at com.sun.proxy.$Proxy0.InitiateSystemShutdown(Unknown Source)
    at es.tecnocom.pruebas.JNABucket.main(JNABucket.java:9)

Someone can help me?

A: If after changing the funcion to "InitiateSystemShutdownA" or "InitiateSystemShutdownW" still isn't working, it's probably a permissions issue, as @cubrr suggested.
Try adding this:
    HANDLEByReference hToken = new HANDLEByReference();
    LUID luid = new LUID();
    Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), WinNT.TOKEN_ADJUST_PRIVILEGES, hToken);
    Advapi32.INSTANCE.LookupPrivilegeValue("", WinNT.SE_SHUTDOWN_NAME, luid);
    TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES(1);
    tp.Privileges[0] = new LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED));
    Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tp, tp.size(), null, new IntByReference());

just before this call to the function:
jnaLib.InitiateSystemShutdown(null, null, (short)0, true, true);

A: If you take a look at the documentation page for InitiateSystemShutdown, you'll notice at the bottom that the actual function names are InitiateSystemShutdownW (Unicode) and InitiateSystemShutdownA (ANSI). Most (all?) WinAPI functions which deal with strings are defined as preprocessor symbols which resolve to either the *A or *W ending function, depending on whether UNICODE is defined at compile time.
Example from Working with Strings:
#ifdef UNICODE
#define SetWindowText  SetWindowTextW
#else
#define SetWindowText  SetWindowTextA
#endif

Rename your function to InitiateSystemShutdownA or InitiateSystemShutdownW, depending on which encoding you want to use. I've personally always used the ANSI variants, so I don't know if you need to specify the Unicode encoding manually if you go with the *W variant.
public interface JNAApiInterface extends StdCallLibrary {

    JNAApiInterface INSTANCE = (JNAApiInterface) Native.loadLibrary("Advapi32", JNAApiInterface.class);

    public boolean InitiateSystemShutdownA(String machine, String message, short timeout, boolean forceAppClose, boolean rebootAfterShutdown);
}

Notice also that you need certain privileges to restart a computer. Excerpt from the documentation:

To shut down the local computer, the calling thread must have the SE_SHUTDOWN_NAME privilege. To shut down a remote computer, the calling thread must have the SE_REMOTE_SHUTDOWN_NAME privilege on the remote computer. By default, users can enable the SE_SHUTDOWN_NAME privilege on the computer they are logged onto, and administrators can enable the SE_REMOTE_SHUTDOWN_NAME privilege on remote computers. For more information, see Running with Special Privileges.
Common reasons for failure include an invalid or inaccessible computer name or insufficient privilege. The error ERROR_SHUTDOWN_IN_PROGRESS is returned if a shutdown is already in progress on the specified computer. The error ERROR_NOT_READY can be returned if fast-user switching is enabled but no user is logged on.


text:
Q: Problems when using Firebase Tools I'm having troubles when I try to execute firebase commands in the Node.js console. Tipically, it shows me the next sentence (for example, when I execute firebase list):
Error: An unexpected error has occurred.
I'm currently logged in.
When I try to deploy, it shows the next message:

npm ERR! code EPIPE
npm ERR! errno EPIPE
npm ERR! syscall write
npm ERR! EPIPE: broken pipe, write

Thanks in advance!

A: try to reinstall firebase-tools with npm install -g firebase-tools
and make sure to either have a default projectId set or pass one with parameter -P.
it would be great, if you'd add more information; eg. the firebase.json (which might be at fault).


text:
Q: Changing Raster Resolution to match other Raster in QGIS I have a raster layer of 0.125 degree resolution and another raster layer of 0.0833 degree resolution. Both the raster layers are to be overlapped. So, I want to change the resolution of 0.0833 resolution raster to 0.125 resolution such that the pixels exactly overlap over each other i.e. corresponding pixels signify the same point on the map.
P.S.- The 0.125 resolution map is exactly as it should be and is not to be changed.
I tried Gdalwarp simply to change the resolution to 0.125 but the pixels are not overlapping. Any help!!


text:
Q: Length of a delimited string with nulls ( not blanks ) in it I was trying to do some operations on a delimited string. I chanced upon a case where I got to check the length of a delimited string with nulls in it.
For Example :
String str = null+', '+null

Now str.length() gives me 10.
When I change str to ''+', '+'' , the length method returns 2.
I was just wondering, if null has no value in it, why does the string take it into account while calculating the length of it ?
Thanks in advance!

A: Interesting ..
I tried this in dev console
string sone = null + ',' + null;
system.debug(sone);
system.debug(sone.length());

and the result is
23:21:38.057 (57852690)|USER_DEBUG|[2]|DEBUG|null,null
23:21:38.057 (57922386)|USER_DEBUG|[3]|DEBUG|9

and then tried this
string stwo = null;
system.debug(stwo);
system.debug(stwo.length());

result is
23:24:01.057 (57435220)|USER_DEBUG|[5]|DEBUG|null
23:24:01.057 (57698518)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object

I m no Java expert but since Apex is based on Java, did some searching on null in java and found this discussion
concatenating null strings in java
which says

If the reference is null, it is converted to the string "null"

so your initial string concatenation of 2 nulls and comma and a space adds up to 10 in length.
another useful discussion around null in java for additional reference.
What is NULL in Java

A: You should learn about Operator Overloading or operator ad hoc polymorphism.
So when you do String str = null+', '+null it result into a text:

null, null // String concatenation takes place by + operator

Try this:
String nops = null+null // Arithmetic calculation takes pace by '+'

You will get an exception:
Also,
when you do String str = ''+', '+'' it result into a text having two Characters space and comma:

, // String concatenation takes place by + operator and there are two character.
> Line: x, Column: y
>     Arithmetic expressions must use numeric argument

So, the + operator behaves according to the data type you are joining with it. Technically it is operator overloading.

A: The reason String str = null+', '+null has a length of 10 is that each null is taken as a literal text value (4 characters each) plus ', ' is an addition 2 characters for a total of 10 characters.
In the situation with ''+', '+'' only the ', ' is counted for a total of 2 characters.
With strings, the concept of null has little meaning. That's why strings should be checked using isEmpty() instead of tested for equality with null.


text:
Q: Optical Isolation of BNC trigger? I am wondering if there is a more practical way to provide optical isolation for a BNC trigger. I am currently using the following: https://www.eagleharbortech.com/product-categories/fiber-optic-isolation/
These are several hundred dollars each and I am thinking a cheaper option or other work-around should be available.


text:
Q: ASP.NET MVC 5 How to update custom property of ApplicationUser as I wrote in title, I have this code:
public class ApplicationUser : IdentityUser
{
    public virtual MapPosition MapPosition { get; set; }

    public ApplicationUser()
    {
        MapPosition = new MapPosition { PositionX = 0, PositionY = 0 };
    }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<MapPosition> MapPositions { get; set; }

    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

And in my controller I have method that I call from @Ajax.ActionLink in my view:
public string ChangeXPosition()
    {
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        // Get the current logged in User and look up the user in ASP.NET Identity
        currentUser = manager.FindById(User.Identity.GetUserId());
        currentUser.MapPosition.PositionX++;

        //manager.Update(currentUser);
        Debug.WriteLine("currentUser.MapPosition.PositionX: " + currentUser.MapPosition.PositionX);

        return "currentUser.MapPosition.PositionX: " + currentUser.MapPosition.PositionX;
    }

I want to save to database changed value of currentUser.MapPosition.PositionX.
I have found numerous ways to solve this problem, but none of them worked with my project.
I tried those solutions:
how-to-update-identityuser-with-custom-properties-using-mvc5-and-entity-framewor
updating-user-data-asp-net-identity
mvc5-applicationuser-custom-properties
UPDATE
Ok so I tried to do as you said, but still doesn't work:
public class ApplicationUser : IdentityUser
{
    public virtual MapPosition MapPosition { get; set; }

    public ApplicationUser()
    {
    }
}

This version works, my controller method does change the value in the table.
But it works only for user, that have been already created. When I create a new User, his new MapPositions record is not created.
public class ApplicationUser : IdentityUser
{
    private MapPosition _mapPosition;
    public virtual MapPosition MapPosition
    {
        get { return _mapPosition ?? (_mapPosition = new MapPosition()); }
    }

    public ApplicationUser()
    {
    }
}

This version doesn't work at all, doesn't change the value in database and doesn't create record in MapPositions when new user is created.

A: At least you have to invoke SaveChanges method on the current ApplicationDbContext instance after updating the entity instance's fields/properties (currentUser.MapPosition.PositionX in your case):
public string ChangeXPosition()
    {
        var dbContext = new ApplicationDbContext();
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(dbContext));
        // Get the current logged in User and look up the user in ASP.NET Identity
        currentUser = manager.FindById(User.Identity.GetUserId());
        currentUser.MapPosition.PositionX++;

        //manager.Update(currentUser);
        Debug.WriteLine("currentUser.MapPosition.PositionX: " + currentUser.MapPosition.PositionX);
        dbContext.SaveChanges();
        return "currentUser.MapPosition.PositionX: " + currentUser.MapPosition.PositionX;
    }

If it does not help, then you have to explicitly mark the corresponding entry as Modified in the DbContext's change tracker in the following way:
dbContext.Entry(currentUser.MapPosition).State = EntityState.Modified;

After that the change should occur in a database as you can see by manually checking the data in the corresponding table at the database (by using Visual Studio SQL Server Data Tools extension, SQL Server Management Studio or any other database management tool).


text:
Q: Unable to change camera / stream for WebRTC call Source: https://github.com/anoek/webrtc-group-chat-example/blob/master/client.html
I'm trying to modify this Webrtc example to add the ability of changing camera (Cross-browser support).
Normal usage works perfectly, after changing camera, failed in renegotiation.
1) Get a list of devices via navigator.mediaDevices.enumerateDevices()
2) Change local_media_stream after getting new stream
local_media_stream.getTracks().forEach(function(track) {
    track.stop();
});
local_media_stream = stream;

3) Trigger renegotiation function (Copied from line 132 of Source code)
function renegotiate(){
    console.log("Creating RTC offer to ", peer_id);
    peer_connection.createOffer(
                    function (local_description) {
                        console.log("Local offer description is: ", local_description);
                        peer_connection.setLocalDescription(local_description,
            function() {
                signaling_socket.emit('relaySessionDescription',
                    {'peer_id': peer_id, 'session_description': local_description});
                console.log("Offer setLocalDescription succeeded");
            },
            function() { Alert("Offer setLocalDescription failed!"); }
        );
    },
    function (error) {
        console.log("Error sending offer: ", error);
    });
};

I believe that my approaches are wrong, but I've tried many different ways found on google to edit the codes for renegotiation, however I'm not familiar to WebRTC and Socket.io, still can't make the thing works.
After changing the camera, the video shown on other participant just became a static image from video last frame.
Can anybody please help to point my mistake? Thanks in advance.

A: Previously I done it in the following way (an order is important).
Let's say you list all our available devices:
var devicesIds = [];

navigator.mediaDevices.enumerateDevices().then(function(devices) {
  devices.forEach(function(device) {
     devicesIds.push(device.deviceId);
  });
});

And now you want to switch:
1) Stop current tracks
localStream.getTracks().forEach(function(track) {
   track.stop();
});

2) Obtain new stream
var constraints = {video: {deviceId: devicesIds[1]}, audio: true};

navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
  replaceTracks(stream);
}).catch(function(error) {

});

3) Replace tracks:
function replaceTracks(newStream){

  detachMediaStream(elementId);

  newStream.getTracks().forEach(function(track) {
     localStream.addTrack(track);
  });

  attachMediaStream(elementId, newStream);

  // optionally, if you have active peer connections:
  _replaceTracksForPeer(peerConnection);

  function _replaceTracksForPeer(peer) {
    peer.getSenders().map(function(sender) {
        sender.replaceTrack(newStream.getTracks().find(function(track) {
            return track.kind === sender.track.kind;
        }));
    });
  }
}

function detachMediaStream = function(id) {
  var elem = document.getElementById(id);

  if (elem) {
    elem.pause();

    if (typeof elem.srcObject === 'object') {
        elem.srcObject = null;
    } else {
        elem.src = '';
    }
  }
};

function attachMediaStream = function(id, stream) {
  var elem = document.getElementById(id);

  if (elem) {
    if (typeof elem.srcObject === 'object') {
        elem.srcObject = stream;
    } else {
        elem.src = window.URL.createObjectURL(stream);
    }

    elem.onloadedmetadata = function(e) {
        elem.play();
    };
  } else {
    throw new Error('Unable to attach media stream');
  }
};


text:
Q: Unity3D Android build report complete size too large I noticed the complete size takes up to 90% more than it should in my Android project. What are the things that takes so much of space? I read some topics in this forum and some claimed it's the unity engine that has big size, but for ~130MB!? How do we check wat takes up so much space?
Build Report
Uncompressed usage by category:
Textures      7.7 mb     5.3%
Meshes        735.3 kb   0.5%
Animations    779.7 kb   0.5%
Sounds        0.0 kb     0.0%
Shaders       69.1 kb    0.0%
Other Assets  125.9 kb   0.1%
Levels        29.1 kb    0.0%
Scripts       1.1 mb     0.8%
Included DLLs 3.9 mb     2.7%
File headers  44.6 kb    0.0%
Complete size 145.3 mb   100.0%

Edit:
This is what i got from analysing the APK using Android Studio, and it seems smaller from unity report. Why?

A: You can check your apk file like this:
Android Studio -> Build -> Analyze APK


text:
Q: serializing two different models with django I have two models Property and PropertyImage.
Property holds all the data and PropertyImage is only for allowing an unlimited number of images to be uploaded.
 class PropertyImage(models.Model):
     property = models.ForeignKey(Property, related_name='images')
     url = models.ImageField(upload_to=property_image_name)

What I want is to be able to add one field to the serialization of the Property class so that it will add the PropertyImage.url element. It does not need to be all of the url elements that the Property has, one would be enough. I am using this for previewing the Property.
Now, I have:
results = Property.objects.raw(mysql_query)
markers = serializers.serialize('json',results)

and of course the PropertyImage is left out and I can't find a clean way of adding it to the JSON and relating it with the Property it belongs.

A: You can proceed with model_to_dict():
import json
from django.forms.models import model_to_dict

results = Property.objects.raw(mysql_query)
data = []
for result in results:
    model = model_to_dict(result)
    model['image_url'] = model.property_image_set.first().url
    data.append(model)

markers = json.dumps(data)

Here's an image_url field is set to the first() PropertyImage's url field value for the each Property instance in the results queryset.
Also see:

*

*Django reverse lookup of foreign keys

*How to JSON serialize __dict__ of a Django model?
Hope that helps.


text:
Q: OR and NOT EQUAL TO statement in queries I've had a look into OR statements and NOT EQUAL TO in Firebase queries, however I couldn't find anything to get it working.
What would be the most efficient way to execute either query?
Thank you all for your help!


text:
Q: fluent nhibernate copy a full entity how can I best copy an entity instance in fluent nhibernate 3.3.1;
I read an object out of the database, I got an object, now I change some values of this object. This object with little changes want I save.
I have tried to set the Id to 0, this is not working, also I write a Clone method in my Entityclass. Here is my approach.
public class Entity: ICloneable
{
    public virtual int Id { get; protected set; }

    object ICloneable.Clone()
    {
        return this.Clone();
    }

    public virtual Entity Clone()
    {
      return (Entity)this.MemberwiseClone();
    }
}

Do you some tips for me.

A: If your objects are not serializable and you are just looking for a quick one-to-one copy of them, you can do this pretty easily with AutoMapper:
// define a one-to-one map
// .ForMember(x => x.ID, x => x.Ignore()) will copy the object, but reset the ID
AutoMapper.Mapper.CreateMap<MyObject, MyObject>().ForMember(x => x.ID, x => x.Ignore());

And then when you copy method:
// perform the copy
var copy = AutoMapper.Mapper.Map<MyObject, MyObject>(original);

/* make copy updates here */

// evicts everything from the current NHibernate session
mySession.Clear();

// saves the entity
mySession.Save(copy); // mySession.Merge(copy); can also work, depending on the situation

I chose this approach for my own project because I have a lot of relationships with some weird requirements surrounding record duplication, and I felt this gave me a little more control over it. Of course the actual implementation in my project varies a bit, but the basic structure pretty much follows the above pattern.
Just remember, that the Mapper.CreateMap<TSource, TDestination>() creates a static map in memory, so it only needs to be defined once. Calling CreateMap again for the same TSource and TDestination will override a map if it's already defined. Similarly, calling Mapper.Reset() will clear all of the maps.

A: You need to

*

*Load entity with NH

*Clone the entity with method below, and create copy

*Evict main entity

*Do changes to copy

*Update the copy, without any reference to the main entity

The clone method is as follows
         /// <summary>
     /// Clone an object without any references of nhibernate
     /// </summary>
    public static object Copy<T>(this object obj)
    {
        var isNotSerializable = !typeof(T).IsSerializable;
        if (isNotSerializable)
            throw new ArgumentException("The type must be serializable.", "source");

        var sourceIsNull = ReferenceEquals(obj, null);
        if (sourceIsNull)
            return default(T);

        var formatter = new BinaryFormatter();
        using (var stream = new MemoryStream())
        {
            formatter.Serialize(stream, obj);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }

To use it you call it as follows
object main;
var copy = main.Copy<object>();

To see some other opinions on what to use, you can view this link aswell Copy object to object (with Automapper ?)


text:
Q: Подключение QChartView как кастомного виджета в Qt Designer Пытаюсь подключить QChartView как кастомный виджет, способом, описанным в документации.
Делаю "Преобразовать в...":

Затем преобразовываю в него QGraphicView. При компиляции возникает ошибка в автоматически генерируемом файле формы:

C:\Users\Shmeisser\Documents\build-DBHandler-Desktop_Qt_5_7_1_MinGW_32bit-Debug\ui_dbanalyzewindow.h:34: ошибка: 'QChartView' does not name a type
       QChartView *graphicsView;

В .pro файл QT += charts подключено, проект пересобирал. В чем может быть проблема?

A: В "Преобразовать в..." нужно вписывать следующее:

Base class name: QWidget
Promoted class name: QtCharts::QChartView
Header file: QtCharts/QChartView
Global include: checked


text:
Q: (!potential spoilers for people who haven't played) In the Witness, how do I solve this puzzle?
I'm terrified to Google this and I would appreciate if anyone could answer this as gingerly and spoiler-free as possible because I'm not very far in the game and I'd like to experience all of the puzzles on my own. I take exception with this particular quandary because I've spent the last 30 minutes feathering the thumbstick ever-so-slightly in every direction, trying to get this thing to activate, and it won't do it.
I'm getting varying degrees of sparks when I click in the circle, but I can't seem to line it up properly. Is there a different (maybe higher?) perspective that I am supposed to activate it from? Does the circle on the right-hand side need to be fully closed (ie: no chunk cut out in the middle)? Or is it more important that the circle is as circular as possible? The amount of sparks on the various attempts seems to indicate that the latter is more important, but about 300 attempts haven't sealed the deal, and I'm starting to question my sanity :p
Thanks in advance for your help :) The game is really great so far!! I was grinning like a buffoon when I discovered the first symbol for the black obelisks; I thought the game consisted entirely of the little panel puzzles.

A: I know this isn't the answer you're looking for, but I'd recommend coming back to this later. There are other environmental puzzles in other parts of the island that, once you have found them, the answer to this one will be obvious.
Really. I'd encourage you to stop reading now. The game is more fun the more puzzles you solve on your own.
But if you insist, here's my gingerly worded hint.

 It looks like a piece of the circle is missing. Can you find a way to fill it in?


text:
Q: How can I make my regular expression match variables inbetween brackets on single and multiple lines? I am trying to match all environment variables that get de-structured from process.env in my Typescript project. This includes matching de-structuring on single or multiple lines.
Take the following TS code examples that contains de-structuring from process.env, 1 is on a single line, the other is across multiple lines:
File1.ts:
const { OKTA_AUDIENCE_DOMAIN, OKTA_DOMAIN = '', OKTA_WEB_CLIENT_ID, OKTA_ISSUER: issuer = '', AUTH_TWO: ISSUE_TWO = '', } = process.env;

File2.ts:
const {
  OKTA_AUDIENCE_DOMAIN,
  OKTA_DOMAIN = '',
  OKTA_WEB_CLIENT_ID,
  OKTA_ISSUER: issuer = '',
  AUTH_TWO: ISSUE_TWO = '',
} = process.env;

I have only been able to write a script that matches the de-strucutred variables on the single line. However, I want the script to match single and multi lines.
This is the script I currently have:
grep -Ezo '\{[^}]*\} = process.env' File1.ts

If ran on File1, I would get the following output, which is what I expect:
{ AUTH0_AUDIENCE_DOMAIN, AUTH0_DOMAIN = '', AUTH0_WEB_CLIENT_ID, AUTH0_ISSUER: issuer = '', AUTH_TWO: ISSUE_TWO = '', } = process.env

You can see here that it has correctly matched the environment variables being de-structured from process.env
Now if I were to run this same script on File2.ts, it would return nothing:
grep -Ezo '\{[^}]*\} = process.env' File2.ts

The output is empty.
How can I modify this script such that it matches the environment variables being de-structured on both single and multiple lines?

A: Try this:
cat File1.ts | tr '\n' ' ' | sed 's/  */ /g' | grep -Ezo '\{[^}]*\} = process.env'
cat File2.ts | tr '\n' ' ' | sed 's/  */ /g' | grep -Ezo '\{[^}]*\} = process.env'

Notes:

*

*tr changes newlines to spaces (change to tr '\n\r' '  ' if you are on Windows)

*sed gets rid of multiple spaces

*grep has your original parameters

A: If you are okay with installing ripgrep
rg -oU '\{[^}]*\} = process\.env'

The -U option enables multiline matching.
That said, grep -oz '{[^}]*} = process\.env' works for me for your given input samples. Also, note that with grep -z the output will be terminated with ASCII NUL characters. So, you'll need to further process the output, for example pipe to tr '\0' '\n'


text:
Q: carousel using jQuery I know there are plugins available out there, but I'm trying to make one of myself but before that I'm trying to understand the concept of making it as an infinite/circular carousel. Here is my jsfiddle so far..  http://jsfiddle.net/hbk35/KPKyz/3/
HTML:

0

1

2

3

4

5

6

7

    <button id="left">left</button>
    <button id="right">right</button>

JS:
var container = $("#carousel_wrapper");

var runner = container.find('ul');
var liWidth = runner.find('li:first').outerWidth();
var itemsPerPage = 3;
var noofitems = runner.find('li').length;

runner.width(noofitems * liWidth);
container.width(itemsPerPage*liWidth);

$('#right').on('click',function(){
   runner.animate({scrollLeft: -liWidth},1000);
});

$('#left').on('click',function(){
    runner.animate({scrollLeft: liWidth},1000);
});

CSS:
div#carousel_wrapper{

    overflow:hidden;
    position:relative;
}

ul {
    padding:0px;
    margin:0px;
}
ul li {
    list-style:none;
    float:left;
}
ul li div {
    border:1px solid white;
    width:50px;
    height:50px;
    background-color:gray;
}

I do not want to use clone and detach method. Is there any other way to do that?
Please anyone would like to guide me where I'm making mistake. I'm newbie to stack overflow and javascript/jquery also..trying to learn on my own. Forgive me I'm trying since to put my code onto the question, couldn't get neat and separate like others.
Thanks!!

A: Here you go an infinite. Could be done with less code for sure.
http://jsfiddle.net/artuc/rGLsG/3/
HTML:
Previous
Next

1

2

3

4

5

6

7

8

9

10

11

12

13

14

CSS:
.carousel{
        padding-top: 20px;
        width: 357px;
        overflow: hidden;
        height: 50px;
        position: relative;
    }.carousel ul{
        position: relative;
        list-style: none;
        list-style-type: none;
        margin: 0;
        height: 50px;
        padding: 0;
    }.carousel ul li{
        position: absolute;
        height: 25px;
        width: 50px;
        float: left;
        margin-right: 1px;
        background: #f2f2f2;
        text-align: center;
        padding-top: 25px;
    }

JS:
$(function(){
        var carousel = $('.carousel ul');
        var carouselChild = carousel.find('li');
        var clickCount = 0;
        var canClick = true;

        itemWidth = carousel.find('li:first').width()+1; //Including margin

        //Set Carousel width so it won't wrap
        carousel.width(itemWidth*carouselChild.length);

        //Place the child elements to their original locations.
        refreshChildPosition();

        //Set the event handlers for buttons.
        $('.btnNext').click(function(){
            if(canClick){
                canClick = false;
                clickCount++;

                //Animate the slider to left as item width
                carousel.stop(false, true).animate({
                    left : '-='+itemWidth
                },300, function(){
                    //Find the first item and append it as the last item.
                    lastItem = carousel.find('li:first');
                    lastItem.remove().appendTo(carousel);
                    lastItem.css('left', ((carouselChild.length-1)*(itemWidth))+(clickCount*itemWidth));
                    canClick = true;
                });
            }
        });

        $('.btnPrevious').click(function(){
            if(canClick){
                canClick = false;
                clickCount--;
                //Find the first item and append it as the last item.
                lastItem = carousel.find('li:last');
                lastItem.remove().prependTo(carousel);

                lastItem.css('left', itemWidth*clickCount);
                //Animate the slider to right as item width
                carousel.finish(true).animate({
                    left: '+='+itemWidth
                },300, function(){
                    canClick = true;
                });
            }
        });

        function refreshChildPosition(){
            carouselChild.each(function(){
                $(this).css('left', itemWidth*carouselChild.index($(this)));
            });
        }
    });

A: Here you go: http://jsfiddle.net/KPKyz/5/
JS
var container = $("#carousel_wrapper");

var runner = container.find('ul');
var liWidth = runner.find('li:first').outerWidth();
var itemsPerPage = 3;
var noofitems = runner.find('li').length;

runner.width(noofitems * liWidth);
container.width(itemsPerPage*liWidth);

$('#right').click(function() {
    $( runner  ).animate({ "left": "-=51px" }, "slow" );
});

$('#left').click(function() {
    $( runner  ).animate({ "left": "+=51px" }, "slow" );
});

CSS
div#carousel_wrapper{

 overflow:hidden;
 position:relative;
 width:500px;
 height: 100px;
}

ul {
 padding:0px;
 margin:0px;
 position: absolute;
 top:50px;
 left: 0px;
 width:300px;
 height: 50px;
 overflow: hidden;
 }
 ul li {
   list-style:none;
  float:left;
 }
ul li div {
  border:1px solid white;
  width:50px;
  height:50px;
  background-color:gray;
}


text:
Q: User-Specific Activity Level Along Weeks I am assigning Low | Medium | High activity levels to users once a week.
At the end of an entire period,a user has been assign n weekly activity levels among {Low, Medium, High}.
Let k be the total number of users, then the data table would look like this:
User   Week_1   Week_2   ...   Week_n
User_1 Low      Low      ...   High
User_2 Medium   Low      ...   Low
.      .        .        .     .
.      .        .        .     .
.      .        .        .     .
User_k High     Medium   ...   Medium

How would you formulate a metric within [0,1] that quantifies the "stickiness" of user, that is, the variability of it's activity label over the entire period.
With such a metric, a user which is assigned always the same activity level (let's say, n times "High"), would have a 100% metric.
Thanks in Advance for your suggestions!

A: I assume that Low-Medium or High-Medium combination are more stick than Low-High ones. That is, that are ordered so the "distance" from Low to High is bigger than to Medium.
I also assume that the order does not matter: High High Low will have the same stickiness than High Low High
If this is it,
1. You can assign 1 to Low, 2 to Medium, 3 to High
2. calculate the variance for each row
3. 100% would be 0 variance, 0% would be the variance of the vector (1,3,1,3...)
4. Map your variances to the range given in 3.
Best!


text:
Q: O que faz a expressão "for x in *;"? Vi essa expressão numa pergunta do SOEN, porém não entendi muito bem o que ela faz
for x in *;
do
    echo $x;
done

Isso imprimiu a lista de pastas do diretório que eu estava.
É para isso que serve essa expressão?
O que seria esse * asterisco?

A: Isto, escrito da forma que está, faz a mesma coisa que o comando ls
O * está sendo usado como coringa.
Experimente deste modo:
for x in *.zip;do echo $x; done;
Você pode usar as mesmas regras que utiliza no ls, como por exemplo:
for x in ./*/*.zip;do echo $x; done;
ou
for x in /var/log/*.log;do tail $x; done;
Como exemplo prático, o código abaixo limpa o conteúdo dos logs no ambiente de desenvolvimento:
for x in /var/log/*.log;do echo '' > $x; done;

A: O asterisco indica a leitura de tudo que há na pasta.
A variável X recebe os nomes dos arquivos individualmente, os quais são impressos pelo construtor echo.


text:
Q: obtaining xml node value in javascript I'm putting together a script for InDesign using javascript, and have a settings xml file from which I'd like to pull out a value of a particular node.
I've successfully read in the XML file
var xml = new XML(file.read());

and can easily pull attribute values / node lengths etc, however I'd like to pull the text inside a particular node.

    <title>This is the title</title>

I've tried xml.article[0].title but this returns an XML object not the vale. I've tried nodeValue to no success. How do I obtain the actual text?

A: This did the trick:
xml.article[0].title.toString()

A: Its very simple, just searching the stackoverflow should have given you the result
var sXML = "
<title>This is the title</title>
";
$( document ).ready( function ()
{
    var xmlDoc = $( sXML );
    xmlDoc.filter( 'article' ).each( function ()
    {
        alert( $( this ).find( 'title' ).text() );
    } );
} );


text:
Q: R: Sorting text within a field based on end of line returns \n Suppose I have a vector in which each field represents a string of values separated by an end line return e.g. :
x<-c("Banana\nApple\nCherry", "Dog\nCat")

Is it possible to sort the text alphabetically within each field so that x becomes:
> x
[1] "Apple\nBanana\nCherry" "Cat\nDog"

?
Thanks!

A: One option would be splitting the strings using strsplit, sort the individual elements in the list and paste
sapply(strsplit(x, "\n"), function(x) paste(sort(x), collapse="\n"))
#[1] "Apple\nBanana\nCherry" "Cat\nDog"


text:
Q: Pass a String parameter as a non-array? I'm passing a String parameter into a java function I wrote.
When I pass the string parameter the method is accepting my parameter as follows
http://mywebsite.com/getCity.php?StateID={"state":"Alabama"}
I want my method to accept my string parameter as follows
    http://mywebsite.com/getCity.php?StateID=Alabama
How do I get rid of     {"state":"Alabama"}?
Hey Guys,
I'm building an android app. My syntax below is definitely java. I'm going to show you where I'm having trouble. I'm having trouble on the first line of the method so to show you the entire method would be silly.
    public JSONArray getDetails(String StateID) {

        // this Log.e is showing {"state":"Alabama"}
        // how do I get it to show Alabama?
        Log.e("StateID= " + " = ", StateID);
}

A: I'm don't know Java, but the best method would be to deserialize the string into a Java object that had a state property. See: http://www.javacreed.com/gson-deserialiser-example/
Alternatively, you could just do something ugly like this:
StateID.substring(10, StateID.length - 2)
Which should trim {"state":"  off the front, and trim "}  off of the back.

A: You've got a JSON object there (and it really should be URL encoded if it's going to live on a URL like that).
Treat it like a JSON object and use JSONObject to decode it.  Deal with the checked exception thrown however you see fit.
JSONObject jsonObject = new JSONObject(StateID);
System.out.println(jsonObject.getString("state"));


text:
Q: Увеличить размер диска CentOS 6.5 Забивается место на /dev/mapper/vg_centos65-lv_root (sda2). Виртуалка.
Подскажите, как можно увеличить размер этого диска?

A: Добавь на виртуалку новый диск. Появится /dev/sdc.
Создай на нем раздел /dev/sdc1
cat << EOF | fdisk /dev/sdc
o
n
p
1

w
EOF

Инициализация lvm
pvcreate /dev/sdc1
vgextend vg_centos65 /dev/sdc1

Добавить место к разделу
lvextend -l +100%FREE /dev/mapper/vg_centos65-lv_root

И растянуть файловую систему на это место
resize2fs /dev/mapper/vg_centos65-lv_root


text:
Q: graphwin problems: 'list' object has no attribute 'onSaveClick' I have (probably) a stupid error on my Python source code, then I search for a simple example to verify if it is my error not and I verify that this simple example/test does not work:
from graphics import *

if __name__ == '__main__':

    def main():
        win = GraphWin('My Graphics', 250, 250) # specifies graphics window size 250x250
        g = Point(125, 125) # creates a Point object at x=125 y=125
        g.draw(win) # draws to the graphics window
        win.getMouse() # keep window up
        win.close()

    main()

It stops after g.draw(win) with this error:
AttributeError: 'list' object has no attribute 'onSaveClick'

I followed the code and I found that the error could be on class GraphWin(tk.Canvas):
in the method:
def addItem(self, item):
    self.items.onSaveClick(item)

So it could be a bug.
Or have I misunderstand something?

A: In Python 3.8.6 graphics.py has an error inside, addItem() method has self.onSave(item) instead of self.items.append(item) so updating graphics.py to the 5.0 release solves the problem as pointed out by https://stackoverflow.com/users/355230/martineau


text:
Q: Class-Path not getting write to MANIFEST.MF file on jar creation I need to create a jar file I did the steps as follows:
C:\TIPL\GCST>javac -classpath lib/xbasej-20091203.jar Test.java

C:\TIPL\GCST>jar cfm MyJar.jar manifest.txt Test.class

My manifest.txt file as follows:
Main-Class: Test
Class-Path: commons-logging-1.1.1.jar xbasej-20091203.jar

My Test.java as follows:
import org.xBaseJ.DBF;

public class Test
{
public static void main(String args[]){

try{

//Open dbf file
DBF classDB=new DBF("Class.dbf");
System.out.println("here");
}
catch(Exception e){
}

}
}

I am getting created the jar file , but when I extract it and inside my Manifet.MF file it looks like this:
Manifest-Version: 1.0
Created-By: 1.8.0_25 (Oracle Corporation)
Main-Class: Test

It is not getting the class-path append to it. Due to this when I run my jar file I am getting errors? How can I solve this? What is the reason the classpath not getting append on MANIFEST.MF

A: In manifest text after putting your contents you must put an extra space into it. So Do an Enter after adding all contents in manifest.txt


text:
Q: How to create a rolling window of fixed length in pandas? Given a timeseries, how do I create a rolling window of some interval such that it starts with that same interval, instead of expanding from size 1. As seen here:
import pandas as pd
from datetime import timedelta

# 'per' x 1 minute (1T) intervals
per = 10
d = pd.DataFrame(
    {'a': list(range(per))},
    index=pd.date_range('2021-05-01T0000', freq='1T', periods=per))

# create a rolling 5 minute window and get its length
w = d.rolling(timedelta(minutes=5))
for wi in w:
    print(len(wi))

# Output (window lengths):
# Window starts with length 1 and iterates until it expands
# to desired size:
#1
#2
#3
#4
#5  < I only want windows starting here
#5
#5
#5
#5

How to instead start the window with the specified window size?

A: Maybe a "workaround": you can use itertools.dropwhile to filter the windows with length < 5:
from itertools import dropwhile

w = dropwhile(lambda w: len(w) < 5, d.rolling(timedelta(minutes=5)))
for wi in w:
    print(len(wi))

Prints:
5
5
5
5
5
5


text:
Q: How do i copy n characters for m lines in a file (in c)? I have a file of 1000 lines with up to 70 characters in them. I want to copy the 13 first in a table, the 15th-30th in another table... i tried many different things without success, here's one of them :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define size_num 13  // 13 character with \0 included
#define line 1000
#define carac 300 // like 300 characters per line

int verifFile(FILE*pf)    //check file
{
    if (pf == NULL)
    {
        printf("can't open file");
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    float td,tf;
    td=clock(); //count execution time of program
    FILE* pf=NULL;
    pf = fopen("call.txt", "r");
    verifFile(pf);
    char str[line];
    char number[line][size_num];
    while(fgets(str,line,pf)!= NULL)
    {
        printf("%s", str);
        number[line][size_num]=str[line]; // here i want number to copy the 13 first characters
                                            //of each 1000 lines
    }
    printf("\nsecond : \n"); // separates the printings
    for(int i;i<1001;i++)
    {
        for(int j;j<14;j++)
        {
            printf("%c",number[i][j]); //supposed to print each charac stored (doesnt work)
        }
    }
    tf=clock();
    printf("\n execution time : %f secondes",(tf-td)/CLOCKS_PER_SEC);   //display execution time
    return 0;
}

there are no warnings so i dont know what to do :/

A: The way you copy the substrings is broken:
    while(fgets(str,line,pf)!= NULL)
    {
        printf("%s", str);
        number[line][size_num]=str[line]; // here i want number to copy the 13 first characters
                                            //of each 1000 lines
    }

First of all, you always assign to number[1000][13] which is illegal as number only has 1000 rows, i.e. maximum index is 999. Also each row only has 13 elements making 12 the maximum index.
Same out of bounds access happens for str.
Then you do not have any counter indicating in which element of your array you want to copy the string.
Finally, strings cannot be copied by a simple assignment. You need to use strcpy or strncpy.
This loop should look like that:
    int row = 0;
    while(fgets(str,line,pf)!= NULL)
    {
        printf("%s", str);
        strncpy(number[row], &str[0], size_num);
        number[row][size_num-1] = 0; // Don't forget to terminate the string!

        // Add copying the other parts here as well...

        row++;
    }

Then you also have a problem with printing the content:
    for(int i;i<1001;i++)
    {
        for(int j;j<14;j++)
        {
            printf("%c",numero[i][j]); //supposed to print each charac stored (doesnt work)
        }
    }

Again, you have out of bounds accesses.
And you print all possible lines even if the file only contains a few lines.
Also you do not even initialize your loop counters to 0.
Do this instead:
    for(int i = 0; i<row;i++)
    {
#if 0
// use this part if you really want to print char by char...
        for(int j = 0; j<size_num; j++)
        {
            printf("%c",numero[i][j]); //supposed to print each charac stored (doesnt work)
        }
#else
// Use this if you want to print the string at once.
        printf("%s\n",numero[i]);
#endif
    }


text:
Q: How to get two type of indices at the same time by numpy? Suppose you have a ndarray z, and would like to get following indices
z_idxes1 = np.argwhere(z == i)
z_idxes2 = np.argwhere(z != i)

Can we do this in one call to some numpy function rather than two calls of argwhere?

A: Not in one call, but you can use logical not operator to get the negation of your mask array.
mask = (z == i)
z_idxes1 = np.argwhere(mask)

z_idxes2 = np.argwhere(~mask)


text:
Q: Circle CI how to deploy to ssh - error The authenticity can't be established I would like to deploy my code into my server using SSH.
I add ssh key to circle ci settings.
In circle ci pipeline I have code...
scp -q -r /build root@XXXXXXXX:/root/test
problem is, that I have The authenticity of host 'XXXXXXXX (XXXXXXXX )' can't be established. message. How can I skip it or confirm it?
scp -q -r /build root@XXXXXXXX:/root/test
The authenticity of host 'XXXXXXXX (XXXXXXXX )' can't be established.
ECDSA key fingerprint is SHA256:6+xxxx.
Are you sure you want to continue connecting (yes/no)?

How can I respond to the prompt in a circle ci pipeline job? It is running somewhere on some server.

A: You are looking for option -o StrictHostKeyChecking=no. Below code should do this.
scp -q -r -o StrictHostKeyChecking=no /build root@XXXXXXXX:/root/test


text:
Q: How to restart ipdb while in debugging? My main goal is to restart ipdb, which should continue on the beginning on the code and catch on the first break-point.
# code.py

val = 10
print(f"Hello_World {val}")
__import__('ipdb').set_trace(context=5)
print("Goodbye_World")

run:
$ ./code.py
Hello_World 10
> /home/alper/eBlocBroker/doo.py(4)<module>()
      1 val = 10
      2 print(f"Hello_World {val}")
      3 __import__('ipdb').set_trace(context=5)
----> 4 print("Goodbye_World")   // right away catched here

ipdb>

[Q] At this point, I updated my code setting val into 11. Now, I want to restart the ipdb session (without closing it) and it should be catched on the same break point, is it possible?

*

*If I run as python3 -m ipdb code.py it does not start from the breakpoint instead it starts from top of the file, which I don't want.

If I type: restart I get following error:
Traceback (most recent call last):
  File "doo.py", line 4, in <module>
    print("Goodbye_World")
  File "doo.py", line 4, in <module>
    print("Goodbye_World")
  File "/usr/lib/python3.7/bdb.py", line 88, in trace_dispatch
    return self.dispatch_line(frame)
  File "/usr/lib/python3.7/bdb.py", line 112, in dispatch_line
    self.user_line(frame)
  File "/usr/lib/python3.7/pdb.py", line 259, in user_line
    self.interaction(frame, None)
  File "/home/alper/venv/lib/python3.7/site-packages/IPython/core/debugger.py", line 305, in interaction
    OldPdb.interaction(self, frame, traceback)
  File "/usr/lib/python3.7/pdb.py", line 350, in interaction
    self._cmdloop()
  File "/usr/lib/python3.7/pdb.py", line 319, in _cmdloop
    self.cmdloop()
  File "/home/alper/venv/lib/python3.7/site-packages/IPython/terminal/debugger.py", line 126, in cmdloop
    stop = self.onecmd(line)
  File "/usr/lib/python3.7/pdb.py", line 416, in onecmd
    return cmd.Cmd.onecmd(self, line)
  File "/usr/lib/python3.7/cmd.py", line 217, in onecmd
    return func(arg)
  File "/usr/lib/python3.7/pdb.py", line 1026, in do_run
    raise Restart
pdb.Restart

If you suspect this is an IPython 7.16.1 bug, please report it at:
    https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev@python.org

You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.

Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
    %config Application.verbose_crash=True

A: *

*Ctrl-d Ctril-c to break the loop.

*Ctrl-d to restart the session

#!/bin/bash

control_c()
{
    printf goodbye
    # kill -SIGINT $(jobs -p)
    exit #$
}

trap control_c SIGINT

while true
do
    ./Driver.py
    # sleep 10 &
    wait
    printf "\n"
    # loop infinitely
done


text:
Q: Why my server request takes 28 Second to get response? I have a Wordpress website on a Godaddy server having at http://kerala.letmeshare.org.
When I request to get this website this takes almost  28 sec to get reply.
Because of this I made a complete caching on both client side and server side. This reduced webpage request from 69 to 32, and from 1.2 MB to 200 KB. But the initial request time is remains same.
How can i Improve this? or is it the problem of Hosting Server?

A: According to this brief article, here are some triggers that cause Apache to perform reverse DNS lookups:
http://betabug.ch/blogs/ch-athens/933

*

*HostnameLookups on somewhere

*checking of allow / deny rules with domains instead of IP ranges, e.g. Allow from www.example.org or Deny from example.org

*a rewrite rule with a condition like RewriteCond %{REMOTE_HOST} www.example.com (the last two I found on this thread)

*update 2009-06-23 according to a post on a "simplywebhosting kb" , having Deny from none somewhere (this caused the problem to reappear for me one more time), apparently "none" is not a proper apache directive

*using %h in a LogFormat directive instead of %a (%h will give you the hostname, no matter what HostnameLookups says, %a will give you the IP address)

Do you need help locating your apache config (httpd.conf)?

A: you could use http://yslow.org/ to find out where the hang up is .... ether in network dns php or somewhere else


text:
Q: Implementing Ajax - Rails App I'm trying to implement ajax into when I favorite a place, but the reload/update of the section/ajax functionality doesn't work.  Only if I reload the page, then I see the action that has occurred.  Would appreciate any tips.
My favorite_places/show.html.erb

   <% if current_user %>
     <%- unless current_user.favorite_places.exists?(id: @place.id) -%>
       <%= link_to favorite_places_path(place_id: @place), remote: true,   method: :post do %>

       <% end %>
     <%- else -%>
       <%= link_to favorite_place_path(@place), remote: true,  method: :delete do %>

       <% end %>
     <% end %>
  <% end %>

My favorite_places_controller.rb
  def update
   @favorite_place.update_attributes[params[:place]]
    respond_to do |format|
      format.html { redirect_to @place }
      format.js
    end
   end

My update.js.erb
<%  if @place.favorited %>
   $(' #<%= @place.id %>').html("true");
   console.log ("<%= @place.name %> has been favorited.");
<% else %>
   $(' #<%= @place.id %>').html("false");
   console.log ("<%= @place.name %> is not a favorite.");
<% end %>

My dev console output
DELETE http://0.0.0.0:3000/favorite_places/34 406 (Not Acceptable)
 jquery.js?body=1:8716send
 jquery.js?body=1:8716jQuery.extend.ajax
 jquery.js?body=1:8146$.rails.rails.ajax
 jquery_ujs.js?body=1:73$.rails.rails.handleRemote
 jquery_ujs.js?body=1:149(anonymous function)
 jquery_ujs.js?body=1:299jQuery.event.dispatch
 jquery.js?body=1:5108elemData.handle


text:
Q: How to crawl links with scrapy only from specific category, and ignore links on product page? I want to crawl products from a category but I don't want the spider to follow the links found on the product page itself (related products are from the same brand but of different type - eg. the product I want is a perfume and it has as a related product a lipstick) .
The url for the category is site.com/category_name/ and the product url is site.com/brand_name/product-name-here/. How should I define the crawling rules?

A: You can use rules to define this kind of behavior.
Rule(LinkExtractor(allow=('.*site.com/category_pattern.*',)),
callback='your_callback', follow=False)

This will crawl category pages with your callback, that will follow links to product pages and nothing from there. You just need some pattern for identifying category part of the url.


text:
Q: status bar and navigation bar becomes visible in immersive mode when searching in listview from the toolbar search I have an activity where the theme is set to
    Theme.AppCompat.Light.NoActionBar.
And i have used toolbar search for searching a listview.
But when i start writing something in the toolbar search area the status bar and navigation bar become visible.
What i want to do is to search the list but the status bar on the top should stay hidden.
check out the pics where the status bar overlaps the toolbar..normal view, when writing something in search bar
This is the layout for the activity with a toolbar and a list view

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:id="@+id/toolbar"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"/>
<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/list"></ListView>
</LinearLayout>

This is the menu item for searching
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="schemas.android.com/tools"
tools:context="com.example.sample.YourActivity" xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/search"
    android:title="@string/search_title"
    android:icon="@drawable/ic_action_action_search"
    app:showAsAction="collapseActionView|ifRoom"

    app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

Searchable layout
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_label"
    android:hint="search it">
</searchable>

search bar implementation in onCreateOptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);

    SearchManager searchManager = (SearchManager) getSystemService(getApplicationContext().SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();

    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false);

    SearchView.OnQueryTextListener textChangeListner = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            adapter.getFilter().filter(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String query) {
            adapter.getFilter().filter(query);
            return false;
        }
    };
    searchView.setOnQueryTextListener(textChangeListner);

    return super.onCreateOptionsMenu(menu);
}


text:
Q: Base Entity and Serializable Can I create something like
@Getter
@Setter
@MappedSuperclass
public class BaseEntity  implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
}

And use it in children class?
Is it ok use one serialVersionUID for all children entities?

A: Eclipse advices to declare new serialVersionUID for my Contract entity extended from BaseEntity with serialVersionUID.
So i think it will be good if you declare it for all child entities.

by the way you can use same serialVersionUID for all your classes.
additionally good writing about serialVersionUID
http://javabeginnerstutorial.com/core-java-tutorial/use-serialversionuid/


text:
Q: User input list,then adding the numbers to calculate ISBN check digit print("""Hi, and welcome to \"GENERATE A CHECK DIGIT \" """)

num1 =input("Enter a 12 digit ISBN number and I will output your check digit:  ")
oddTotal=int(num1[0])+int(num1[2])+int(num1[4])+int(num1[6])+int(num1[8])+int(num1[10])
evenTotal=int(num1[1])+int(num1[3])+int(num1[5])+int(num1[7])+int(num1[9])+int(num1[11])
Total=oddTotal+(evenTotal*3)
checkDigit=10-(Total%10)

print("For the given ISBN: "  + str(num1)+ " The Check digit should be: " + str(checkDigit))
print("Complete ISBN 13 CODE = " +str(num1)+str(checkDigit))

My question: I have added "int" before every single list item but found this to be a bit tedious. I tried putting it at the beginning before the main bracket but it didn't work.
Is there a way of improving this code.

A: You can use sum with map and string slicing:
num1 = input("Enter a 12 digit ISBN number and I will output your check digit:  ")
oddTotal = sum(map(int, num1[::2]))
evenTotal = sum(map(int, num1[1::2]))

The syntax for string slicing is similar to list slicing, i.e. the format is start:end:step.

A: You could use a list comprehension to convert all elements of your string num1to integers, and then use list slicing to calculate both sums:
num1 = input("Enter a 12 digit ISBN number and I will output your check digit:  ")
nums = [int(num) for num in num1]
oddTotal = sum(nums[::2])
evenTotal= sum(nums[1::2])


text:
Q: How to shut down Lubuntu immediately with the power button instead of a logout method dialog prompt I would like the computer to shut down directly after I press the power button. At the moment, Lubuntu opens a shutdown method dialog box when I press the shutdown button.
I suspect I can simply modify the Lubuntu-rc.xml file in the .config/openbox/ folder. I used that file to easily change other shortcut keys. If this is the case, I believe I have found the proper line of code where the shutdown command should be. But when I enter the command "sudo shutdown - now" in the appropriate place, it doesn't work. Is there another command I should enter for the physical power button to shutdown the computer immediately?
`<!-- Launch logout when push on the shutdown button -->
<keybind key="XF86PowerOff">
  <action name="Execute">
    <command>lxsession-default quit</command>
  </action>
</keybind>`

A: This is a configurable option in the XFCE Power Manager, which was installed by default in my relatively fresh Lubuntu 14.04.1 installation (a laptop). I found it at Preferences > Power Manager. If it's not installed already for you, you should be able to install it with sudo apt-get install xfce4-power-manager
In "General Options", you'll want to select "When power button is pressed: Shutdown" (default setting is "Ask" - which brings up the popup menu you want to skip). See the starred line in the image below.

I needed to log out of Lubuntu and log back in for this setting to take effect, but after that, one press of the power button shut down my system.
Hope this works for you!

A: Please try this.  It works in Ubuntu and may work in Lubuntu:

Tap the power button then press the enter key.

I'm always surprised when seasoned ubuntu users don't seem to know that this easy trick which can performed as swiftly as half a second shuts down the computer properly and fastest of all.  Like I said, it might not work in Lubuntu but you can at least try.

A: See following bug with the same problem description:
https://bugs.launchpad.net/ubuntu/+source/lubuntu-default-settings/+bug/1319134
Workaroud: in /etc/acpi/powerbtn.sh, delete all but the last line:
/sbin/shutdown -h now "Power button pressed"
Maybe your system has exactly the same problem and this workaround will also work for you.

A: In the terminal type
sudo apt-get install acpid

Now reboot a few times. Worked for me.
This took me 3 days of study.


text:
Q: Integration of Erf function Let $f(x) = \int^\sqrt{x}_1 e^{-t^2}dt$. Find $\int^1_0 \frac{f(x)}{
\sqrt{x}}dx$.
Could anyone give me any hint how to start? The Erf function $f(x)$ seems not to be easily integrated.

A: You want to find
$$\int_0^1\frac{\int_1^{\sqrt{x}}e^{-t^2}dt}{\sqrt{x}}dx=\int_0^1\frac{f(x)}{\sqrt{x}}dx$$
This should SCREAM integration by parts, as we somehow want to differentiate the numerator. Let's try it. We note that $u' = \frac{e^{-x}}{2\sqrt{x}}$ and $v=2\sqrt{x}$
$$=2\sqrt{x}f(x)\bigg|_0^1 -\int_0^1 \frac{e^{-x}2\sqrt{x}}{2\sqrt{x}}$$
$$=2f(1) -\int_0^1 \frac{e^{-x}2\sqrt{x}}{2\sqrt{x}}$$
$$=\left(2\int_1^{1}e^{-t^2}dt\right) -\int_0^1 e^{-x}$$
$$=\frac{1}{e}-1$$

A: Brevan Ellefsen's solution is the most straightforward and efficient. Here is an alternative solution.
\begin{equation}
f(x) = \int\limits_{1}^{\sqrt{x}} \mathrm{e}^{-t^{2}} dt
\label{eq:161108-1}
\tag{1}
\end{equation}
\begin{equation}
\int\limits_{0}^{1} \frac{f(x)}{\sqrt{x}} dx
\label{eq:161108-2}
\tag{2}
\end{equation}
We need the following result
\begin{equation}
\int \mathrm{erf}(x) dx = x\,\mathrm{erf}(x) + \frac{\mathrm{e}^{-x^{2}}}{\sqrt{\pi}}
\label{eq:161108-3}
\tag{3}
\end{equation}
Proof: Integrate by parts
\begin{align}
\int \mathrm{erf}(x) dx &= x\,\mathrm{erf}(x) -\frac{2}{\sqrt{\pi}} \int x\,\mathrm{e}^{-x^{2}} dx \\
&= x\,\mathrm{erf}(x) + \frac{\mathrm{e}^{-x^{2}}}{\sqrt{\pi}}
\end{align}
we used the substitution $u=x^{2}$.
Now we evaluate equation \eqref{eq:161108-1}
\begin{equation}
f(x) = \frac{\sqrt{\pi}}{2} \mathrm{erf}(x) \Big|_{1}^{\sqrt{x}} = \frac{\sqrt{\pi}}{2} [\mathrm{erf}(\sqrt{x}) - \mathrm{erf}(1)]
\label{eq:161108-4}
\tag{4}
\end{equation}
Substitute equation \eqref{eq:161108-4} into equation \eqref{eq:161108-2} and evaluate the following two integrals.
\begin{align}
I_{1} &= \int\limits_{0}^{1} \frac{\mathrm{erf}(\sqrt{x})}{\sqrt{x}} dx \\
&= 2\int\limits_{0}^{1} \mathrm{erf}(z) dz \\
&= 2\,\mathrm{erf}(1) + \frac{2}{\mathrm{e}\sqrt{\pi}} - \frac{2}{\sqrt{\pi}}
\end{align}
we used the substitution $z=\sqrt{x}$.
\begin{equation}
I_{2} = \int\limits_{0}^{1} \frac{1}{\sqrt{x}} dx = 2
\end{equation}
Putting all of the pieces together yields our final result
\begin{align}
\int\limits_{0}^{1} \frac{f(x)}{\sqrt{x}} dx
&= \frac{\sqrt{\pi}}{2} \left(2\,\mathrm{erf}(1) + \frac{2}{\mathrm{e}\sqrt{\pi}} - \frac{2}{\sqrt{\pi}} - 2\,\mathrm{erf}(1) \right) \\
&= \frac{1}{\mathrm{e}} - 1
\end{align}


text:
Q: Instruments profiling: "top functions" reorders functions I have optimized a function Render() by changing OpenGL code. I have then run Instruments / Time Profile with time limit 180 sec (so the measure was done accurately).

*

*Turn on Invert Call Tree:

*

*680 ms for non-optimized,

*500 ms for optimized.

*Turn off Invert Call Tree:

*

*277 ms for non-optimized,

*345 ms for optimized.

*Turn on Top Functions (still turn off Invert Call Tree):

*

*4591 ms for non-optimized,

*5277 ms for optimized.

*Turn on Invert Call Tree (still turn on Top Functions):

*

*no changes (4591),

*no changes (5277).

How to interpret this? Is the optimized version faster or slower?

A: The Time Profiler results depend on the version of Xcode you're running. If you are running Xcode 4.4 or later, the Time Profiler instrument has two columns for each symbol in the call tree: Running Time and Self. The Self column is more important because it tells you the amount of time the function was at the top of the call stack. All the Running Time column tells you is how much time the function was on the call stack, which doesn't really mean as much as being at the top of the stack.
To see how much time your app spent in Render(), deselect the Invert Call Tree checkbox and look at the Self column for Render(). If this is a game you're profiling, what can help is to double-click your game loop function in the call tree. Double-clicking the game loop function opens the source view, which will tell you the percentage of time your game loop spends in the Render() function.
The Time Profiler instrument isn't the best tool for profiling OpenGL code. If you're writing a Mac app, the OpenGL Profiler tool profiles OpenGL code better than Instruments. Instruments also has an OpenGL Driver instrument for measuring OpenGL statistics. If you're profiling an iOS app, use the OpenGL ES Analysis Instruments template and the OpenGL ES Performance Detective tool.


text: Q: Ubuntu desktop right-click menu Where is the code that controls the right-click menu system? I understand that I can add menu items by editing .desktop files, but I would be interested to modify the system itself. My feeling is that the desktop shortcuts should be implemented as shell (eg bash) functions, so I want to find out what would be involved in implementing that.


text:
Q: fullcalendar viewdisplay alternative function I want upgrade my full calendar to latest version. all working But some data I am fetching from database using php. some functions are creates problems like view display function.
Please check below code.
    viewDisplay: function(view) {
        if (view.name != lastView )
        {
            if (view.name == 'month')
            {
                    $('#meetings').fullCalendar( 'removeEventSource', '/meetings/meetinglistdays/my').fullCalendar( 'refetchEvents' );
                    $('#meetings').fullCalendar( 'addEventSource', '/meetings/meetingslistmonth/my');
            }
            else
            {
                $('#meetings').fullCalendar( 'removeEventSource', '/meetings/meetinglistdays/my' );
                $('#meetings').fullCalendar( 'removeEventSource', '/meetings/meetingslistmonth/my' ).fullCalendar( 'refetchEvents' );
                $('#meetings').fullCalendar( 'addEventSource', '/meetings/meetinglistdays/my' );
            }
            lastView = view.name;
        }

    },

A: I have faced a similar problem and the reason behind was Renamed/Removed functions  and viewDisplay option has been deprecated in favor of the viewRender callback.
Note: Before moving towards the migration you should try reading the migration docs click here for migration docs And the solution to your problem exist here at the very bottom inRenamed/Removed section.


text:
Q: YA book series about alien teenagers who (maybe) time travel on Earth Looking for the name of this book series from the 90s or early aughts, and I can't remember the title, the author, or any of the characters names.
What I can remember is that one of the girls had four arms, and on one of the covers she's dressed as a pirate, swinging on a rope.  I remember that much because she was my favorite.
I don't remember if they were actually time-traveling or if it was a holodeck kind of situation, or why they were learning about Earth (unless, of course, they were trapped there via a faulty time travel device)
The other thing I remember is that there were Os in the title, because they were saturns/ringed planets on the covers.
ETA: something I remembered this morning: the books came with a sheet of temporary tattoos in them, which was a new big thing at the time.

A: I've been looking for that book series as well, and I finally found it! I think the specific book you're thinking of is All Hands On Deck, part of the Goners series by Jamie Simons and E.W. Scollon

The cosmic rescue team of Xela and Arms Akimbo, searching for a Goner among the sailing ships of the Canary Islands in 1492, find themselves aboard the Santa Maria and pursue suspicions surrounding Christopher Columbus. Original.


text:
Q: How do you format code in Sublime Text editor 3 How I can format, or beautify php,html,css,javascript code in the Sublime 3 Text editor?
When I go into Edit menu of Sublime 3 there is no option for formatting or beautifying code!

A: First, install Package Control, the package manager for Sublime Text. Next, you need to install packages that do what you're after: beautify code or maybe just indent it.


text:
Q: Airflow:SnowflakeOperator:Last query id returned to XCOM I have a snowflake file with a query like as below, in the snowflake operator if I have a return so that I can pass xcom to the next task.
How can I get only the last query id to be returned for xcom ? Basically I need to get the snowflake last query id to xcom
In SQL File:
select columns from tableA ;
select last_query_id();

Error : Multiple SQL statements in a single API call are not supported; use one API call per statement instead.
or is there a way I can get below query id returned to xcom

Code:
  class LastQueryId(SnowflakeOperator):

    def execute(self, context: Any) -> None:
        """Run query on snowflake"""
        self.log.info('Executing: %s', self.sql)
        hook = SnowflakeHook(snowflake_conn_id=self.snowflake_conn_id,
                             warehouse=self.warehouse, database=self.database,
                             role=self.role, schema=self.schema, authenticator=self.authenticator)
        result = hook.run(self.sql, autocommit=self.autocommit, parameters=self.parameters)
        self.query_ids = hook.query_ids

        if self.do_xcom_push and len(self.query_ids) > 0:
            return self.query_ids[-1]

UPDATED: I was able to get the query id of the snowflake  with above code  but in the log, I also see the result of the query, how can I avoid those in the log

[2022-06-23, 20:43:39 UTC] {cursor.py:696} INFO - query: [SELECT  modifieddate, documentdate...]
[2022-06-23, 20:43:40 UTC] {cursor.py:720} INFO - query execution done
[2022-06-23, 20:43:56 UTC] {snowflake.py:307} INFO - Statement execution info - {'MODIFIEDDATE': datetime.datetime(2022, 6, 23, 11, 42, 34, 233000), 'DOCUMENTDATE': datetime.datetime(2015, 10, 1, 0, 0)...}
[2022-06-23, 20:43:56 UTC] {snowflake.py:307} INFO - Statement execution info - {'MODIFIEDDATE': datetime.datetime(2022, 6, 23, 13, 50, 45, 377000), 'DOCUMENTDATE': datetime.datetime(2021, 7, 1, 0, 0)...}
[2022-06-23, 20:43:56 UTC] {snowflake.py:307} INFO - Statement execution info - {'MODIFIEDDATE': datetime.datetime(2022, 6, 23, 11, 36, 51, 583000), 'DOCUMENTDATE': datetime.datetime(2015, 8, 31, 0, 0)...}
....
....
....
[2022-06-23, 20:43:56 UTC] {snowflake.py:311} INFO - Rows affected: 22116
[2022-06-23, 20:43:56 UTC] {snowflake.py:312} INFO - Snowflake query id: 01a5259b-0501-98f3-0251-830144baa623
[2022-06-23, 20:43:56 UTC] {connection.py:509} INFO - closed

A: SnowflakeOperator already store the query_ids but it does not push them to xcom.
You can create a custom operator as:
class MySnowflakeOperator(SnowflakeOperator):

    def execute(self, context: Any) -> None:
        """Run query on snowflake"""
        self.log.info('Executing: %s', self.sql)
        hook = self.get_db_hook()
        execution_info = hook.run(self.sql, autocommit=self.autocommit, parameters=self.parameters)
        self.query_ids = hook.query_ids

        if self.do_xcom_push and len(self.query_ids) > 0:
            return self.query_ids[-1]  # last query_id

If you want to maintain the original operator functionality then you can do:
class MySnowflakeOperator(SnowflakeOperator):

    def execute(self, context: Any) -> None:
        parent_return_value = super().execute(context)
        if self.do_xcom_push and len(self.query_ids) > 0:
            self.xcom_push(
                context,
                key="last_query_id",
                value=self.query_ids[-1],
            )
        return parent_return_value


text:
Q: SQL Current and Future Dates I have an Events table and have found a solution for selecting all Current events and Upcoming events (within the next 14 days).
I'm just wondering if there is a better solution than using the OR in the WHERE statement.
This solution makes me feel like a crappy programmer.
SELECT
   eventID
  ,eventTitle
  ,eventStartDate
  ,eventFinishDate
FROM Events
WHERE eventStartDate <= GETDATE() AND eventFinishDate >= GETDATE()
OR eventStartDate >= GETDATE() AND DATEDIFF(DAY,GETDATE(),eventStartDate) <= 14
ORDER BY eventStartDate

Your wisdom is greatly appreciated!
Thanks much

A: Assuming eventStartDate <= eventFinishDate, you could just say it has to start before 2 weeks from now, and end after today:
where   eventStartDate <= dateadd(week, 2, getdate())
        and getdate() <= eventFinishDate

A: You probably need something like:
SELECT
   eventID
  ,eventTitle
  ,eventStartDate
  ,eventFinishDate
FROM Events
WHERE GETDATE() BETWEEN eventStartDate AND eventFinishDate
OR eventStartDate BETWEEN GETDATE() AND DATEADD(DAY, 14, GETDATE())
ORDER BY eventStartDate

By the way, always take care when using OR operators to specify exactly what you need using parenthesis. Your code example might fail because of this. If you were getting wrong results, you should try:
SELECT
   eventID
  ,eventTitle
  ,eventStartDate
  ,eventFinishDate
FROM Events
WHERE (eventStartDate <= GETDATE() AND eventFinishDate >= GETDATE())
OR (eventStartDate >= GETDATE() AND DATEDIFF(DAY,GETDATE(),eventStartDate) <= 14)
ORDER BY eventStartDate

In my code this it not needed because it's not a complex expression, there's just one OR.


text:
Q: PIC 18F46K22, MikroC: 'Multitasking' simple and time consuming task I'm receiving a UART message containing an array of raw sensor data. I'm reading the message within the main loop of the program. There are 2 things I need the PIC to do with the different values. Display it on a LCD (somewhat time consuming) and, atleast for one of the values, change a LED-bar connected to PORTD accordingly to the value (rather simple).
In the main loop this is my current way of working:

*

*Request sensor data from external device on UART

*Receive bytes array from external device

*Do calculation to convert raw sensor data to actual values/units

*Display RPM value on LCD-bar using this code:
 if (RPM < 99)
 {
   PORTD = 0;
 }

 if (RPM > 100)
 {
   PORTD = 0x01;
 }

 if (RPM > 2400)
 {
   PORTD = 0x03;
 }

 if (RPM > 3700)
 {
   PORTD = 0x07;
 }

 if (RPM > 4900)
 {
   PORTD = 0x0F;
 }

 if (RPM > 6200)
 {
   PORTD = 0x1F;
 }

 if (RPM > 7400)
 {
   PORTD = 0x3F;
 }

 if (RPM > 8700)
 {
   PORTD = 0x7F;
 }

 if (RPM > 10000)
 {
   PORTD = 0xFF;
 }

*Finally displaying multiple values on a LCD. Thus removing old value, drawing the label, set new value, again draw the label.
That last task slows the whole loop down, which is making the LED-bar function to 'laggy'.
I got the suggestion to check if the value(s) have changed before redrawing the labels, to avoid unnecessary drawing. But all the values are rather rapid changing values like RPM and such.
Any suggestion would be welcome!!

A: Data going to an display does not need to change faster than the viewer can sense.  If your changes are greater than a threshold (40 to 100 Hz), then only use the last change that occurred in the previous period.
int UpdateValue;
int UpdateNeeded = 0;

void TimerServiceRountine() { // called at N (60) Hz.
  if (UpdateNeeded) {
    UpdateNeeded = 0;
    UpdateLCD(UpdateValue);
  }
  // ...
}

// Call this with each RPM
void UpdateDisplay(int Value) {
  UpdateValue = Value;
  UpdateNeeded = 1;
}

Further refinement: Only call UpdateLCD(x) if x is different from before.

A: Solution idea #1
My guess is that the slowness of the LCD part is due to that you need to wait for the LCD to process the commands sent to it (common with certain alphanumeric LCDs).
Your main loop otherwise could probably do several thousand cycles a second.
If this is the case, then you should implement a state machine for the LCD output in the main loop. This state machine would clock out the necessary commands to the LCD for updating the display, one by one, once in each run of the main loop, only if the LCD is ready to accept the new command.
This way your main loop can run free of waiting for the LCD, while the LCD also gets updated sufficiently fast (depending on whether the turnaround time of the main loop without the LCD task would be sufficiently low: optimally less than the typical "busy" time of the LCD).
Solution idea #2
This is more complicated and applies if the LCD process is rather calculation heavy for some reason (pixel by pixel work on a graphic LCD?).
Even this case a similar approach to Solution #1 may work well. If you can split up the LCD task to smaller chunks with roughly similar processing time requirements, you may speed up the main loop (by only processing one chunk of these at once).
If you rather would prefer a more accurate timing for the main task, then the main task needs to be put in an interrupt (Assuming that you request the data from your sensor, you need a timer IT to time these requests). The main loop then would only work with the LCD.
Common elements
In all cases you do more samplings while a single fragmented LCD display data construction processes. This needs some data management: You have to "sample" (mostly copy away, interrupts disabled in the case of the last solution) your data going onto the LCD before starting building the display.
All the solutions I presented are "ideal" in that sense they could "automatically" pull out the most (in the term of display update frequency) from your hardware using all cycles available. You only need to select the appropriate method for your situation.


text:
Q: Restrict command in powershell session but allow access to a cmdlet that calls it? I have a bunch of PowerShell scripts that call out to external programs to perform certain actions (no choice about this). I'm trying to find a way to allow users to connect to a constrained remote session using delegation to run these scripts (and the external binaries) as a privileged account, WITHOUT the user being able to execute the binaries with the privileged account.
I've found that if I constrain the endpoint using NoLanguage and RestrictedRemoteSession, or using a startup script to remove access to those parts of the system that it breaks the scripts because they're no longer able to execute the binaries.
Is there any possibility of making this work, or will I have to rewrite my existing scripts as DLL cmdlets which could then make the calls to the external binaries (or write just a proxy command in a DLL to make the calls)?

A: Create scheduled tasks without a trigger, configure them to run as a privileged user, and have your restricted users start them from the Task Scheduler.

A: You are looking for JEA or Just Enough Admin. It does exactly what you are trying to do with restricted endpoints.
http://blogs.technet.com/b/privatecloud/archive/2014/05/14/just-enough-administration-step-by-step.aspx
Start with the video. Jeffery Snover may give you the details needed to make your solution work as he explains step by step how JEA was built.


text:
Q: How should you handle reviews when out of flags? Today I was handed an audit which was obviously junk that needs to be deleted. However, I was out of flags for the day and clicked "Needs Editing" instead. What is the proper thing to do in this case? Skip it or stop reviewing until I have more flags?

A: My mother used to say, "If you can't say something nice, don't say anything at all." Same thing applies here.
Never do something wrong just because you can't do it right.
This applies to reviews, to commenting ("I would comment, but I don't have the rep"), to sockpuppets ("I had to make a new account because the old one got blocked from asking questions"), etc, etc, etc. If you know the correct action in review, but you can't take it, either Skip (if you're likely to be able to handle at least some other reviews correctly, such as in First Posts where running out of flags doesn't necessarily happen at the same time you run out of votes) or, yes, stop reviewing. Or sometimes you can add a comment to let others know what you think about it, then Skip.
This is especially true of blatant spam; there's no reason to allow that through, and hitting Needs Editing leaves it on the site longer and requires more people to handle it. (Worst case, since this is Triage, it would pass it to the Help & Improvement queue.)


text:
Q: does documents directory order files? IOS I am saving many different images to the documents directory in this way:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

int num = arc4random() % 100000000000000;

NSString* path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"%dtest.png", num]];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];

Then I read the files in this way:
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES)objectAtIndex:0];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//NSString* FinalPath = [documentsDirectory stringByAppendingPathComponent: @"Images/"];

NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:&error];

for(int i=0;i<[filePathsArray count];i++)
{
    NSString *strFilePath = [filePathsArray objectAtIndex:i];
    if ([[strFilePath pathExtension] isEqualToString:@"jpg"] || [[strFilePath pathExtension] isEqualToString:@"png"] || [[strFilePath pathExtension] isEqualToString:@"PNG"])
    {
        NSString *imagePath = [[stringPath stringByAppendingFormat:@"/"] stringByAppendingFormat:strFilePath];
        NSData *data = [NSData dataWithContentsOfFile:imagePath];
        if(data)
        {

            @try {

               NSString *nameOfGroup = [array objectAtIndex:i];

                MWPhoto *photo;
                photo= [MWPhoto photoWithFilePath:imagePath];
                [finalPhotoArray addObject:photo];
            }
            @catch (NSException *exception) {

                NSString *nameOfGroup = @"No description available for this sheet";

                MWPhoto *photo;
                photo= [MWPhoto photoWithFilePath:imagePath];
                [finalPhotoArray addObject:photo];

            }

        }
    }

The problem is the images are not ordered correctly, in the order I save the files in, but they are mixed up. Is there a way to order them? when I save to the documents directory, are the files mixed up?

A: For contentsOfDirectoryAtPath:error: (which is the non-recursive equivalent of subpathsOfDirectoryAtPath:error:) the documentation says:

The order of the files in the returned array is undefined.

If you want to associate image paths with captions you should store that association somewhere. If you are storing your captions in an NSArray of NSStrings you could instead store them in an NSArray of NSDictionaries. Each dictionary has a key @"imagePath" and @"caption".
Also, when dealing with NSStrings representing paths you should use the method listed under Working with Paths in the documentation. (e.g. stringByAppendingPathComponent: instead of stringByAppendingFormat:)