text:
Q: How to get rid of route-name conflicts when ensuring api works both with and without the api-version? I want to apply asp.net api-versioning to my web app (which didn't have versioning). However, the tricky issue is that I must ensure that APIs should work both with and without the api-version.
    [ApiVersion("1.0")]
    [Route("api/products/{productId}/[controller]")]
    [Route("api/v{version:apiVersion}/products/{productId}/[controller]")]
    [ValidateModel]
    [Produces("application/json")]
    public partial class ProductController : ControllerBase {

        internal const string GetLatestRoute = "GET Product/GetLatestAsync";

        [HttpGet(Name = GetLatestRoute)]
        public async Task<IActionResult> GetLatestAsync() {

        }
    }

I have a controller with multiple actions, each of them is defined with a unique route name. When I add two routes (with and without versions) to the controller, there comes a route-name conflict error:

Attribute routes with the same name 'GET Products/GetLatestAsync' must have the same template:
Action: 'Service.Controllers.ProductController.GetLatestAsync (ProductFD)' - Template: 'api/products/{productId}/Product'
Action: 'Service.Controllers.ProductController.GetLatestAsync (ProductFD)' - Template: 'api/v{version:apiVersion}/products/{productId}/Product'

There are several answers on StackOverflow that say the issue can be solved by removing the route names defined for the action methods. However, in my scenario, the route names are used to create Url Links in several places in the project.
Is there an approach that I can get rid of the issue? I'm wondering whether I could append version to the route name variable or mapping the non-version api to the version/1.0 ...? On the other hand, there is a rare case that I update all the methods in a controller. So is it possible that I only define a route-prefix on the top-level of the controller and only apply the api-version on the method-level?

A: Route names and the route table are not API version aware. In order for this to work, you need to use double route registration like you have because you are versioning by URL segment (not recommended). If clients are properly following the links returned by the server, then always using the route generated with the explicit version in it will do. If the client doesn't honor that and just calls the APIs directly without the API version, the second template will handle that for you. If you are only generating links with the same controller, then I would suggest using CreatedAtAction instead because it will not rely on the route name. If memory serves me correct, you can specify the order of each [Route] for precedence. If unspecified, it will be the first attribute specified - which matters.
You'll also need to enable:
services.AddApiVersioning(options => options.AssumeDefaultVersionWhenUnspecified = true);

If you haven't already.
Last, but not least, beware the known, breaking change: Async suffix trimmed from controller action names. This has snared many people.


text:
Q: Automatically set Teams status I'd like my Microsoft Teams status to automatically be set to Be Right Back when I lock my PC and to Available when I unlock my PC. Is this possible?
I have:

*

*Looked into whether there are any relevant CLI switches / options that I can plug in to by Googling it, running teams.exe -? and teams.exe /?, and running Strings on teams.exe but it seems that there is not.

*Used Process Monitor / procmon to trace the activity when statuses are changed but found nothing useful. The only notable thing I found was the following entry in the file %appData%\Microsoft\Teams\logs.txt but it didn't lead me to anything useful:
Fri Jul 03 2020 13:23:17 GMT+0100 (British Summer Time) <3292> -- event -- panelaction: Action.Outcome: setpresence, DataBag.PresenceState: beRightBack, Action.Gesture: click, Action.Scenario: setPresenceFromTrayMenu, Action.ScenarioType: other, ppChannel: Production::CC, distSrc: PROPLUS_O365BusinessRetail, ppInstallMode: UPDATE, autoStartPolicy: undefined, vdiMode: 0, eventpdclevel: 2,

*Looked into using an AutoHotkey mouse macro but I haven't really pursued this because I'm hoping for a better solution, I'm unsure whether it'd work on lock and unlock, and it's a bit tricky because the statuses are only accessible by hovering over the System Tray or in-app context menu item first.

A: When locking and unlocking my Windows session, Teams takes a second or two to update its icon and, in that time, I've noticed that it automatically sets its status to away and back which is good enough for me.

If anyone else manages to come up with a way of programmatically controlling Teams statuses then I'll change the accepted answer to theirs.

A:
Note: If you have the ability to register an Azure connected app with your organization (and receive a client ID/client secret), see Đrakenus's answer, which would be more appropriate.

I've created something that works for me, but it's a hack, so please forgive me in advance. Desperate times call for desperate measures...
I used Java's java.awt.Robot to manually click the status to be changed in Teams.
Here's an example:
import java.awt.*;
import java.awt.event.InputEvent;
import java.io.IOException;

public class StatusChanger {

    private static final int waitBetweenSteps = 300;
    private static Robot robot;

    public static void main(String[] args) throws IOException, InterruptedException, AWTException {
        robot = new Robot();

        // Get the status from the first arg to the program, options are
        // away, available, busy, or offline.
        final String status = args[0];

        // This will bring the Teams window into focus on macOS, there is likely
        // a similar solution for Windows.
        runCommand(new String[]{"osascript", "-e", "tell application \"System Events\" to tell process \"Microsoft Teams\" to set frontmost to true"});

        // Move mouse to the profile icon in the top left of the Teams window
        // and click the icon.
        mouseMove(3760, 50);
        click();

        // Move to the status in the modal that appears and click the status.
        mouseMove(3570, 140);
        click();

        // Move the mouse to the correct status position based on the argument.
        switch (status) {
            case "away":
                mouseMove(3600, 315);
                break;
            case "busy":
                mouseMove(3600, 220);
                break;
            case "available":
                mouseMove(3600, 180);
                break;
            case "offline":
                mouseMove(3600, 360);
                break;
        }
        // Click the new status.
        click();
        System.out.println("Status was set to " + status);
    }

    private static void runCommand(String[] command) throws IOException, InterruptedException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        process.waitFor();
        Thread.sleep(waitBetweenSteps);
    }

    private static void click() throws InterruptedException {
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        Thread.sleep(waitBetweenSteps);
    }

    private static void mouseMove(int x, int y) throws InterruptedException {
        robot.mouseMove(x, y);
        Thread.sleep(waitBetweenSteps);
    }
}

Then I build this into a jar (you could also just compile the class with javac) and run the command like:
# Set status to Away
java -jar TeamsStatusChanger.jar away

# Set status to Busy
java -jar TeamsStatusChanger.jar busy

# Set status to Available
java -jar TeamsStatusChanger.jar away

# Set status to Offline
java -jar TeamsStatusChanger.jar offline

You can then use cron to set your status automatically during specific timeframes:
# set Teams status to offline at 5pm
0 17 * * * java -jar /path/to/TeamsStatusChanger.jar offline

There are a few caveats:

*

*It requires you to keep Teams running, but could certainly be improved to check if Teams is running and start it/wait if it's not.

*It requires you to keep your Teams window in the same position (in my case, the top-right of the screen against the monitor's edge).

*The coordinates for this utility are hard-coded for my monitor size, which is 3840x1600. You will need to update the mouseMove calls with the proper coordinates of each "click" area (see next point).

*On macOS, you can use the screenshot tool to find the coordinates of each "click" area on your own monitor by pressing Cmd+Shift+4 and hovering over the area you want to click. The screen coordinates will be shown next to the crosshair.

*I'm not sure what this will do if you're using multiple monitors, it might require some additional tweaking or only work on your main monitor.

A: There is a way to programmatically set a MS Teams status, see
https://docs.microsoft.com/en-us/graph/api/presence-setpresence?view=graph-rest-beta&tabs=http
You can also combine it with Microsoft Teams Powershell module, there is a Connect-Teams cmdlet, see here - https://docs.microsoft.com/en-us/powershell/module/teams/connect-microsoftteams?view=teams-ps
However this might need additional setup -- you will probably need an Microsoft Graph API access via an Azure application (see https://docs.microsoft.com/en-us/powershell/module/teams/connect-microsoftteams?view=teams-ps#parameters), section about -AccessTokens parameter.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set background to views programmatically? I added a View to layout programmatically to draw a horizontal line.
Below is java code.
  // I want to add a view to ll
  LinearLayout ll = (LinearLayout)findViewById(R.id.main);

  LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
  View view = new View(this);
  ll.addView(view);
  view.setLayoutParams(params);

  // this method does not work.
  view.setBackgroundDrawable(getResources().getDrawable(R.drawable.division_line));

my division_line.xml in /drawable is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:color="#800400"
            android:width="2dp"/>
</shape>

I tried to apply division_line.xml to View but it doesn't work. What method should I use?

A: view.setBackground(getResources().getDrawable(R.drawable.division_line))
instead of
view.setBackgroundDrawable(...)
and keep in mind that first 2dp isn't much and you are adding a view with no layout properties so its size is 0px x 0px
you can do so in code:
view.setLayoutParams(new AbsListView.LayoutParams(300, 300));


text:
Q: Swift: Generics and type constraints, strange behavior I can't figure out how to perform a cast which would let me eventually to introduce some sort of dynamism working with generics.
Next piece of code does not compile. It shows this error:

Cannot invoke 'createContainer' with an argument list of type
  '(FooProtocol)' Expected an argument list of type '(T)'

protocol FooProtocol {
    func doSomething()
}

class Foo : FooProtocol {
    func doSomething() {}
}

class Container<T : FooProtocol> {
    let someDataConformingFooProtocol : T

    init(someDataConformingFooProtocol : T) {
        self.someDataConformingFooProtocol = someDataConformingFooProtocol
    }
}

class AllTogether {

    init () {
        createContainer(Foo()) //So far, so good

        let foo2Mask : AnyObject = Foo()
        if let foo2MaskChecked = foo2Mask as? FooProtocol {
            createContainer(foo2MaskChecked)
            //ERROR: Cannot invoke 'createContainer' with an argument list of type '(FooProtocol)'
            //Expected an argument list of type '(T)'
        }

    }

    func createContainer<T : FooProtocol>(data: T){
        Container<T>(someDataConformingFooProtocol: data)
    }
}

Is this really the expected behaviour? Because personally I can't understand what or why the compiler is complaining about it.
What would be the appropriate cast? Without referencing to the concrete class, I mean NOT like this:
if let foo2MaskChecked = foo2Mask as? Foo

Thanks!

A: What it comes down to is the difference between T: FooProtocol and FooProtocol as @Hamish mentioned in his comment.
When I have a function like this:
func foo(_ i: FooProtocol)

I'm taking in an instance of type FooProtocol, so I can pass in a value that conforms to FooProtocol or its type is FooProtocol. This is similar to subclassing where you can pass both SuperClass and SubClass into SuperClass.
But if you have a function like this:
func foo<T>(_ i: T) where T: FooProtocol

I can pass in any type that conforms to FooProtocol, but because FootProtocol does not conform to itself, you can't pass that in.
So in your question, you are trying to pass in a type FooProtocol where the types must conform to FooProtocol. You could probably fix this by doing:
class Container {
    let someDataConformingFooProtocol: FooProtocol

    init(someDataConformingFooProtocol: FooProtocol) {
        self.someDataConformingFooProtocol = someDataConformingFooProtocol
    }
}

// Later
func createContainer(data: FooProtocol){
    Container(someDataConformingFooProtocol: data)
}


text:
Q: Contador en SQL server quería consultarles sobre este error al contar registros.
Esta es la consulta:
SELECT COUNT(A.PTA, B.ORD)

FROM

CLIESO A ,

CLIORD B

WHERE  A.PTA = B.PTA

AND A.ORD = B.ORD

AND A.EST = 'PCRCOR'

AND B.FEC_ATE

BETWEEN (SELECT  DATEADD(MONTH, -1, DATEADD(day , 1 , EOMONTH(GETDATE()))))

AND (SELECT EOMONTH(GETDATE()))

y este es el error:

Mens. 8120, Nivel 16, Estado 1, Línea 1 Column 'CLIESO.PTA' is invalid
in the select list because it is not contained in either an aggregate
function or the GROUP BY clause.


text:
Q: How to remove .html from the Friendly URL - Modx? I'm using MODX Revolution 2.2.4-pl. I'm using the supplied .htaccess file and have friendly URLs turned on. These are my rewrite rules.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

What do they need to look like to have it remove the .HTML from the URL?
I've been googling this for the past twenty minutes and my solutions have not worked.
Thanks

A: There is a much easier built in way. Log in to the Manager.
MODX Revolution
2.2.x and earlier: Go to System -> Content Types.
2.3.x and later: Go to Content -> Content Types.
Find HTML and erase what is written in "File Extension". You do this by double clicking .html in the table to activate the editable field. After you have erased the content, clear cache.
MODX Evolution
Go to Tools -> Configuration -> Friendly URLs.
Delete the content in "Friendly URL Suffix". Save and clear cache.

A: This works for me:
# The Friendly URLs part
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

RewriteCond %{REQUEST_URI} \.html$
RewriteRule ^(.*)\.html$ $1 [R=301,L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
#RewriteRule . /index.php [L]

A: First, I think you need to understand what this .htaccess is trying to do.
It is trying to redirect all requests that come into the site that are not for an actual file or directory (i.e. images, css, or other scripts that might not be a part of the "main" website) to a front controller located at index.php.
If what you are trying to do is use a bunch of *.html files on your site (and not a front controller), but have them use clean URL's then you will need to use a different sort of rewrite.  Probably something more like
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [L,QSA]

This rule would take a request in the form of http://domain.com/somepage and have it silently point to http://domain.com/somepage.html to serve the request.


text:
Q: Merge multiple tabs (Column wise, not row by row) into a master sheet in google sheets I'm trying to merge the information stored in multiple tabs in one master sheet such that it'll look like "Final" in this sample sheet. I found a code online that does something similar but merge the information row-wise, which is not ideal in my case. The code looks like this:

function merge() {
  const ss = SpreadsheetApp.getActive();
  const arr = ss
    .getSheets()
    .filter(s => !s.getName().includes('Master'))//exclude Master sheet
    .flatMap(s => s.getDataRange().getValues());//map sheet to values and flatten it
  ss.getSheetByName('Master')
    .getRange(1, 1, arr.length, arr[0].length)
    .setValues(arr);
}

Please let me know if you have any suggestions. Thanks in advance.

A: Issue:
The values of each sheet are getting appended as successive rows in the target sheet. That's because the outer array corresponds to rows.
You should add the values of each sheet row to each inner array. That would correspond to columns.
Solution:
Transpose the array to make the columns correspond to the outer array, and then transpose back.
Also, since the first column in all sheets is the same, you only want to copy it for the first one, so you should check the index when using flatMap, and not retrieve the full range via getDataRange in these cases (use getRange instead).
Code sample:
function merge() {
  const ss = SpreadsheetApp.getActive();
  const excludedSheetNames = ['Master', 'Final']; // Add excluded sheet names
  let arr = ss
    .getSheets()
    .filter(s => !excludedSheetNames.includes(s.getName()); //exclude several sheets
    .flatMap((s, i) => {
      let values;
      if (i === 0) values = s.getDataRange().getValues();
      else values = s.getRange(1,2,s.getLastRow(),s.getLastColumn()-1).getValues(); // Ignore first column for non-first sheet
      values = values[0].map((_, colIndex) => values.map(row => row[colIndex])); // Transpose 2D array
      return values;
    });
  arr = arr[0].map((_, colIndex) => arr.map(row => row[colIndex])); // Transpose back
  ss.getSheetByName('Master')
    .getRange(1, 1, arr.length, arr[0].length)
    .setValues(arr);
}

Related:

*

*Transposing a 2D-array in JavaScript


text:
Q: Check if two lattices are isomorphic Given 2 lattices: $\Lambda_A$ and $\Lambda_B$, where A and B - the basis matrices of the equal dimension. How to check if these lattices are isomorphic?
As I understand, it's enough to show that A can be derived from B using translation, scaling and rotation, but how do I do that? Or is there a better way?
Thank you.

A: Showing that $A$ can be derived from $B$ using translation, scaling, and rotation is the same as showing that there exists is a matrix $M$ such that $A$ = $M^tBM$. You can do this brute-force, just checking matrices until you find one that works; more systematically and practically (by hand), write $A$ and $B$ as an augmented matrix and row reduce until $A$ is the identity matrix; then $M$ will be the $B$ side of the (reduced) augmented matrix.


text:
Q: How can I get the current playing time from an embedded video on a webpage? How can I get the current playing time from an embedded video on a webpage?  Is there simply an attribute that can be obtained using JavaScript from one of the common embedded video players?  Or do I need to do a work-around like make my own pause and play buttons and keep track of time manually while feeding the play/pause commands to the video using JavaScript?  The latter is much more ugly in my opinion.  Other solutions?

A: The html5 video tag provides some decent support for this kind of thing.
The following page gives some decent ideas:
http://www.broken-links.com/2009/10/06/building-html5-video-controls-with-javascript/


text:
Q: how to write query for split two rows? I have order table
OrderId OrderStatusId  CurrencyId      PromotionCode
------------------------------------------------------
  137         5           1             123a-123d
  138         5           1             123a-123d-234c

I want to split the PromotionCode column like this:
Result:
OrderId  OrderStatusId  CurrencyId  PromotionCode
-----------------------------------------------------
  137             5             1             123a
  137             5             1             123d
  138             5             1             123a
  138             5             1             123d
  138             5             1             234c

Please help me ...
is it possible to do... any way plz help me asas possible....

A: If the promotion codes are always 4 characters long, the simplest way is probably a union:
select  id, substring(code,1,4)
from    YourTable
where   LEN(code) >= 4
union all
select  id, substring(code,6,4)
from    YourTable
where   LEN(code) >= 9
union all
select  id, substring(code,11,4)
from    YourTable
where   LEN(code) >= 14
<etc>

For a more flexible solution, have a look at one of the various Split functions.  After creating this function in your database, you can invoke it like:
select  t.id, s.items
from    YourTable t
cross apply
        dbo.Split(t.code,'-') s

Both queries will produce the result as requested in your answer.


text:
Q: How to remove horizontal lines inside primefaces p:panelGrid I have lines horizontally inside the panel as you can see in screen shot.
Ideally I would like to have only the border which should show as a box and would like to remove the horizontal lines.
I have tried with
.ui-panelgrid tr
{
 border-width: 0px !important;
}

however this removes border completely.
How can I set the border as a box for the panel and no lines inside the panel?
Screen shot


text:
Q: Changing MBR code I have read that during the booting process in linux, BIOS loads MBR from the first sector of the bootable device.
Now, if I change the code  of size 446 Bytes in the first sector of the bootable device to some malicious code, or any other code, then will it get loaded as MBR? If yes, then what will happen if it gets executed? If no, why?

A: There have been MBR viruses since the times of MSDOS. It is nowadays that maybe they are less popular.
The reasons why MBR viruses have issues:

*

*446 bytes is not too big and you still need to store part of the code in files. You should be very careful about chaining your code and point to the original MBR or you'll render the computer kind of unbootable.

*Many antivirus have special code to prevent MBR modification.

*Some BIOS, specially newer computers with UEFI require digitally signed bootloader code.

Despite that I once made a custom simple MBR code to display a message and reboot, on machines which failed to boot through PXE.


text:
Q: how to create button hover effect like zbigz.com I tried to search about this effect in stackover flow, but I have no clue, what developers call this kind of hover effect also no idea to achieve it.

A: You can say that is box-shadow css property from css3 with inset applied:

div{
  width:200px;
  height:150px;
  background:#156a70;
  text-align:center;
  line-height:150px;
}
div:hover{
  box-shadow: inset 0px 0px 30px 5px rgba(135,255,249,1);
}

Hover me!!

A: Just right click the button -> inspect element
And see this css:
#input-file-wrapper {
    display: block;
    position: absolute;
    width: 180px;
    height: 30px;
    left: 50%;
    margin-left: -90px;
    top: 79px;
    cursor: pointer;
    background: url(https://zbigz.com/img/upload-torrent-file-btn.png) no-repeat;
    background-position: 0 -0;
}

#input-file-wrapper:hover {
    background-position: 0 -43px;
}

http://jsfiddle.net/7h4zns5m/
If you take a look at the image you see that there are 3 different buttons, they just change the background-position to have another button image. That way it looks like it pops out ;)


text:
Q: How to create repository for organization using github-api? I'm using github-api, an npm plugin, to create and manage repositories in node.js. I was able to create repositories for a user, and read a user's organizations, but I could not find out how to create a repository for an organization. I looked through the documentation but I am still confused as to how to create the repository.
Thanks in advance!

A: It seems that this client doesn't support repository creation for organizations. There is only createRepo for user.
The request for the user looks like:

POST /user/repos

and for the organization:

POST /orgs/:org/repos

where :org is the organisation name.


text:
Q: Is it normal to have a performance problem in Doctrine? Is it normal to have a performance problem in doctrine when working with insert or update of more than 2000 records? Should I turn to the PDO?

A: Yes. Doctrine is effective when you use bulk selects, but very bad if you use bulk update, insert or delete. Do not use doctrine for those operations use plain sql.
When you bulk insert for example, you create 2000 objects (poor server memory) and then doctrine insert it one by one if you do flush in a loop. Of course you can persist them for example with 200 object chunk and flush, but still memory usage will be a lot bigger than inserting via plain sql.
Even worse if you select 2000 records with doctrine then those records become not only entity objects, but they become persistent collection with a lot of other objects mapped to them and when you try to persist them server will use even more memory.


text:
Q: What's the best source-level debugger for ColdFusion MX 2004? I have a legacy web site in ColdFusion MX 2004.  I'm re-writing it in .Net, so I don't want to pay $600+ for an upgrade to the latest version of ColdFusion, nor do I want to go through the (very large) site fixing version incompatibilities.
I often have to track down and fix bugs in the site.
A source-level debugger that would let me step through the code line-by-line and examine variables would be a HUGE time-saver.
Does anyone have experience using any of the third-party ColdFusion source-level debuggers?

A: There's no such thing as ColdFusion MX 2004, neither in name nor release year (CFMX 6.1 was released in 2003, and CFMX 7 was released in 2005).
FusionDebug supports all versions of CFMX from 6.1 onwards.
You may want to investigate BlueDragon.NET, which allows you to run CFML code on the .NET platform, and may make the transition easier for you.

A: The developer versions of ColdFusion are free so you can install the latest version, install debugging tools into eclipse and run debugging for free.
The other option, if you prefer to debug on your target version of CF, is FusionDebug which supports CF 6.1 and up.

A: There are certain debuggers listed here on Charlie Arehart's site.
http://www.carehart.org/cf411/#debug
This CF411 site has a whole lot of great info on various subjects.

A: You don't seem to have marked this question as answered. The answers are offered by others, but to be clear:
If you're running a version of CF prior to CF 8, then you can get line debugging using the available commercial third-party tool, FusionDebug (www.fusiondebug.com).
If you're running CF 8, it includes line debugging, for free.
Both approaches leverage the Eclipse IDE's built-in debugging capability, hooking it up to CF.
For more on each, I've written several articles:
The ColdFusion 8 Debugger Explained: Interactive Step Debugging for CF 8
Using the CF8 Debugger
FusionDebug Explained: Interactive Step Debugging for CFML
FusionDebug Tips and Tricks
Hope those help.

A: BlueDragon.Net is interesting, but I installed it and found out that it does not do source-level debugging.


text:
Q: Infinite horizontal background ios using SKAaction I have a long image that I want to set as a "Rollable" background .
I'm trying to use 2 instance of the sprite and once the image reached to (frame - imageHeight) to add the second one above and to keep it with a smooth movement.
However, I'm getting an unexpected behaviour - at the last part of the animation the screen are overlapped - the second screen is overlapping the first one.
This is my code:
- (void) repositionBackground{

SKSpriteNode *currentBackground = self.backgroundArray[self.currentBackgoundIndex];
if(!currentBackground.parent && !self.currentBackgoundIndex) //First time running
{
    SKAction *imageMinusFrameAnimation = [SKAction moveToY:-currentBackground.size.height+self.frame.size.height/2.0f duration:self.backgroundAnimationLength];
    SKAction *sequence = [SKAction sequence:@[imageMinusFrameAnimation, [SKAction runBlock:^{
        [self repositionBackground];
    }]]];
    [currentBackground runAction:sequence];
    [self addChild:currentBackground];

    NSLog(@"Calling Reposition for the first time");
}
else
{
    self.currentBackgoundIndex = (self.currentBackgoundIndex + 1) % [self.backgroundArray count];
    SKSpriteNode *newBackground = self.backgroundArray[self.currentBackgoundIndex];
    //Reposition th enew backfround on top of the current one
    [newBackground setPosition:CGPointMake(0, self.frame.size.height/2.0f)];

    //Add actions to backfround - the top backgound to be vanished from the screen and the new one to appear and start scrolling down
    SKAction *imageMinusFrameAnimation = [SKAction moveToY:-currentBackground.size.height+self.frame.size.height/2.0f duration:self.backgroundAnimationLength];
    SKAction *sequence = [SKAction sequence:@[imageMinusFrameAnimation, [SKAction runBlock:^{
        [self repositionBackground];
    }]]];
    [newBackground runAction:sequence];

    if(!newBackground.parent)
    {
        [self addChild:newBackground];
    }
    float newBackgroundAnimationLength = self.frame.size.height / BACKGROUND_ANIMATION_VELOCITY;
    SKAction *frameLengthAnimation = [SKAction moveByX:0 y:-self.frame.size.height duration:newBackgroundAnimationLength];

    [currentBackground runAction:frameLengthAnimation];

}

}

A: I figure it out myself.
It was aa mistake in the algorithm.
I post here the solution: (SpriteKit)
//creating 2 background - positioning one above the screen and one to stand on the (0.5,0} axis
SKSpriteNode *firstBackground = [SKSpriteNode spriteNodeWithImageNamed:@"mtImage.jpeg"];
firstBackground.anchorPoint = CGPointMake(0.5f,0);
firstBackground.zPosition = 1;
SKSpriteNode *secondBackground =[firstBackground copy];
self.backgroundArray = @[firstBackground,secondBackground];
[firstBackground setPosition:CGPointMake(0, -self.frame.size.height/2)];
[secondBackground setPosition:CGPointMake(0, self.frame.size.height/2)];
self.currentBackgoundIndex = 0;
self.backgroundAnimationLength = firstBackground.size.height / BACKGROUND_ANIMATION_VELOCITY;

[self repositionBackground];

- (void) repositionBackground{

  SKSpriteNode *currentBackground = self.backgroundArray[self.currentBackgoundIndex];
  SKAction *majorPartAnimation;
  //First time running
  if(!currentBackground.parent && !self.currentBackgoundIndex)
  {
      float firstAnimationDuration = (currentBackground.size.height - self.frame.size.height) / BACKGROUND_ANIMATION_VELOCITY;
      majorPartAnimation = [SKAction moveToY:-currentBackground.size.height+self.frame.size.height/2.0f duration:firstAnimationDuration];
      SKAction *sequence = [SKAction sequence:@[majorPartAnimation, [SKAction runBlock:^{
        [self repositionBackground];
      }]]];
      [currentBackground runAction:sequence];
      [self addChild:currentBackground];
  }
  else
  {
      //current background needs to move by frameHeight and the new one has to be set above him and start its animation
      majorPartAnimation = [SKAction moveToY:-currentBackground.size.height+self.frame.size.height/2.0f duration:self.backgroundAnimationLength];
      self.currentBackgoundIndex = (self.currentBackgoundIndex + 1) % [self.backgroundArray count];
      SKSpriteNode *newBackground = self.backgroundArray[self.currentBackgoundIndex];
      //Reposition th enew backfround on top of the current one
      [newBackground setPosition:CGPointMake(0, self.frame.size.height/2.0f)];

      //Add actions to backfround - the top backgound to be vanished from the screen and the new one to appear and start scrolling down
      SKAction *sequence = [SKAction sequence:@[majorPartAnimation, [SKAction runBlock:^{
          [self repositionBackground];
      }]]];
      [newBackground runAction:sequence];
      if(!newBackground.parent)
      {
          [self addChild:newBackground];
      }
      float currentBackgroundAnimationLength = self.frame.size.height / BACKGROUND_ANIMATION_VELOCITY;
      SKAction *minorPartAniamiton = [SKAction moveByX:0 y:-self.frame.size.height duration:currentBackgroundAnimationLength];
      [currentBackground runAction:minorPartAniamiton];
  }

}


text:
Q: I try to get information from login form and change it to the id I have a login page in html that i get there username, password and type
and when i log in to the account i need to find the account details from the id of the user get when he register, but every time i get this message that it cannot convert from: "'java.lang.String' to required type 'long'"; how can i fix this?
my login method return long which is the id type.
this is the code:
public class LoginController {

    @Autowired
    LoginServiceImpl loginService;

    @GetMapping("/login/{userName}/{password}/{clientType}")
    public long Login(@PathVariable("userName") String userName,@PathVariable("password") String password,
            @PathVariable("clientType") ClientType clientType)throws CustomException {
        return loginService.login(userName, password, clientType);}

public long login(String userName, String password, ClientType clientType) throws CustomException {
    if(clientType.equals(ClientType.ADMIN)) {
        adminService.login(userName, password, clientType);
        System.out.println("admin loged in");

    }
    else if(clientType.equals(ClientType.COMPANY)) {
        Company companyLogin = companyRepository.findByCompName(userName);
        companyService.login(userName, password, clientType);
        System.out.println("company loged in");
        return companyLogin.getId();
    }
    else if(clientType.equals(ClientType.CUSTOMER)) {
        customerService.login(userName, password, clientType);
        System.out.println("customer loged in");
    }
    else {
        System.out.println("login didnt execute");
    }
    return 0;
}

    $scope.submit=function(){
$http.get("http://localhost:8080/rest/api/login/" +     $scope.username +"/" + $scope.password + "/" + $scope.cType).then(
    function(response){
        $scope.login = response.data;
        switch ($scope.cType){

            case "COMPANY":
                window.location.assign("http://localhost:8080/rest/api/company.html")
                break;

                $scope.hideAllTables();
                $scope.welcomePage = true;
                // $scope.MainMenu = true;
                $http.get('http://localhost:8080/rest/api/company.html/comanyDetailes/' + compny).then(function(response) {
                            $scope.company = response.data;
                            $scope.welcomePage = true;
                        }, function(error) {
                            alert('operation failed ', error.data);
                        });


text:
Q: Is the RAII wrapper a good idea for this C transactions API or should I stick to the C style? Consider the following C API:
void BeginTransaction(State *s);
void AddToTransaction(State *s, Object *value);
void CommitTransaction(State *s);

void Foo(State *s, Object *value)
{
    BeginTransaction(s);
    AddToTransaction(s, value);
    CommitTransaction(s);
}

I created a C++ class to wrap this API:
class StateTransaction
{
public:
    StateTransaction(State *s) : state_(s)
    {
        BeginTransaction(state_);
    }

    StateTransaction(const StateTransaction &st) = delete;

    void Add(Object *value)
    {
        AddToTransaction(state_, value);
    }

    ~StateTransaction()
    {
        CommitTransaction(state_);
    }

private:
    State *state_;
}

void Foo(State *s, Object *value)
{
    StateTransaction st(s);
    st.Add(value);
    // When st goes out of scope, the transaction automatically gets committed
}

Assuming that none of the functions can fail, is this a good use case for RAII? My main problem with it right now is that in order to force the transaction to be committed before some other code, I need to put the object in a new scope:
void Foo(State *s, Object *value)
{
    {
        StateTransaction st(s);
        st.Add(value1);
    }

    // Code which relies on transaction being completed
}

And of course, there's the danger that someone will come along and delete the braces because they look useless. That could be fixed with a comment like /* DO NOT DELETE BRACES */, but at that point it seems safer to just use the C API.
So, is the RAII wrapper a good idea? Or should I stick to the C style?

A: Using BeginTransaction and EndTransaction directly can give different results that using RAII.
If we compare:
BeginTransaction(s);
AddToTransaction(s, value);
CommitTransaction(s);

To:
{
    StateTransaction st(s);
    st.Add(value1);
}

There's a significant difference if the step of adding something to the transaction throws an exception. In the first case, throwing means execution in that scope will stop, resources cleaned up, and restart at the nearest matching exception handler.
In the RAII case, since the transaction is a resource that was created in that scope, it will be destroyed before exiting from that scope.
So, if the first AddToTransaction throws an exception, the transaction will be left hanging open, but in the second, it will be committed.
This probably doesn't make much difference if you only add a single item to the transaction, but consider a transaction in which we add several items:
BeginTransaction(s);
AddToTransaction(s, value1);
AddToTransaction(s, value2);
AddToTransaction(s, value3);
AddToTransaction(s, value4);
CommitTransaction(s);

Now, what happens if (for example) adding value 4 to the transaction throws? We haven't done anything to close the transaction--we have an open transaction with values 1-3 just "hanging".
In this case, we probably want to abort the transaction, not commit it though. So the dtor should probably look something like this:
~StateTransaction()
{
    if (std::uncaught_exceptions() > 0)
        AbortTransaction(state);
    else
        CommitTransaction(state_);
}

This way we know the transaction will always be closed--but it has at least a little intelligence about whether to abort or commit the transaction.
If we write code to do the same using CommitTransaction/AbortTransaction directly, it ends up pretty messy. We typically end up with something like:
try {
    BeginTransaction()
    AddToTransaction()
    AddToTransaction()
    CommitTransaction();
}
catch (...) {
    AbortTransaction();
}

If we try to handle this without exceptions at all, life gets even worse in a hurry. We typically end up with either deep nesting:
if (BeginTransaction())
    if (AddToTransaction())
        if (AddToTransaction())
            CommitTransaction();
        else
            AbortTransaction();
    else
        AbortTransaction();

I think a block without an obvious reason for existence is (by far) the cleanest solution that actually works.

A: In general using RAII to implement transactions is a good idea. However, you have to be careful when doing anything in the destructor.

*

*A destructor cannot return a value indicating success/failure.

*The destructor really should not throw exceptions, as the destructor may be invoked during exception handling.

This means we cannot really use destructors to represent operations that can fail.
Because the destructor will be invoked during normal control flow and during exception handling, it could happen that the transaction is not in fact complete:
StateTransaction transaction;
transaction.Add(x);
throw "oops";
transaction.Add(y);

Your current design would happily commit the "x" value, and miss the "y" value. This isn't a very transactional transaction, if the transaction may be incomplete.
Destructor-based transactions are more useful if they are implemented as rollbacks – the destructor will roll back the transaction unless it is explicitly committed. Implicit committing doesn't quite work.
To auto-commit only when no exception occurred, use normal control flow. If you want to avoid the possibility that the control flow exited normally but the programmer forgot to call Commit, then a callback-based solution would work (C++11):
template<class TransactionBuilder>
void transaction(TransactionBuilder callback) {
  State transaction;
  BeginTransaction(&transaction);
  callback(&transaction);
  CommitTransaction(&transaction);
}

transaction([&](State* transaction) {
  AddToTransaction(transaction, x);
  throw "oops";
  AddToTransaction(transaction, y);
});

A: As to your actual problem, assuming that "CommitTransaction" is poorly named and must be called even in exception cases (per your comments) and your issue is with the scoping of RAII, I see two choices.

Option 1: Comment the scope appropriately. C#-like syntax (C# has "using" for its RAII), or simply a message about the scope. Stylistic choice, just be consistent.
void Foo(State* s, Object *value)
{
    //using(StateTransaction st)
    {
        StateTransaction st(s);
        st.Add(value);
    }
    // Code which relies on transaction being completed
}

OR
void Foo(State* s, Object *value)
{
    //scope for StateTransaction st
    {
        StateTransaction st(s);
        st.Add(value);
    }
    // Code which relies on transaction being completed
}

Option 2: Refactor your scope into a private method/additional global function.
void FooAddValue(State* s, Object *value)
{
    StateTransaction st(s);
    st.Add(value);
}
void Foo(State* s, Object *value)
{
    FooAddValue(s, value);
    // Code which relies on transaction being completed
}

I prefer option 2. The fact that you feel you need this sub-scoping indicates that your function has multiple responsibilities and is thus violating the SOLID principle of Single Responsibility and should be broken up into multiple functions.

A:
Is the RAII wrapper a good idea for this C transactions API or should I stick to the C style?

Consider a RAII wrapper that rolls back the transaction in destructor, with explicit commit (note: I changed the API to use references:
class StateTransaction
{
public:
    StateTransaction(State &state) : state_(s), active_{ true }
    {
        BeginTransaction(&state_);
    }

    ~StateTransaction()
    {
        if(active_)
        {
            RollbackTransaction(&state_); // you didn;t mention this API,
                                         // but your C transactional
                                         // layer should have something like this
        }
    }

    void Commit() noexcept
    {
        active_ = false;
        CommitTransaction(&state_);
    }

    void Add(Object &value) { ... }

private:
    bool active_;
    State &state_;
};

Client code:
void Foo(State &s, Object &value)
{
    StateTransaction transaction{ s };
    transaction.Add(value);
    // ... may have multiple steps here
    transaction.Commit();
}

If anything throws, (in the multiple steps of the transaction), the transaction.Commit() will not be reached, and the transaction will be automatically rolled back on destruction.
Regarding the artificial scope (and someone removing it by mistake), simply name it and document the reason (instead of documenting what your colleagues should do with it):
void FooTransaction(State & s, Object & value) // name tells you it's a transaction (and
                                             // supposed to be one)
                                             // if it doesn't add a comment about it
{
    StateTransaction transaction{ s };
    transaction.Add(value);
    // ... may have multiple steps here
    transaction.Commit();
}

That said, a RAII wrapper may not be the best top-level abstraction to use. Consider adding the following API on top of it:
void transact(State& s, std::vector<Object*> values)
{
    StateTransaction transaction{ s };
    for(auto& x: values)
        transaction.Add(*x);
    transaction.Commit();
}

Client code:
transact(&state, { value });

This makes it clear what you are doing and that all effects (such as the transaction being committed) have been finished when the function has finished executing.


text:
Q: Call variable under a PS script as a parameter in Jenkins I have a config.ps1  script which has a variable "$versionNumber = "1.0.0"". I need enter the variable value of users choice and save the config.ps1 file. I need to do this task using Jenkins Parameter.
My config.ps1 script.
#------------------------------------------------
# Pack parameters used to create the .nupkg file.
#------------------------------------------------

# Specify the Version Number to use for the NuGet package. If not specified, the version number of the assembly being packed will be used.
# NuGet version number guidance: https://docs.nuget.org/docs/reference/versioning and the Semantic Versioning spec: http://semver.org/
# e.g. "" (use assembly's version), "1.2.3" (stable version), "1.2.3-alpha" (prerelease version).
$versionNumber = "1.0.0"

# Specify any Release Notes for this package.
# These will only be included in the package if you have a .nuspec file for the project in the same directory as the project file.
$releaseNotes = ""

# Specify a specific Configuration and/or Platform to only create a NuGet package when building the project with this Configuration and/or Platform.
#   e.g. $configuration = "Release"
#        $platform = "AnyCPU"
$configuration = ""
$platform = ""

Any possible approach is advisable
My approach--
Get-Content c:\config.ps1 | ForEach-Object { $_ -replace "$versionNumber = "1.0.0"", "$versionNumber = "$env:version_number" }

Output
PS D:\> . .\Config.ps1
PS D:\> $versionNumber=1.0.2
PS D:\> $versionNumber
PS D:\> . .\Config.ps1
PS D:\> $versionNumber
1.0.0
PS D:\>

A: You can source your *.ps1 file via the . operator. Example:
Test.ps1
$test=1234

PS>. ./Test.ps1
PS> $test
1234

So in your Jenkins Powershell step you've to call: . PATHTO\config.ps1


text:
Q: iOS 14 : UNUserNotificationCenter requestAuthorizationWithOptions always fails with "Notifications are not allowed for this application" I could not find a solution for this and dumbfounded on this. I have this code :
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
        UNAuthorizationOptionSound | UNAuthorizationOptionBadge;

[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions
        completionHandler:^(BOOL granted, NSError * _Nullable error) {
             NSLog(@"%i %@",granted, error);
        }];

and then it immediately gets into the call handler without showing the notification permission
2020-09-18 18:05:46.657991-0700 My App [404:9600] 0 Error Domain=UNErrorDomain Code=1 "Notifications are not allowed for this application" UserInfo={NSLocalizedDescription=Notifications are not allowed for this application}

What am i missing? The alert does not even popup.
NOTE: This same code works with no issues on iOS 13.x, on iOS 14 it immediately fails.

A: My problem was to use Turkish characters in the Product Name section.
https://developer.apple.com/forums/thread/660648

In my case, Build Settings - Packaging - Product Name was not English. Changed to English and worked.

A: The problem is you omitted a step. Before asking for authorization, call getNotificationSettingsWithCompletionHandler: and look at the authorizationStatus of the resulting object. If it is UNAuthorizationStatusDenied there is no point proceeding.

A: My product name was in Japanese. When the product name is non-english the above issue happens! If I change the product name to English it works! I have filed an issue via Apple Feedback Assistant.

A: I had the same problem. The other posters are right that it seems to be a non-English character in the app name (mine was ñ), for some reason that's disallowed.
To get around it I added CFBundleDisplayName to my plist and put the app's "correct" name (with the ñ) in there, and removed that character from the ${PRODUCT_NAME}.


text:
Q: creating social commerce site with Play! or Icefaces?or JVM based language? i want to build a social commerce site who can manage customers and buyers can meet their need and can do transaction in that site..i want to create it using java,but i confuse about framework i want to use..
in fact i have using icefaces but,you know,not a lightweight one,but i the component is so good,..
how about play farmework,they say play! is good and fast and lightweight,but is good enough to handle large users and the security?
or maybe a jvm based language,like scala or clojure,is that good?
iam sorry,but i kind of confuse about this thing..thanks for your response and sorry for my bad english..thanks..

A: Please note that Play uses Java/Scala under-the-hood which are JVM based and are really capable of powering large websites. Moreover Play is very scalable/productive/fast/easy-learning-curve (which are just few of many 'unique selling points'). Just Play! ahead and don't worry at all.


text:
Q: Android Bluetooth: file transfer over BluetoothSocket I wish to perform device-to-device file transfer over Bluetooth in my Android application.  Currently I have written the code necessary to make connections between multiple Bluetooth devices and I have retrieved connected BluetoothSockets for data exchange.
Is there a library available which implements file transfer that can be given a socket, or streams to use?
If not, can someone point me towards information about implementing the ability myself?
I am very new to file transfer programming and Bluetooth, so any help is appreciated.
Also, because I want this functionality built into my app, I am not looking to just run some other end-user app on the phone, I really do need to be able to code against this functionality (whether via a library, or my own implementation).

A: Normally over Bluetooth you would use something like OPP.
However that doesn't seem to be implemented on Android yet...
What I would do, is try serializing the data and sending it via RFCOMM or SPP bit by bit. For XML there is XStream, or, even simpler, Google's Protobuf.
Let me know if it works.


text:
Q: Which is normal percentage usage of internal cache for WiredTiger engine? I use mongoDB WiredTiger v3.4.1. Current stat of cache usage in mongostat is 80%(used field). Is it normal or this value should be lower?
Could you tell me where I can get normal values for all stats?


text:
Q: Defining Internal Energy The first law of Thermodynamics is $$ dU = dQ - dW $$ Halliday and Resnick says that energy transfer of heat Q $\text{occurs to the system}$ (which is by convention positive) and a Work W is done $\text{by the system}$ (which is by convention again is positive). this total energy transfer is the internal energy so shouldn't internal energy U be defined Q + W rather than Q - W.
Please let me know why is it defined Q - W whereas in chemistry it is defined as Q + W?
The above conventions are mentioned in Halliday Resnick

A: The convention for the International Union of Pure and Applied Chemistry (IUPAC) is the Kelvin form
$dU = \delta q + \delta w$
Heat eXits the system in an eXothermic process (and eNters in an eNdothermic process). Work eXits the system when it is done by the system. In either case (heat or work), exiting values are negative.
The convention for engineering is the Clausius form (which was the first statement of the first law)
$dU = \delta q - \delta w$
The same conventions apply for heat (negative for exothermic processes, positive for endothermic processes). For engineers, work done by the system has utility for us and is given a positive sign.
Both forms are explained here

A:
Please let me know why is it defined Q - W whereas in chemistry it is
defined as Q + W?

It's simply a matter of convention.
The sign of $Q$ is the same for both, with the sign for $W$ reversed. In the version $\Delta U=Q-W$ work done by the system is considered positive whereas in $\Delta U=Q+W$ the work done by the system is negative. But since, in the absence of heat, when a system does work its internal energy decreases, both versions are consistent.
Hope this helps.

A: Halliday and Resnick is not, in my opinion, a good book. There are many editions, and most of them have egregious errors that are corrected in the next edition, while  new errors are added.
I don't know what they say here, but work done by the system can be  positive or  negative. When work done by the system is positive the system  looses energy. Similarly the heat added to the system can be both positive or negative. When it is postive the system gains energy.
Note that Chemists and Physicics have opposite sign conventions. For physicists $Q$ is postive when the system gains energy, and for chemists $Q$ is postive when the system looses energy to the outside world (an exothermic reaction for example).


text:
Q: Gradle custom ear I would like to deploy my project with below structure:
--MyPrj.ear
  --APP-INF
    --classes
    --lib
  --META-INF
    --application.xml
    --weblogic-application.xml
  --WEB_MAIN
    --assets
    --WEB-INF
      --conf
      --web.xml
      --weblogic.xml

And here is my ear configuration
ear {
    appDirName 'APP-INF/src'
    libDirName 'APP-INF/lib'

    deploymentDescriptor {
        applicationName = "MyPRJ"
        displayName = "My Project"
        description = "My Project"
    }
}


text:
Q: How can I disable the popup that shows parameter info? I can't figure what this kind of popup is that shows information about function parameters for various overloads of a function I am writing a call to.

I want to get rid of it, but without its name, I can't.

A: These are parameter hints. Try setting the following in your settings.json file
"editor.parameterHints.enabled": false

The setting's description:

Enables a pop-up that shows parameter documentation and type information as you type.

A: U probably have an Extension installed on your VS code.


text:
Q: Android Bitmap to WebRtc I420 Frame corrupted Trying to stream bitmaps over WebRtc.
My Capturer class looks approximately like this:
public class BitmapCapturer implements VideoCapturer, VideoSink {
private Capturer capturer;

private int width;
private int height;

private SurfaceTextureHelper textureHelper;
private Context appContext;
@Nullable
private CapturerObserver capturerObserver;

@Override
public void initialize(SurfaceTextureHelper surfaceTextureHelper,
                       Context context, CapturerObserver capturerObserver) {
    if (capturerObserver == null) {
        throw new RuntimeException("capturerObserver not set.");
    } else {
        this.appContext = context;
        this.textureHelper = surfaceTextureHelper;
        this.capturerObserver = capturerObserver;
        this.capturer = new Capturer();
        this.textureHelper.startListening(this);
    }
}

@Override
public void startCapture(int width, int height, int fps) {
    this.width = width;
    this.height = height;

    long start = System.nanoTime();
    textureHelper.setTextureSize(width, height);

    int[] textures = new int[1];
    GLES20.glGenTextures(1, textures, 0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);

    Matrix matrix = new Matrix();
    matrix.preTranslate(0.5f, 0.5f);
    matrix.preScale(1f, -1f);
    matrix.preTranslate(-0.5f, -0.5f);

    YuvConverter yuvConverter = new YuvConverter();
    TextureBufferImpl buffer = new TextureBufferImpl(width, height,
            VideoFrame.TextureBuffer.Type.RGB, textures[0],  matrix,
            textureHelper.getHandler(), yuvConverter, null);

    this.capturerObserver.onCapturerStarted(true);
    this.capturer.startCapture(new ScreenConfig(width, height),
        new CapturerCallback() {
            @Override
            public void onFrame(Bitmap bitmap) {
                textureHelper.getHandler().post(() -> {
                    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
                    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
                    GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

                    long frameTime = System.nanoTime() - start;
                    VideoFrame videoFrame = new VideoFrame(buffer.toI420(), 0, frameTime);
                    capturerObserver.onFrameCaptured(videoFrame);
                    videoFrame.release();
                });
            }
    });
}

@Override
public void onFrame(VideoFrame videoFrame) {
    capturerObserver.onFrameCaptured(videoFrame);
}

@Override
public void stopCapture() throws InterruptedException {

}

@Override
public void changeCaptureFormat(int i, int i1, int i2) {

}

@Override
public void dispose() {

}

@Override
public boolean isScreencast() {
    return true;
}}

Resulting stream looks in following way:

Below, I'll try to give the results of my experiments so far.

*

*In case frame rotated to 90 degrees - stream looks normal.
VideoFrame videoFrame = new VideoFrame(buffer.toI420(), 90, frameTime);

*Tried to swap TextureBuffer size
TextureBufferImpl buffer = new TextureBufferImpl(height, width,
    VideoFrame.TextureBuffer.Type.RGB, textures[0],  matrix,
    textureHelper.getHandler(), yuvConverter, null);

*Also tried to pass height as both height and width
TextureBufferImpl buffer = new TextureBufferImpl(height, height,
    VideoFrame.TextureBuffer.Type.RGB, textures[0],  matrix,
    textureHelper.getHandler(), yuvConverter, null);

And I'm confused here. It seems that WebRtc somehow expects horizontal frame despite all sizes were set to vertical. I've tried to log all frame buffer sizes inside WebRtc library up to video encoder and they are correct.
The issue doesn't seem to be with convertation method, because except this I've tried to convert using ARGBToI420 from libyuv. The produced results were the same.
Would be extremely grateful for any assistance


text:
Q: why would url not load I have the code
Open Url

the sizeUrl has the value of http://www.mysite.com
but the following code doesnt load
var sizeUrl = $('#urlWindow').attr('value');

    newWindow.document.write(
        '' +
            ''+

        '' +

         ''

where as this one does
 var sizeUrl = $('#urlWindow').attr('value');

            newWindow.document.write(
                '' +
                    ''+

                '' +

                 ''

A: ''

You weren't breaking the string to include your variable.


text:
Q: What does In [*] in IPython Notebook mean and how to turn it off? I use Windows 7, Python 2.7.9 plus latest version of IPython 3.1.
I ran %python inside an IPython Notebook and ran the cell, instead of returning the Python version, it did not run and jumped to a new line and printed a In [*] instead of a line number. Now no line is running in ipython everything is ignored when I try to run a cell value.
Anyone know what has happen?

A: The kernel is busy. Go to the menu Kernel and click Interrupt. If this does not work click Restart. You need to go in a new cell and press Shift + Enter to see if it worked.

A: The issue causing your kernel to be busy can be a specific line of code.  If that is the case, your computer may just need time to work through that line.
To find out which line or lines are taking so long, as mentioned by Mike Muller you need to restart the program or interrupt the kernel.  Then go through carefully running one line at a time until you reach the first one with the asterisk.
If you do not restart or interrupt your busy program, you will not be able to tell which line is the problem line and which line is not, because it will just stay busy while it works on that problem line.  It will continue to give you the asterisk on every line until it finishes running that one line of code even if you start back at the beginning.  This is extremely confusing, because lines that have run and produced output suddenly lose their output when you run them on the second pass.  Also confusing is the fact that you can make changes to your code while the kernel is busy, but you just can't get any new output until it is free again.
Your code does not have to be wrong to cause this.  You may just have included a time-consuming command.  Bootstrapping has caused this for me.
If your code is what it needs to be, it doesn't actually matter which line is the problem line, and you just need to give all of your code time to run.  The main reasons to find out which is the problem line would be if some lines were expendable, or in case you were getting the asterisk for some other reason and needed to rule this one out.
If you are writing code on an internet service that times out when you aren't giving it input, your code might not have enough time to finish running if you just wait on it.  Scrolling every few minutes is usually enough to keep those pages from timing out.

A: For me to resolve this issue, I had to stop my anti-virus program.


text:
Q: Is it safe to use session in codeigniter? I wonder if using codeigniter session is safe.
Some earlier versions said no because the default configuration file was configured in a way that was unsafe.
In the current version (3.1.2), have this problem? Do I need to worry about using encription_key, for example?
Thank you.

A: Sessions are stored on the server. As long as the server is safe, sessions should be safe as well. CodeIgniter's session class is just a wrapper for PHP's native sessions.


text:
Q: Can an applet install an application? I have two questions:

*

*Can I use applet to install APK applications?

*Is it possible to send and install an APK application using OTA?
Summary, can I send an applet that contains an APK and install that?

A: AFAIK there is no way how an (U)SIM card applet could directly install an APK.
But it might be possible if there was an agent application installed (in the phone) which would install the APK on behalf of the (U)SIM applet (of course this application would have to have permissions to install APKs).
This agent application could communicate with the applet using the SIMalliance Open Mobile API (as long as the phone supports this API).

(Being enlightened by your other question)
Maybe you could trigger APK installation by opening the browser with the URL pointing to the APK file.
Good luck!


text:
Q: Fail to get flash effect by given times when using animate package Text flash effect is the purpose of the following simple code. Some text should flash for a given times(here is nine times) by a \foreach loop command.
However, it can not pass compile.
This error message is always given:
Package animate Error: Contents of first frame must not have zero width.

What's wrong with this code?
\documentclass{article}
\usepackage{pgffor,animate}

\begin{document}

\begin{animateinline}[autoplay,scale=1]{2}
    flash something
    \foreach \x in {1,...,9}{% flash nine times
        \newframe
            \newframe flash something
    }
\end{animateinline}

\end{document}

A: The implementation of TikZ/PGF's \foreach is faulty.
Any of the LaTeX3 comma-list mapping commands, such as \clist_map_inline:nn, does a better job here:
\documentclass{article}
\usepackage{animate}

\ExplSyntaxOn
\cs_set_eq:NN\clistMapInlinenn\clist_map_inline:nn
\ExplSyntaxOff

\begin{document}

\begin{animateinline}[autoplay]{2}
  \strut flash something: 0
  \clistMapInlinenn{1,2,3,4,5,6,7,8,9}{
    \newframe
    \newframe\strut flash something: #1
  }
\end{animateinline}

\end{document}

Note that package animate provides its own loop command for multiplying animation frames:
\documentclass{article}
\usepackage{animate}

\begin{document}
\begin{animateinline}[autoplay]{2}
\multiframe{9}{i=0+1}{        % 2nd argument may be left empty,
  \strut flash something: \i  % if a loop variable is not needed
  \newframe % <--- This one creates the blank in-between frame.
}
\newframe
\strut flash something: 9
\end{animateinline}

\end{document}

There is nothing wrong with using \foreach inside a frame definition. Just don't embed \newframe into the \foreach body. E. g.:
\documentclass{article}
\usepackage{animate}
\usepackage{pgffor}

\begin{document}

\begin{animateinline}[autoplay]{2}
\multiframe{9}{i=0+1}{
  \strut flash something:\makebox[1.2in][l]{%
                           \foreach \x in {0,...,\i}{ \x}}
  \newframe
}
\newframe
\strut flash something:\makebox[1.2in][l]{%
                         \foreach \x in {0,...,9}{ \x}}
\end{animateinline}

\end{document}


text:
Q: Blinking divs like traffic lights? I have this website: backlinkbeat.com. To the down, there are 3 divs having the background images. Each background-image includes a number like "1", "2", "3". I want those divs to blink as traffic lights respectively.
The script I wrote is not blinking the lights correctly as you can see in the link which means that it is not blinking the correct order. I want to blink them in the way are shown in the markup:

put you on just any, www.yourwebsite.com

Press "do it"

see the backlinks roll in!

The script I wrote which donot work correctly is:
setInterval(function () {
    setTimeout(function(){
       var vis1 = $("#blink1").css("visibility");
       vis1 = (!vis1 || vis1 == "visible") ? "hidden" : "visible";
       $("#blink1").css("visibility", vis1);
        }, 1000);
    }, 1000);
setInterval(function() {
    setTimeout(function(){
       var vis2 = $("#blink2").css("visibility");
       vis2 = (!vis2 || vis2 == "visible") ? "hidden" : "visible";
       $("#blink2").css("visibility", vis2);
    }, 2000);
}, 2000);
setInterval(function() {
    setTimeout(function(){
       var vis3 = $("#blink3").css("visibility");
       vis3 = (!vis3 || vis3 == "visible") ? "hidden" : "visible";
       $("#blink3").css("visibility", vis3);
    }, 3000);
}, 3000);

Thanks,
Areeb

A: I suggest you give your elements a common class, ex:

One

Two

Three

Then you can simplify your code to:
//Cache element collection and keep a reference to the visible element
var $elements = $('.blink').css('visibility','hidden'),
    $visible = $elements.first().css('visibility','visible');

//Single interval function to handle blinking
setInterval(function(){
    //Hide visible element
    $visible.css('visibility','hidden');
    //Find next one
    var $next = $visible.next('.blink');
    if(!$next.length)
        $next = $elements.first();
    //Show next element
    $visible = $next.css('visibility','visible');
},1000);

Demo fiddle

A: This may be what you're looking for. http://jsfiddle.net/andaywells/eQuXn/15/
I have modified this code: http://jsfiddle.net/paislee/pdsu7/5/
So that each div stays in position, the 'hold' div keeps it there.
$(document).ready(function () {

var delay = 5000,
    fade = 500;
var banners = $('.banner');
var len = banners.length;
var i = 0;

setTimeout(cycle, delay);

function cycle() {
    $(banners[i % len]).fadeOut(fade, function () {
        $(banners[++i % len]).fadeIn(fade, function () {
            setTimeout(cycle, delay);
        });
    });
}

});

A: Perhaps this example will help you.
CSS

.lamp {
    height: 30px;
    width: 30px;
    border-style: solid;
    border-width: 2px;
}
.lampRed {
    background-color: red;
}
.lampYellow {
    background-color: yellow;
}
.lampGreen {
    background-color: green;
}

HTML

Click to Start and Stop

Javascript

var changeState = (function () {
    var state = 0,
        lamps = ["Red", "Yellow", "Green"],
        lampsLength = lamps.length,
        order = [
            [5000, "Red"],
            [3000, "Red", "Yellow"],
            [5000, "Green"],
            [3000, "Yellow"]
        ],
        orderLength = order.length,
        lampIndex,
        orderIndex,
        sId;

    return function (stop) {
        if (stop) {
            clearTimeout(sId);
            return;
        }

        var lamp,
        lampDOM;

        for (lampIndex = 0; lampIndex < lampsLength; lampIndex += 1) {
            lamp = lamps[lampIndex];
            lampDOM = document.getElementById(lamp);
            if (order[state].indexOf(lamp) !== -1) {
                lampDOM.classList.add("lamp" + lamp);
            } else {
                lampDOM.classList.remove("lamp" + lamp);
            }
        }

        sId = setTimeout(changeState, order[state][0]);
        state += 1;
        if (state >= orderLength) {
            state = 0;
        }
    };
}());

document.getElementById("trafficLight").addEventListener("click", (function () {
    var state = false;

    return function () {
        changeState(state);
        state = !state;
    };
}()), false);

On jsfiddle


text:
Q: Import statements in modules in Python Let's say I have a module that defines a function:
# import time
def printTime():
    import time
    print 'the time is ' + time.time()

I my main app, I load the function like this:
from modules.Help import printTime
if somecondition:
    # from modules.Help import printTime
    printTime()

In modules, should I do all imports at the top of the file?
Or, since the module is only required under certain conditions, should I do the import in the function?
What is more economical, or is there no difference?
In PHP, there is the require_once. Are the import statements at the top of submodules optimised in the same way?
I have some duplicate imports (e.g. time) in both the parent and submodule. Should I worry about the number of packages that I import in submodules?


text:
Q: Cast FileInfo into FileSystemInfo I am working on modifying file copy program that used to only copy a directory to another directory. Now I want to pass both directories and files in a list for the copy to run.
    For Each _fromPath In CopyList
        Dim FSinfo As FileSystemInfo()
        If Directory.Exists(_fromPath) Then
            Dim dir As New DirectoryInfo(_fromPath)
            FSinfo = dir.GetFileSystemInfos
        ElseIf File.Exists(_fromPath) Then
            Dim file As New FileInfo(_fromPath)
            FSinfo = file
        End If

        CountFiles(FSinfo)

    Next

    Private Function CountFiles(ByVal FSInfo As FileSystemInfo()) As Boolean

This code works fine for directories. In order to pass paths to the CountFiles, they must be in FileSystemInfo. Is there anyway to get FileInfo casted as a FileSystemInfo.
I tried CType(file, FileSystemInfo) but it said Value of type 'System.IO.FileInfo' cannot be converted to '1-dimensional array of System.IO.FileSystemInfo'.

A: One problem is that you are trying to convert an object (FileInfo) to an ARRAY of objects (FileSystemInfo()) which is what the error message is trying to tell you.  You could write an overloaded function to handle some of that:
' my Count functions return numeric values:
Private Function CountFiles(FSInfo As FileSystemInfo()) As Integer

Private Function CountFiles(FInfo As FileInfo) As Integer

Internal to them, the FileSystemInfo might call the other in a loop to avoid duplicate code, or maybe they both call a common procedure depending on how it is written.


text:
Q: How to default search to organization to see promoted search? I am working to use promoted search results to help guide our users towards their most common query faster. The issue is that you have to select Organization in order to see promoted search results. Does anyone have any recommendations for solving the issue of displaying promoted search results in the default search or making the default search the organization search?
FYI - This is for SharePoint Online
Search example for a promoted result I added:

It does not display the promoted result, clicking Organization

Now it shows the promoted search result

Thank you for your help!

A: did not come across this. But logical thinking tells me to do below

*

*Get the Organizational results page URL (it would differ from normal search with respect to parameters I suppose)

*Set it as the default search results page

Below is not a desired way

If above cannot be accomplished (meaning the URL doesn't change between normal search and org search & its an internal PostBack), then see whats happening while you click on "org" using F12 dev tools and try to call that on page load (Jquery.load(executeOrgClick))

A: came across this question when I was searching for a solution myself. You can use PnP powershell to make Organization level search as default.
Refer:https://techcommunity.microsoft.com/t5/sharepoint/configure-modern-search-results-to-search-all-of-your/m-p/447334


text:
Q: li element custom attribute not getting in IE 10 I have an list where I have added dataset attribute like this

  Correos

I am selecting element a and using that I am trying to get the attributes of LIST element like this
var parent = $(this).closest('li')[0];
if (!parent.dataset.action) {
    return;
}

Where $(this) is a selector for the a element. It is working fine in Chrome but in IE 10 it is giving error in console:

Unable to get property 'action' of undefined or null reference

Any help would be helpful for me.

A: The problem is because dataset is only available from IE11 onwards - MDN.
To fix this you can use jQuery's data() method:
var $parent = $(this).closest('li');
if (!$parent.data('action'))
    return;


text:
Q: Can/should Thread Switching be controlled? Forgive me - I'm not a hardware tech, just an app user.
Background: I've observed that when I am running one large process in a singlethreaded program (OCAD, QGIS, usually R, etc), I can see that one of my cores (8 phys, 16 log, i9_9900K CPU) is at or near 100% for a while and then drops to zero just as another core goes from nothing to at or near 100%. While observing this, all of the other cores bump along near zero, so it's clear that the one large process is consuming one core, but that it switches amongst available cores

*

*Is this 'thread switching' slowing down the processing of whatever I'm having the app do?

*If "yes" to #1, is there a way that I can make this stop happening?

A: *

*Yes, but in scales of "a while" it is indiscernible.  Since RAM is so slow compared to processor speed, processors automatically remember recently accessed locations in very fast memory (cache) in the hope they will require it again.   This operation speeds up the overall processing.   When a program switches to another processor, it will take a bit of time repopulating the caches.  Again, very small amounts of time, so unless the switching is happening very rapidly, it is not a concern.   It is somewhat odd behaviour though.

*If you are on linux, you could use taskset to launch your program; for example taskset 4 R would somewhat confusingly run R on cpu 3.  The first argument to taskset is a bitwise-set of which processors R should run on.  The manual should likely explains it better than I can.   If you aren't on linux, your system will likely have some equivalent, you might have to hunt around a bit for it.


text:
Q: Simulate Data Protection on iPhone Simulator I am trying study the Data Protection Process on iPhone Simulator, but i am failing at the initial step.I created a DB File and added it to the Application Resources. During the Application Launch i copy this file to the Application Folder.
Then i do this:
NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];

if (![[NSFileManager defaultManager] setAttributes:fileAttributes ofItemAtPath:appDBPath error:&error]) {
        //handle error
    }

But when i check the file attributes after this, i do not get the key NSFileProtectionKey
Am i missing something obvious in it? Do we have to add any Framework for Data Protection?
Or is it that this can only be tested on the device?
I need to get it done quickly.. Please help me guys :(


text:
Q: iMacros - WhatsApp Web I'm working on a project that extracts a table from a webpage dashboard, then it goes to excel where it gets filtered by how many each user has in a nice table, and the next step I'm working on is having already in the clipboard the table I want to send it to our work group on whatsapp, specifically in chrome since it sends the tables as an image.
EVENT TYPE=CLICK SELECTOR="HTML>BODY>DIV>DIV>DIV>DIV:nth-of-type(2)>DIV:nth-of-type(2)>DIV>LABEL>INPUT" BUTTON=0
EVENTS TYPE=KEYPRESS SELECTOR="HTML>BODY>DIV>DIV>DIV>DIV:nth-of-type(2)>DIV:nth-of-type(2)>DIV>LABEL>INPUT" CHARS="Usuario Admin"
EVENTS TYPE=KEYPRESS SELECTOR="HTML>BODY>DIV>DIV>DIV>DIV:nth-of-type(2)>DIV:nth-of-type(2)>DIV>LABEL>INPUT" KEYS=13
EVENT TYPE=CLICK SELECTOR="HTML>BODY>DIV>DIV>DIV>DIV:nth-of-type(3)>FOOTER>DIV>DIV>DIV>DIV:nth-of-type(2)" BUTTON=0
EVENT TYPE=KEYPRESS SELECTOR=* Char="V" MODIFIERS="ctrl"
TAG POS=1 TYPE=BUTTON ATTR=CLASS:btn<SP>btn-round<SP>btn-l&&TXT:

I used EVENT mode since the conventional mode didn't do anything
This script was working but then it stopped doing it, on Chrome instead of writing the group name on the search bar it does in the chat now:S
on Firefox, I need to have something written in the search bar(like a space) so it writes it there but the ENTER part doesn't always work.
Is there a way that ensures it writes where it should?, I tried something in javascript but it wrote it on search but it was like I had to type something so it searches what it was written, I hope I explained myself correctly.
Thanks!

A: Since the search bar was very tricky, and worked when it wasn't empty I tried to write a space before the word and it worked:
EVENTS TYPE=KEYPRESS SELECTOR="HTML>BODY>DIV>DIV>DIV>DIV:nth-of-type(2)>DIV:nth-of-type(2)>DIV>LABEL>INPUT" CHARS=" Usuario Admin"


text:
Q: Recursive block arrangement pattern. I'm allowed to only use three blocks (these ones) and only use the corner pieces together, to build different shapes of height $3$ and variable width.
I'm tasked with finding a recursive pattern for the number of arrangements of width $1, 2, 3, 4. . .$.
I've drawn out the number of arrangements for the first 4 widths:(here) but I cannot seem to figure out the pattern.
I realize that:

*

*Starting with all the shapes of width $1$, you can combine shapes of width $3$ in $17$ different ways to build the shapes of width $4$,

*Starting with all the shapes of width $2$, you can make all the shapes of width $4$ (which is $21$)

*Starting with all the shapes of width $3$, it's the same as all the shapes as width $1$.

I do not see a specific (recursive) pattern here, can someone help me out? Thanks.

A: Using this information, you can define base cases $f(1) = 1, f(2) = 3, f(3) = 10$, and then the number of arrangements of width $n \ge 4$, $=f(n) = f(n-1) + 2f(n-2) + 5f(n-3)$.


text:
Q: Does OpenIddict 2.0.0 RC3 Final support AspNetUsers table? I have followed the video tutorial at the weblink below and am receiving the following error when I navigate to https://localhost:5001/connect/token:

fail: Microsoft.AspNetCore.Server.Kestrel[13]
        Connection id "0HLFGA04R3IV9", Request id "0HLFGA04R3IV9:00000001": An unhandled exception was thrown by the
  application. System.Data.SqlClient.SqlException (0x80131904): Invalid
  object name 'OpenIddictApplications'.

From what I can tell, the new OpenIdDict does not support the AspNetUsers table that is created with a migration. Is this correct?
In this tutorial, the author is using the AspNetUsers table. Note: the author is using OpenIddict 1.0. and I am using 2.0 RC3. I am unable to get my sample TodoList project to use the AspNetusers table. Is it possible to get OpenIddict 2.0 to use the AspNetUsers table? If yes, how?
https://www.youtube.com/watch?v=GIQqIz1Gpvo&index=4&list=PLu4Bq53iqJJAo1RF0TY4Q5qCG7n9AqSZf
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using TodoListAPI.Data;
using JsonApiDotNetCore.Extensions;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using OpenIddict.Abstractions;
using OpenIddict.Core;
using OpenIddict.EntityFrameworkCore.Models;
using OpenIddict.Validation;
using TodoListAPI.Models;
using AspNet.Security.OpenIdConnect.Primitives;
using Microsoft.IdentityModel.Tokens;

//// Some code here

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigins",
        builder =>
        {
            builder.WithOrigins("http://localhost:4200");
        });

        //options.AddPolicy("AllowAllOrigins",
        //builder =>
        //{
        //    builder.AllowAnyOrigin();
        //});
    });

    services.AddDbContext<AppDbContext>(opt =>
        {
            opt.UseSqlServer(this.GetConnectionString());
            opt.UseOpenIddict();
        });

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<AppDbContext>()
        .AddDefaultTokenProviders();

    services.AddOpenIddict()
        .AddCore(opt =>
        {
            opt.UseEntityFrameworkCore()
                .UseDbContext<AppDbContext>();
        })
        .AddServer(options =>
        {
            options.UseMvc();
            options.EnableTokenEndpoint("/connect/token");
            options.AllowPasswordFlow();
            options.AllowRefreshTokenFlow();
            options.DisableHttpsRequirement();
            options.AcceptAnonymousClients();
            // options.AllowAuthorizationCodeFlow();
        })
        .AddValidation()
        ;

    services.AddAuthentication(options => {
        options.DefaultScheme = OpenIddictValidationDefaults.AuthenticationScheme;
    });

    services.Configure<IdentityOptions>(options =>
    {
        options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
        options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
        options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
    });

    services.AddJsonApi<AppDbContext>(opt => opt.Namespace = "api/v1");
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    // Shows UseCors with CorsPolicyBuilder.
    //app.UseCors(builder => builder.WithOrigins("http://localhost:4200"));
    app.UseCors("AllowSpecificOrigins");

    //app.UseIdentity();
    //app.UseOpenIddict();
    //app.useoauth

    app.UseAuthentication();
    app.UseMvcWithDefaultRoute();
    app.UseJsonApi();
}

A: Found the answer: https://stackoverflow.com/a/46329242/4630376
Turns out that OpenIddict requires both sets of tables: ASP and OpenIddict tables.


text:
Q: Warning on setting variable in MYSQL 8.0 I am getting a deprecation error on the following query, and I can't seem to figure out the correct syntax.
SELECT case_id, start_date, end_date,
@calc_end_date:= COALESCE(actual_end_date, end_date, CURDATE()),
DATE_SUB(@calc_end_date,INTERVAL 5 day) AS ending_soon
FROM authorizations;

The query works, but I get the following warning:
Setting user variables within expressions is deprecated and will be removed in a future release. Consider alternatives: 'SET variable=expression, ...', or 'SELECT expression(s) INTO variables(s)'.
I tried (leaving out part of the query for simplicity):
SELECT case_id, start_date, end_date,
(SELECT COALESCE(actual_end_date, end_date, CURDATE()) FROM authorizations INTO @calc_end_date)
FROM authorizations;

And:
SELECT case_id, start_date, end_date,
(SET calc_end_date = COALESCE(actual_end_date, end_date, CURDATE()))
FROM authorizations;

And both do not work. What am I doing wrong?

A: Works for me in MySQL 8.x. For example:
create table t (a int, b int);

insert into t (a, b) values (5, 3);

select a * b into @total from t;

select @total;

Result:
@total
------
    15

However, if your query produces more than a single row, the query crashes. For example:
create table t (a int, b int);

insert into t (a, b) values (5, 3);
insert into t (a, b) values (7, 2);

select a * b into @total from t;
Error: Result consisted of more than one row
SQLState:  42000
ErrorCode: 1172

This makes a lot of sense since a variable can only hold a single value.


text:
Q: Spreadsheet styles.xml shows alpha value for fonts as zero I got a wierd ooxml spreadhsheet document whose styles.xml has the following content :
-<fonts count="3">
-
<sz val="10"/>
 <color rgb="FF000000"/>
 <name val="Arial"/>

-
<sz val="9"/>
 <color rgb="00333333"/>
 <name val="Arial"/>

-

<sz val="9"/>
<color rgb="00FFFFFF"/>
<name val="Arial"/>

</fonts>

I am unable to render it on the screen, since the alpha value for the fonts is set to zero in this case. If I re-save the document again, the alpha value in styles.xml changes to 0xFF and the content is visible on the screen. The entire code for reading the values in written in C using XML Parser. The original document is able to open fine in Office suite. Is it that Office suite is discarding alpha values for the fonts or applying a workaround to view the document? Are there some other values in styles.xml that I should be looking for in alpha value for the fonts is set to zero so I can render the content on the screen?Any pointers.
or In other words, what other properties can help if alpha value of font is zero but the content should still be visible? Probably, another value in the xml file that I may be ignoring?

A: It seems like there was an issue in the xml itself, as if someone has explicitly modified it. Fixed it by checking for the color theme value while reading fonts in styles.xml and if not set, set the alpha value of the font to 0xFF and voila, everything works
Re-saving the same document once again causes the font's alpha value to be reset to 0xFF, hence, proving my point.


text:
Q: c program does not print anything I have been having trouble with this program for a few days and I have decided to see if anyone could help me or give me hints as to why its not working. I am trying to do a program that will take the user input and then print it back to the user ( I am really trying to do a sort of text editor but I am doing it one step at a time to make sure I understand all the parts). I have not given a max of lines, I'd like the user to be able to write as many lines as he/she would like to thats why I am using malloc, and realloc after to readjust the necessary memory:
The problem I am having is that it doesn't print anything
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LEN  1000

int main(void)
{

  int totalLines = 0;
  char content[MAX_LEN + 1];
  char **arrays;
  int i = 0;

  printf("Enter your text to be edited\n");

  while (content[0] != '.') {
    fgets(content, MAX_LEN, stdin);
    content[strlen(content) - 1] = '\0';

    arrays = malloc(sizeof(char *) * totalLines);
    for (i = 0; i < totalLines; i++) {
      arrays[i] = malloc(sizeof(char) * (strlen(content) + 1));
      strcpy(arrays[i], content);
    }

    if (totalLines >= 1) {
      arrays = realloc(arrays, sizeof(char *) * totalLines);
      for (i = 0; i < totalLines; i++) {
        arrays[i] = malloc(sizeof(char) * (strlen(content) + 1));
        strcpy(arrays[i], content);
      }
      totalLines++;

    }
  }

  /* after user presses '.' the following is excuted: */

  for (i = 0; i < totalLines; i++) {
    printf("%s", arrays[i]);
  }
  int k;
  for (k = 0; k <= totalLines; k++) {
    free(arrays[k]);
  }
  free(arrays);
  arrays = NULL;
  return 0;
}


text:
Q: Vector size increases only by one when insert with multiple elements I'm currently learning C++ and for my current goal I want to fill values from vector A into vector X. vector X must not be larger than 20. To archive this I have a function that checks if the current vector has space left. If no space is left, it replaces the current vector with a new vector from a template (which already contains some entries, that have to be the same for all the vectors):
int ChunkedBufferBuilder::checkNewBuffer() {
  int space_left = chunk_size - super::current.size();
  if (space_left == 0) {
    bufVec.push_back(super::current);
    super::current = tpl;
    space_left = chunk_size - super::current.size() ;
  }

  return space_left;
}

bufVec is another vector holding all vectors that have reached a size of 20. This function returns always the remaining amount of "free" entries in the current Vector.
To prevent having to insert every single value from the input vector in to the smaller vectors, I'm trying to use the insert function here:
ChunkedBufferBuilder* ChunkedBufferBuilder::push_back(const std::vector<uint8_t> &vec) {
  auto pos = 0;
  const auto size = vec.size();

  while (pos < size) {
    const int space_left = checkNewBuffer();
    const int to = (space_left > size - pos) ? size : pos + space_left;
    auto fromPtr = vec.at(pos);
    auto toPtr = vec.at(to);

    int size = super::current.size();

    super::current.insert(super::current.end(), fromPtr, toPtr);

    size = super::current.size();

    pos = to;
  }

  return this;
}

Note, that the second size = super::current.size() was placed there by me for helping to debug. In the following images I have set two breakpoints. One on the line where insert is called and the other one on the pos = to assignment.
The documentation of std::vector states that:

The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.

Thus I expect that the size increases by the amount of elements, that I added. But when I run the debugger:
I get these values at the first breakpoint:

And at the second breakpoint size only increased by one:

However on the second pass of the while loop, it then tries to insert another twelve values (size is still 8 so 20 - 8 == 12):

And then suddenly the size jumps to 22:

This is currently breaking my program and I'm pretty much clueless why my code behaves in the way it currently does.

A: In this snippet:
auto fromPtr = vec.at(pos);
auto toPtr = vec.at(to);

super::current.insert(super::current.end(), fromPtr, toPtr);

you are inserting fromPtr copies of the value toPtr (i.e. overload (3)). From your description, it appears you mean to use overload (4):
super::current.insert(super::current.end(), vec + pos, vec + to);

which copies elements from vec to super::current.


text:
Q: How do you delete an item from a 'this' object in a jQuery function? I am trying to delete an
 item using the this.remove() function but I can't find the function in the DOM using Firebug:
jQuery
$( "#list_a, #list_b" ).sortable({
  connectWith: ".connected_sortable",
  receive: function(event, ui) {
    $("#list_b li").each(function() {
      if(ui.item.context.id == this.id)
        $(this).remove(); //<-----HOW DO I DELETE?  (also tried this.remove())
});}}}).disableSelection();

HTML

test text

test text

test text

test text

How would I go about deleting an
 here? Please do not give me a direct reference solution - eg $("#item_3").remove() because I am trying to delete the other similiar id
.

A: I think this should work.
$('#list_b li[id="'+ ui.item.context.id +'"]').remove();

this should replace the .each loop you have btw:
also, you should use $(this).attr("id") instead of this.id assuming you meant the jQuery element when y9ou said this, but try the above first me thinks.
also look at this question JQuery. Remove element by attribute name. How?


text:
Q: link criteria ms access stLinkCriteria = "[UpdateStatus] = '" & _
    Forms![Updates-Search Menu]!LookupUpdateStatus & "'" & " And _
    [Office] = '" & [Office] & "'"

Just trying to confine my search to a linked criteria. It looks at the update status and office and filters my form correctly. The above code is my base code that currently works. I want to add one more criteria so it looks like this
update status AND (office or shared). Here is my attempt but does not work
stLinkCriteria = "[UpdateStatus] = '" & _
    Forms![Updates-Search Menu]!LookupUpdateStatus & "'" & " _
    And [Office] = '" & [Office] & "'" Or _
    "[Forms]![Updates]!ShareWithOtherOffice = -1"

Any help is appreciated

A: It should probably be
stLinkCriteria = "[UpdateStatus] = '" & _
    Forms![Updates-Search Menu]!LookupUpdateStatus & _
    "' And ([Office] = '" & [Office] & _
    "' Or [Forms]![Updates]!ShareWithOtherOffice <> 0)"

Since AND is performed before OR by default, you must enclose the office stuff in parentheses in order to execute the OR before the AND.
Also I the OR should be within the string.
I am using a Function Build which makes it simpler
Function Build(ByVal s As String, ParamArray args()) As String
    'Build("LastName = '{0}', FirstName = '{1}'","Doe","John").

    Dim i As Long

    For i = 0 To UBound(args)
        s = Replace(s, "{" & i & "}", Nz(args(i)))
    Next i
    Build = s
End Function

sql = "[UpdateStatus] = '{0}' And ([Office] = '{1}' Or {2})"
stLinkCriteria = Build(sql,
                       Forms![Updates-Search Menu]!LookupUpdateStatus, _
                       [Office], _
                       [Forms]![Updates]!ShareWithOtherOffice <> 0)


text:
Q: Ajax inserted content not accessible in DOM I am working on a pure jquery/js site, mostly to practice some jquery. I am using a load statement to load a menu from a file of common html, like so:
$('#categoryListing').load('../common.html #categoryLinksUL');

which loads:

Anklets

Bracelets

The problem is where I am using it now I need to alter the href of the above links, but they are not part of the dom. In previous instances I was able to use .live(click... But not here. Is there a way I can accomplish this?
Specifically I need to load the links and change the href from #anklets to ?category=anklets

A: What about the following?

$('#categoryListing').load('../common.html #categoryLinksUL', function() {
    $('li a[href^="#"']').each(function () {
        this.href = '?category=' + this.href.substr(1);
    });
});

In my example, after the load is completed, the anonymous function is called. It takes every anchor with a hash HREF and replaces it with an HREF based on your description.

A: Thank you Dimitry, you solution basically worked. I finally used:
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
  $('#categoryListing li a').each(function () {
    var hashPos=this.href.indexOf("#");
    var tCategory = this.href.substr(hashPos+1,this.href.length );
  });
});

So why did jQuery recognize categoryListing there? I tried moving the each function outside of the load function and categoryListing did not contain any links. Is it because maybe the load was not completed when it tried to get categoryListing links? Seems like that is possible.
Thanks,
        Todd


text:
Q: Cassandra failure detection mechanism Cassandra has gossiper implementation(class org.apache.cassandra.gms.Gossiper) as well as implementation of 'The Phi Accrual Failure Detector'(class org.apache.cassandra.gms.FailureDetector).
As far as I know, both are mechanisms for failure detection. So which one of these is exactly used for detecting node failures by Cassandra?

A: The 2 work hand-in-hand.
The FailureDetector uses the last gossip heartbeat to calculate the elapsed interval in order to decide whether a node has failed and mark it as down. Cheers!


text:
Q: prevent inheritance of interface outside of package I have a stateless abstract base class that should not be inherited from outside of its package:
package foo;

public abstract class Foo
{
    // some abstract methods
    // one concrete method
    // no state

    // Prevent classes outside of package foo from inheriting
    Foo()
    {
    }
}

Now that Java 8 supports default methods in interfaces, I would like to convert the abstract class to an interface. With interfaces, is it also possible to prevent inheritance outside of the current package?

A: From the java tutorial:

.. All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

It means that you can't unless you restrict the interface visibility to package. But i guess that you can't.
package foo;

interface Foo
{
}

I suppose that you could write a custom annotation (somelink like @InstanciableOnlyInMyPackage) and put it on the interface. And then using raise a compiler error using Annotation Processing Tool.


text:
Q: Write unit test for metadata Can someone give an example how to write unit test for this function by using async and await....
function writeFragment(fragment) {
  return metadata.put(fragment.ownerId, fragment.id, fragment);
}