text:
Q: pass parent url to iframe - iframe auto resize I'm using a solution I found here on stackoverflow that auto sizes an iframe based on its content.
https://stackoverflow.com/a/362564/258594
My iframe is being used by several websites so I need the call to the helper file to be dynamic instead of hard coded. How can I pass the parent url to my iframe to change the following line.
pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();

A: Ended up adding the url to the iframe src

Then accessed it in the iframe srouce file
URL = window.location.hash.substr(1);
var height = document.body.scrollHeight;
var pipe = document.getElementById('helpframe');
pipe.src = URL + '/helper.html?height='+height+'&cacheb='+Math.random();

A: First Solution

Second Solution

foo.html

Your all content


text:
Q: Top down approach of longest increasing subsequence?
https://leetcode.com/problems/longest-increasing-subsequence/

This the link of the question which I tried to solve using recursion + memorization technique but not able to solve my testcases only pass only up to 4 is also I don't know that whether my approach is correct or not.
Below this line is the code I tried:
int lis( vector<int>& nums, int i, int n, int prev, vector<int>& ls){
    if(i==n||n==0){
        return 0;
    }
    if(ls[i]!=-1){
        return 1 ;
    }

    lis(nums,i+1,n,prev,ls);

    if(nums[i]>prev){
        int  num=1+lis(nums,i+1,n,nums[i],ls);
        ls[num]=1;
        return num;
    }

    return 0;
}

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int  n=nums.size();
        int c;
        vector<int> ls(n+1,-1);

        lis(nums,0,n,INT_MIN,ls);
        for(int i=n;i>=0;i--) {
            if(ls[i]!=-1) {
                c=i;
                break;
            }
            else {
                c=0;
            }
        }
        if(nums.size()==0) {
            return 0;
        }
        else    {
            if(c==0) {
                return 0;
            }
            else {
                return c;
            }
        }
    }
};

I want to know how to apply  recursion + memorization technique in this type of question. Everyone is teaching bottom up approach, not top down approach so it is hard to understand top down. So explain me how to solve this question?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serial port com3 doesn't exist c# I have an usb device that is plugged in as a serial port on com3. I use this to open port:
string[] ports = SerialPort.GetPortNames();
foreach (string portName in ports)
{
     try
     {
          var port = new SerialPort(portName, 256000);
          port.Open();
     }
     catch(Exception ex)
     {
          Console.WriteLine(ex.Message);
     }
}

I get an io exception here "port com3 does not exist". I use VS2012 + Win7x64Pro. I tried to reboot windows and everything worked fine, but just 1 time. Some days ago I run this project on VS2012 + Win8 and everything was great. It worked great, no exceptions were found. I found great amount of similar questions but there are not any solution for this problem. For more information: as a usb device I use BlueGiga BLED112 with driver version "ble-1.1.1-71". Explain me please where and what am I doing wrong.

A: Bluetooth often creates phantom virtual serial ports that can't actually be opened.  In an even worse scenario, it is paired, and the driver spends a minute looking for a not-present Bluetooth accessory before failing to open.
Other serial devices may not respond well to being opened for no reason (opening does change voltages on several serial pins).
Solution: Never open all serial ports returned by GetPortNames in a loop.  Instead open just the one your device is attached to.  (You can know this by checking device descriptor strings, or in the worst case, asking the user which of the listed ports is the right one)
Perhaps you're just trying to use the Bluetooth radio?  In that case you're using the wrong approach.  The serial port associated with Bluetooth is for use when you pair with a device that identifies itself as the SPP (Serial Port Profile).  Not for manipulating the radio.  For that you use the Sockets API.  See Bluetooth Programming with Windows Sockets.  From C#, you'll want to use one of the third-party libraries that wraps this stuff.


text:
Q: Code for dynamic commenting feature I have tried searching the internet but couldn't find what I needed.
I am familiar with php mysql html and css. However, I can't use javascript or php to make a dynamic feature like I have explained below:
I need commenting feature similar to youtube attached to photo or video.
every time the files are uploaded to the system.
The user should be able to enable or disable the feature. He will have access through Facebook login.
The one who comments will just need to provide his name and his comments.
If you have the solution or can offer any help please share the link or any code would be helpful also.

A: I can do it now from Laravel. Learn it, it is awesome!!


text:
Q: How to Convert scapy packetList to dataframe in python? I am trying to convert(pcap data) packetList to dataframe so that i can perform preprocessing on it.
I have used scapy library to read pcap file.
import pandas as pd
from scapy.all import *

packets_list=rdpcap('D:/anaconda/path/youtube2.pcap')
//return type PacketList

print(packets_list[3].show())    //Display contents of the packet

df = pd.DataFrame (packets_list,columns=
['No.','Time','Source','Destination','Protocol','Length','Info'])

print (df)

ERROR:
TypeError: DataFrame constructor called with incompatible data and dtype: cannot copy sequence with size 66 to array axis with dimension 1
Please help anyone.

A: I used something like this:
fields = {
    UDP: ('sport', 'dport'),
    # ...
}

df = pd.DataFrame({field: [getattr(pkt[layer], field) if layer in pkt else pd.NA
                           for pkt in packets_list]
                   for layer, field_list in fields.items()
                   for field in field_list})


text:
Q: 77062:77062:0921/091821.489365:ERROR:browser_main_loop.cc(1417) Unable to open X display My Server CentOS 7.7 is located in HongKong.
I started the minikube success:
[dele@att root]$ minikube start --driver=docker --registry-mirror=https://registry-mirror.com

when I run dashboard, there get error:
[dele@att root]$ minikube dashboard
  verifying dashboard state...
  Launching proxy ...
  verifying proxy state ...
  Opening http://127.0.0.1:38441/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/ in your default browser...
START /usr/bin/google-chrome-stable "http://127.0.0.1:38441/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/"
[77062:77062:0921/091821.489365:ERROR:browser_main_loop.cc(1417)] Unable to open X display.
[0921/091821.528962:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!
Most likely you need to configure your SUID sandbox correctly
xdg-open: no method available for opening 'http://127.0.0.1:38441/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/'

❌  Exiting due to HOST_BROWSER: failed to open browser: exit status 3

how to solve this issue?

A: Looks like the issue is with root user. Can try the solution mentioned in here


text:
Q: SQLITE is extreme slow with ORDER BY I have a simple query like
SELECT * FROM "mytable" where col1="foo"

which resolves in around 0.5 seconds (approx. 100 results of approx 100'000 rows of a 700 MB database file)
However, as soon as I add ORDER BY it takes 120 seconds.
SELECT * FROM "mytable" where col1="foo" ORDER BY col2

Even when I limit the result like so
SELECT * FROM (SELECT * FROM "mytable" where col1="foo" LIMIT 1) ORDER BY col2

it takes 120 seconds although there's literally nothing to sort.
The only exception is if I sort with ORDER BY rowid (instead of ORDER BY col2), or when I do it like this (0.5 seconds):
SELECT * FROM "mytable" WHERE rowid IN (SELECT rowid FROM "mytable"  WHERE col1="foo") ORDER BY col2

I VACUUM'ed the DB and I checked the integrity of the DB (ok) and this problem persists.
I am using SQLite version: 3.7.7.1, the slowdowns appear both in phpLITEadmin and in my PHP code.
Edit
EXPLAIN QUERY PLAN SELECT * FROM "mytable" WHERE col1="foo"

selectid|order|from|detail
       0|    0|   0|SCAN TABLE mytable (~11345 rows)

EXPLAIN QUERY PLAN SELECT * FROM "mytable" WHERE col1="foo" ORDER BY col2

selectid|order|from|detail
       0|    0|   0|SEARCH TABLE mytable USING AUTOMATIC COVERING INDEX (col1=?) (~7 rows)
       0|    0|   0|USE TEMP B-TREE FOR ORDER BY

A: So it seems SQLite erroneously thinks it would be cheaper to build a temporary index (automatic covering index) to run your query instead of sorting in memory. Obviously building an index on 100,000 rows for every query isn't the most optimal query plan.
An obvious solution would be to add an index on the columns on which you want to perform querying/sorting.
CREATE INDEX col1_idx ON mytable (col1);
CREATE INDEX col2_idx ON mytable (col2);

A: We ran into a similar issue and adding a dummy computed value and using it for sorting resolved this 'bug':
SELECT *, (col2+0) AS col2_forSort FROM "mytable" where col1="foo" ORDER BY col2_forSort

or for string (which was not our case):
SELECT *, (col2 || "") AS col2_forSort FROM "mytable" where col1="foo" ORDER BY col2_forSort

YMMV...Good luck!


text:
Q: How do I get a MethodInfo for an overloaded static method? When I run:
MethodInfo m = typeof(Expression).GetMethod("Lambda", new Type[]{typeof(Expression), typeof(ParameterExpression[])});

I get:
System.Reflection.AmbiguousMatchException: Ambiguous match found.

This is in an effort to do this genericly (instead of knowing it's a string)
var newExpression = Expression.Lambda<Func<T, string>>(propertyExpression, parameters);
return entities.OrderBy(newExpression);

EDIT: Additional info:
running:
typeof(Expression).GetType().GetMethod("GetMethodCandidates", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(typeof(Expression),new object[]{"Lambda", BindingFlags.Static| BindingFlags.Public, CallingConventions.Standard,new Type[]{typeof(Expression), typeof(ParameterExpression).MakeArrayType()},false})

returns the array:
[0]: {System.Linq.Expressions.Expression`1[TDelegate] Lambda[TDelegate](System.Linq.Expressions.Expression, System.Linq.Expressions.ParameterExpression[])}
[1]: {System.Linq.Expressions.Expression`1[TDelegate] Lambda[TDelegate](System.Linq.Expressions.Expression, System.Collections.Generic.IEnumerable`1[System.Linq.Expressions.ParameterExpression])}
[2]: {System.Linq.Expressions.LambdaExpression Lambda(System.Linq.Expressions.Expression, System.Linq.Expressions.ParameterExpression[])}
[3]: {System.Linq.Expressions.LambdaExpression Lambda(System.Linq.Expressions.Expression, System.Collections.Generic.IEnumerable`1[System.Linq.Expressions.ParameterExpression])}

A: Unfortunately reflection was written before generics were made available and often doesn't support generic methods/classes well at all.
Similar questions to this have been asked (GetMethod for generic method) where the answer has been to get the candidate methods and pick the one you want from the collection of methods.


text:
Q: How to seed a table with a foreign key constraint laravel How can I seed my Comments table with comments.post_id as Foreign Key to post.id.
I have a Factory for the Comments table but not for the Post table.The Post table I populate manually so I can not link Factories.
I have a problem with adding a comment, because of the FK constraint. I insert a post.id manually, but don;t know how to let Laravel choose an id automatically.
Thanks in advance, Sam
CommentFactory

<?php

namespace Database\Factories;

use App\Models\Comment;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class CommentFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Comment::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
            'post_id'=> 38,
            'author' => $this->faker->name(),
            'comment' => $this->faker->realText(150),
            'approved' => 0,
        ];
    }
}

CommentSeeder

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

use App\Models\Comment;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CommentSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // factory(App\Comment::class, 25)->create();
        Comment::factory()->count(rand(1,5))->create();
    }
}

**Comment Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use HasFactory;

    protected $fillable = ['author','comment', 'post_id','approved'];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

}

**

A:  Post::all()->random()->id, always fetch any random post ID and assign it the comment.

<?php

namespace Database\Factories;

use App\Models\Comment;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class CommentFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Comment::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
            'post_id'=> Post::all()->random()->id, <---- try this.
            'author' => $this->faker->name(),
            'comment' => $this->faker->realText(150),
            'approved' => 0,
        ];
    }
}

A: I used pluck() to create an array with all post.id
$posts = Post::all()->pluck('id')->toArray();

and used randomElement() to pick a random id as a post_id
$post_id = $this->faker->randomElement($posts);

Many thanks for the suggestions!


text:
Q: Appium - Steps to use Appium Inspector with Android emulator on Windows I want to use the Appium Inspector on Windows 7.
I want to use it with the example Android app ApiDemo and the Android emulator.
My question is: What steps do have I to do, to make this work?
I have installed:

*

*Appium GUI

*Android Studio with Android SDK

*Java JDK

I have set the path variables.
I have configured an Android emulator by GUI.

*

*Do I have to install the app on this emulator?

*Do I have to build the app in a special way with Android Studio or can I simply use the delivered ApiDemo.apk for installation?

*Do I have to launch the emulator or is Appium Inspector doing this for me?

Thanks in advance!
Greets.
EDIT: This is what Android emulator is showing me.

Is this correct? Because nothing changes from here? What have I to do?

A: Appium installs and launches the app, all u need to give the path of the apk u have in ur machine and emulator name in the desired capabilities,activity name
if its for java , use this code, to launch the app
public class sample{
    protected static AppiumDriver driver = null;

       private static DesiredCapabilities capa = null;

        public static void main(String[] args) {

            try{

                    File app = new File("D:/MobileAutomation/yourpath/appname.apk");

                    capa = new DesiredCapabilities();
                    capa.setCapability("automationName","Appium");
                    capa.setCapability("platformName","Android");
                    capa.setCapability("deviceName","Android Emulator");
                    capa.setCapability("platformVersion","5.1");
                    capa.setCapability("newCommandTimeout","30");
                    capa.setCapability("unicodeKeyboard", true);
                    capa.setCapability("resetKeyboard", true);
                    capa.setCapability("app", app.getAbsolutePath());
                    capa.setCapability("appPackage", "com.yourapppackage name");
                    capa.setCapability("appActivity", "com.yourappactivity name");

                    driver = new AndroidDriver(new URL("http://127.0.0.1:4731/wd/hub"), capa);

A: Suggestion : You can go through some tutorials and sample code on using appium for automation. Just to answer the listed questions inlined as follow :

Do I have to install the app on this emulator?

No : The sample code similar to the one as shared by @karthick23 would do that on its own.

Do I have to build the app in a special way with Android Studio or can
  I simply use the delivered ApiDemo.apk for installation?

Yes and No : You can simply use the delivered ApiDemo.apk but ensuring it is a debuggable build which would be helpful for you to get to know the details of the element you would be accessing while creating your automation suite.

Do I have to launch the emulator or is Appium Inspector doing this for me?

No : You wouldn't have to launch and emulator if you have specified the appropriate configurations of an AVD on appium GUI[which should be running as you execute your tests.]
Note : Ideally you provide some capabilities to the appium server via your code and some of them are set by default on your GUI, a merged combination of these helps you drive your tests.


text:
Q: Cant use Textbox.Select(0, 0) on textbox inside scrollviewer I cant use the code that'll set the CaretIndex before the first character.
Here is my XAML Code:
    <Border CornerRadius="5">
        <ScrollViewer x:Name="scDetailedText" Grid.Column="0" BorderBrush="Transparent" BorderThickness="0">
            <TextBox x:Name="ucDetailedText" Text="{Binding DetailsText}" Style="{StaticResource SearchDetailsTextStyle}" BorderBrush="Transparent" BorderThickness="0"/>
        </ScrollViewer>
    </Border>

And here is my Backend code:
void ucDetailedText_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    if (e.NewValue.Equals(true))
    {
        ucDetailedText.Focus();
        ucDetailedText.Select(0, 0);
    }
}

I've narrowed it down and it seems the style prevents the code.
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type TextBox}">
            <TextBox x:Name="PART_EditableTextBox" MinWidth="50" Width="{Binding TextWidth}" Padding="3" BorderBrush="Transparent"
                             VerticalAlignment="Center"  Background="Transparent"
                             **This line causes the problem** ~> Text="{Binding Text, RelativeSource={RelativeSource Mode=TemplatedParent}, UpdateSourceTrigger=PropertyChanged}"
                             HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"/>
        </ControlTemplate>
    </Setter.Value>
</Setter>

I've indicated below the cause, any thoughts why it happens?


text:
Q: Removing last record terraform state in a terraform workspace I am using terraform cloud workspaces.
By mistake, I upload the wrong terraform state to my workspace. Now my terraform plan is using it, but I don't want to use it since that is not the state I wanted to get.
Let me explain with this image: I want to use the state from 10 months ago and not the New State I got recently:

I want to go back to my old state since in the new one there are no some resources and then they are being recreated in my terraform plan.
I am trying to import every separate resource, by executing terraform import <RESOURCE-INSTANCE> <ID> command in this way:
terraform import azurerm_app_service_plan.fem-plan /subscriptions/d37e88d5-e443-4285-98c9-91bf40d514f9/resourceGroups/rhd-spec-prod-rhdhv-1mo5mz5r2o4f6/providers/Microsoft.Web/serverfarms/fem-plan-afd1
Acquiring state lock. This may take a few moments...
azurerm_app_service_plan.fem-plan: Importing from ID "/subscriptions/d37e88d5-e443-4285-98c9-91bf40d514f9/resourceGroups/rhd-spec-prod-rhdhv-1mo5mz5r2o4f6/providers/Microsoft.Web/serverfarms/fem-plan-afd1"...
azurerm_app_service_plan.fem-plan: Import prepared!
  Prepared azurerm_app_service_plan for import
azurerm_app_service_plan.fem-plan: Refreshing state... [id=/subscriptions/d37e88d5-e443-4285-98c9-91bf40d514f9/resourceGroups/rhd-spec-prod-rhdhv-1mo5mz5r2o4f6/providers/Microsoft.Web/serverfarms/fem-plan-afd1]

Error: Cannot import non-existent remote object

While attempting to import an existing object to
azurerm_app_service_plan.fem-plan, the provider detected that no object exists
with the given id. Only pre-existing objects can be imported; check that the
id is correct and that it is associated with the provider's configured region
or endpoint, or use "terraform apply" to create a new remote object for this
resource.

Releasing state lock. This may take a few moments...

But I got in the output, that resource does not exist, because terraform is using my latest New state where that resource is not included.
How can I use my old 10 months ago state?
If someone can point me out in the right path I will appreciate it.

A: Maybe you can use the command terraform refresh to update the state file to match the current state of the resources. You can get the details of the command here.


text:
Q: Ask for certificate with Laravel I would like to look for certificates on the browser of the user when the user go to my web.
It's a login in laravel and i dont know how to ask for a user certificate lo automatically login the user in Laravel(php).
I need to configure the server to require the certificate that should be install in the browser.
I would appreciate any information, Thanks!

A: @Kora
When user login one time than you can manage the cred store session and cookie then use that cred to log in the user automatically.


text:
Q: GDAL 3.4.1 build "Cannot create TIFF file due to missing codec for DEFLATE" I have built GDAL 3.4.1 on CentOS7.  Everything seems to be working except if I try to use DEFLATE compression and I get the error below.  I have installed libtiff-4.1.0 and libdeflate-1.10.  Previously I was running GDAL 2.3.2 using a similar build process with no issues with DEFLATE.
Can anyone suggest what I may be missing to get DEFLATE compression working?  Thanks!
gdal_translate -co COMPRESS=DEFLATE /cmake-3.19.5/Packaging/CMakeDMGBackground.tif test.tif
Input file size is 500, 365
Warning 6: 'DEFLATE' is an unexpected value for COMPRESS creation option of type string-select.
ERROR 1: Cannot create TIFF file due to missing codec for DEFLATE.

My GDAL build output shows:
checking for deflateInit_ in -lz... no
using internal libz code as deflateInit_ is missing
using internal libz code.
checking for libdeflate_zlib_decompress in -ldeflate... yes
checking libdeflate.h usability... yes
checking libdeflate.h presence... yes
checking for libdeflate.h... yes
...
  libdeflate support:        yes
  LIBGEOTIFF support:        internal
  LIBGIF support:            internal
  LIBJPEG support:           internal
  LIBLZMA support:           no
  LIBPNG support:            internal
  LIBTIFF support:           external (BigTIFF=yes)
  libxml2 support:           no
  LIBZ support:              internal

A: It turns out I did not have zlib installed.  Installing zlib fixed my issue.


text:
Q: How does player level and difficulty affect story mode gameplay? A story mission might have several difficulties, e.g., normal level 14, hard level 18, hard level 20, impossible level 24. What actually changes across these difficulties? Enemy health? Player health? Enemy weapon power? Drops and in-map vehicles? Experience and glimmer gain? The only difference I can see from the settings is that there is a greater XP bonus for finishing on a higher difficulty, but I don't know what that entails. What are the differences between story difficulty levels?
This is also to ask how player level affects story mode gameplay. I heard someone say that every level difference added/removed 20% of difficulty, but I couldn't verify this anywhere else.


text:
Q: tflite : is there any way for tflite to handle various shape of input I want to use MTCNN  for face detection in tflite ,it should be avilible for variable input shape like

both 1920*1080 or 640*360

but tflite must set input shape to a certain value ,is there any way to let tflite accept variable input or output shape ?
many thanks

A: If the model architecture supports variable input shape, you should be able to call the resizeInput API (Java) or ResizeInputTensor API (if you're using C++).
For example, in Java:
interpreter.resizeInput(tensor_index, [1, 1920, 1080, 3]);
interpreter.resizeInput(tensor_index, [1, 640, 360, 3]);

Note that many network architectures (e.g. MobileNet, Inception, ResNet...etc) don't support variable input shape.
If you're certain the model should support variable input shape and it doesn't work. Please file a Github issue or reply here.


text:
Q: Conditional probabilities from two data sets using software I am working on a project where I have two pieces of information for each individual $i$, $x_i$ and $y_i$. There are $n$ individuals in total.
I want to find the probability that $y_i \geq y_j$ given $x_i \geq x_j$, for all $1 \leq i, j \leq n$.
I feel doing it manually would not be possible and even undesirable, because the $n$ in my case is more than 100, but I do not know any way to let some software find this for me.
Is it possible in Microsoft Excel or IBM SPSS, as I usually use these two? If yes how? If no, where can I do this? I am currently learning the basics of R Studio and Python too.


text:
Q: Procedural collection operations into java stream or reactive stream How to transform this "old style" procedural java code into at least java 8 streams or reactive streams using Flux and Mono.
My goal is to achieve good foundations for using that code in concurrent non-blocking web environment.
I want to have a constant number of Elem elements in whole system and at the same time smaller or bigger number of places available for those elements.
Visually it might looks something like that for 8 elements, 12 places and 3 objects (containing each of them their own list of Elems):
s1 [Elem(1), Elem(2), Elem(3), Elem(4)]
s2 [Elem(5), Elem(6), Elem(7), Elem(8)]
s3 [FREE, FREE, FREE, FREE]
call for s1 requestElem()
call for s1 requestElem()
call for s2 requestElem()
s1 [Elem(1), Elem(2), FREE, FREE]
s2 [Elem(5), Elem(6), Elem(7), FREE]
s3 [FREE, FREE, FREE, FREE]
...and currently those three elements are waiting to be returned in random order...
call for s3 returnElem(4)
call for s3 returnElem(8)
call for s3 returnElem(2)
s1 [Elem(1), Elem(2), FREE, FREE]
s2 [Elem(5), Elem(6), Elem(7), FREE]
s3 [Elem(4), Elem(8), Elem(3), FREE]
Of course order of those operations might be different and randomly choosen.
class MyClass {
    private String name;
    private final int size = 4;     // size of s1, s2, s3
    private BlockingDeque<Elem> places;
    private int numOfElem;
    private BlockingDeque<Elem> additionalElems;

    public void requestElem() {
        if (numOfElem > size) {
            numOfElem--;
            additionalElems.pop();
            return;
        }
        if(!places.isEmpty()){
            places.pop();
            numOfElem = places.size();
        } else {
            System.out.println("empty: " + name + ", waiting for new elements...");
        }
    }

    public void returnElem(int id) {
        if (numOfElem >= size) {
            numOfElem++;
            additionalElems.push(new Elem(id));
            return;
        }
        if(places.size() < size){
            places.push(new Elem(id));
            numOfBicycles = places.size();
        }
    }

}

Is this possible? Can you provide me some useful tips or resources?


text:
Q: Generalized additive model I need help on how to interpret results for Generalised Additive Models(GAM) in R using the mgcv package. I have a dataset  called  flood which has a dependent variable called year (1985-2014) and the predictor variable  called deaths ( number of deaths from flood in each corresponding year) and is binary. If there was no death from a flood it is represented as 0 while if there was any death despite the number, it is represented as 1. I want to check whether the relationship between the two variables is linear or not. Here is the code.
    flood$deaths[flood$deaths==0]<-0
    flood$deaths[flood$deaths>0]<-1
    attach(flood)
    library(mgcv) he relationship
    gam1 = gam(deaths~s(year),family=binomial,data=flood)
    summary(gam1)

and the results :
    Family: binomial
    Link function: logit

    Formula:
    deaths ~ s(year)

    Parametric coefficients:
    a                                     Estimate Std. Error z value      P   pr(>|z|)
    (Intercept)  0.98706    0.03791   26.04   <2e-16 ***
              ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

    Approximate significance of smooth terms:
    edf Ref.df Chi.sq p-value
    s(year) 3.886  4.804  7.892   0.131

    R-sq.(adj) =  0.00188   Deviance explained = 0.252%
    UBRE = 0.17011  Scale est. = 1         n = 3527

how do i interpret the above results?


text:
Q: How to make whole textarea readable on using link..using jquery I have this code in my view..
Comment:
  <%=Html.TextAreaFor(model => model.Comment, new { })%>

The comment field is populating from a database. The text from the database is too long to fit in the visible area of the textarea. I have been asked to create a link next to the text area that, when clicked, would display the entire contents of the textarea in a 'popup bubble'.
Is this possible using jQuery?

A: Lets break your problem up into two parts; get the value from the textarea and display the value in a tooltip.
Using the current stackoverflow "Your Answer" form as a sample form, start entering a new answer and then run this in your browser's console:
$("#wmd-input").val()

For me it looks a little something like this right now:

"Lets break your problem up ...

Now you have to decide how to display your tooltip with one of the many available options (or just roll your own).

A: Something like this should do the trick
See it on jsFiddle http://jsfiddle.net/GmBqy/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <textarea id="myTextField">It is a long established fact that
  a reader will be distracted by the readable content of a page
  when looking at its layout. The point of using Lorem Ipsum is
  that it has a more-or-less normal distribution of letters, as
  opposed to using 'Content here, content here', making it look.
  </textarea>
  View Contents

A: yes, it is in fact possible.

A: You could create another property on your model for the shortened comment text and then store the full comment text in a hidden span.
Here is an example to get you started:

Comment:
  <%=Html.TextAreaFor(model => model.CommentShortened, new { })%>
  More...
  <%=Html.TextAreaFor(model => model.Comment, new { })%>


text:
Q: antiderivative around inverse trigonometric function I'm just learning about antiderivative that resulted some inverse trigonometric functions, since derivative of $ \arccos (x)$ is $-\frac {1} {\sqrt{1-x^2}}$.
I tried put this value back into integral calculator, but I got $- \arcsin (x)$ instead of $ \arccos (x)$. even though $-\arcsin (x) \neq \arccos (x)$ so why this happen? Kow should I fix my understanding?

A: That's because
$$
\arcsin(x)+\arccos(x) = \frac{\pi }{2}
$$
and $\pi/2$ is a constant.
When integrating, always remember that there's a constant $C$ in the result.

A: $$
\arccos(x) = \frac{\pi }{2}-\arcsin(x)\implies
(\arccos(x))' =-(\arcsin(x))'
$$


text:
Q: Origin and name for horizontal line hiding date or place name Does anyone know a) the origins, or b) the name of the convention of replacing dates or place names in 18th / 19th century novels with a horizontal line? I'm not asking for the reasons authors did this, (various answers are given here), but as it were the genealogy of its use.
An example, from Laurence Sterne's marvellous Tristram Shandy:

My father, you must know, who was originally a Turky merchant, but had
  left off business for some years, in order to retire to, and die upon,
  his paternal estate in the county of ------ , was, I believe, one of
  the most regular men in every thing he did, whether 'twas matter of
  business, or matter of amusement, that ever lived.

[EDIT:] The word is not "redaction", as some have suggested (see the comment below and those on the linked question above). Redaction means (quoting the OED, 'redaction', section 1.b):

b. The action or process of revising or editing text, esp. in
  preparation for publication; (also) an act of editorial revision.

What I am referring to is at best an act of simulated redaction by the author. It is not the editor's work, but the author's. I just wonder whether there exists a literary term  for this kind of simulated redaction.


text:
Q: Best way to slice a string that is stored in an object I am trying to slice a string that is stored in an object, but I am getting an error because I believe you cant use .slice() on values stored in an object.
paidData.id contains the id of the invoice and is a string, which I have confirmed with typeof

function paidCard(paidData) {

    // Converting epoch seconds to human readable date
    const invoiceDue = moment.unix(data.due_date);
    const invoiceDueConverted = invoiceDue.format(' MMMM Do YYYY');

    // Executing the function to convert amout due.
    const amountDue = decimalInsert(data.amount_due);
      const test = paidData.id; // <--- Logged this to console and it exists
      const result = test.slice(5) // <--- Cant read properties of undefined error here

    // Shows a notification when data from database has been loaded
    return(
      <InvoiceCard
      paid={true}
      invoiceStatusIconContainerColor='rgba(2,49,7,0.7)'
      invoiceStatusIconColor='#29DA7A'
      invoiceStatusText={paidData.status}
      customerName={paidData.customer_name}
      invoiceId={paidData.id}
      invoiceIdTextColor='#5C5C5C'
      customerEmail={paidData.customer_email}
      customerAddress={paidData.customer_address}
      invoiceAmount={amountDue}
      invoiceDateIconStatusColor='#FA3C3C'
      invoiceDateText={invoiceDueConverted}
    />
    );
  };
  let invoiceData = []
  let paidInvoiceData = []

  // Render the invoices by mapping through state.
  if(data && paidData && Array.isArray(data) && Array.isArray(paidData)) {
     invoiceData = data.map(card);
     paidInvoiceData =  paidData.map(paidCard);

Error I am getting
TypeError: Cannot read properties of undefined (reading 'slice')

A: It doesn't matter where the string is located (in an array, in an object, or in a variable). You can slice it normally:
var object = {id: '12345'};
console.log(object.id.slice(0,3)); // returns 123

A: You can call the .slice() method on any string, even if it is stored in an object. For example, this would be valid JS code:
const obj = { str: "StackOverflow is good" }
console.log(str.slice(0,12)) // "StackOverflow"

However, .slice() does not mutate the string it was called on. JS does not provide a .splice() (mutating) for strings, so you'll have to polyfill it. Check out this question  for a good polyfill.


text:
Q: Is the ".get()" function considered as a request? Im using parse cloud code and I need to use get() function in a recursive metohd.
Considering the pricing plan of Parse, which based on number of requests to the server, I need to check if every time I'm using the get method, its calculated as a individual request.
var query = new Parse.Query("User")
    query.limit(1000);
    query.find(
        {
            success: function (results)
             for (var j = 0 ; j < results.length ; j++)
                {
                  if(results[j].get("username").indexOf(shortNumberArray[i]) > - 1)
                       {
                           break;
                       }
                }
        });

if it is considered as individual request, are there any alternatives for this method?

A: No, getting a property on a Parse object does not make an HTTP request. If the property is a Pointer to another object and you need a property on that object, then use the Parse.Query.include() method to include the full object on your query.
To illustrate, make this the first line in your success function:
console.log(results);

Update: If the username is all you're after, then use pluck in underscore (or lodash):
_ = require('underscore');

...
    success: function (results) {
        usernamesArray = _.pluck(results, 'username');


text:
Q: Simple jQuery variable issue - conflicting variables I am trying to use this great jQuery text slider here: http://codepen.io/mikedevelops/pen/eNjeJm
But I really need two sliders on the same page. I have attempted to duplicate the code and change the variable names in the second slider to prevent there being an issue - but can't seem to get it to work. Here is my attempt, with the jquery below: http://codepen.io/hardanger/pen/NqmOom
Just to be clear, I think it is an issue with variables.
// add as many adjectives as you like!
var adjs = ["very cool", "really exciting", " super awesome", "jQuery sliding"],
sentence = $('#sentence'),
adjList = $('#adjList'),
stop = false;

    // function to return the most up-to-date
    // version of our adjective list
    function getList() {
       return $('.adj');
    }

    // function to build the adjective list
    // args: adjective array
    function build(arr) {
       for (i=0; i<arr.length; i++) {
          var item = "
";
          $(adjList).append(item + arr[i] + "
");
       }
    }

    // function to resize adjective list
    // args: adjective list item
    function resize(el) {
       $(adjList).animate({
          width: $(el).width(),
       }, 200);
    }

    // function to add slide-in transition
    // args: element that needs to slide
    function slideIn(el) {
       // duration slide is on screen
       var hold = 1000;
       // resize area to sliding element
       resize($(el));
       // add slide-in class
       $(el).addClass('slide-in');
       // after 'hold' duration slide-out current item
       // then slide in next item
       setTimeout(function(){
          // check to see if loop should continue
          if (stop === true) {
             stop = false;
             return;
          }
          // slide current element out
          slideOut(el);
          // slide in next element in queue
          slideIn($(el).next());
}, hold);
    }

    // function to add slide-out transition
    // args: element that needs to slide
    function slideOut(el) {
// remove current class and add slide-out transition
$(el).removeClass('slide-in').addClass('slide-out');
// wait for slide tramsition to finish then
// call 'change' function
setTimeout(function(){
    change();
}, 200);
    }

    // function to re-arrange adjective list
    function change() {
// store last item index
var i = adjs.length - 1;
// detach element that has slide-out class
// put to the bottom of the list after
// the last item
$('.adj:eq(' + i + ')').after($('.slide-out').detach());
// remove class to send element back to original position
$('.adj').removeClass('slide-out');
    }

    // build slider
    build(adjs);
    // init loop
    slideIn(getList()[0]);

    // second slider

    // add as many adjectives as you like!
    var adjs2 = ["test", "test", " testtesttesttesttesttest", "test"],
sentence2 = $('#sentence2'),
adjList2 = $('#adjList2'),
stop = false;

    // function to return the most up-to-date
    // version of our adjective list
    function getList2() {
return $('.adj2');
    }

    // function to build the adjective list
    // args: adjective array
    function build(arr2) {
for (i2=0; i2<arr2.length; i2++) {
    var item2 = "
";
    $(adjList2).append(item2 + arr2[i2] + "
");
}
    }

    // function to resize adjective list
    // args: adjective list item
    function resize(el2) {
$(adjList2).animate({
    width: $(el2).width(),
}, 200);
    }

    // function to add slide-in transition
    // args: element that needs to slide
    function slideIn2(el2) {
// duration slide is on screen
var hold2 = 1000;
// resize area to sliding element
resize($(el2));
// add slide-in class
$(el2).addClass('slide-in2');
// after 'hold' duration slide-out current item
// then slide in next item
setTimeout(function(){
    // check to see if loop should continue
    if (stop === true) {
        stop = false;
        return;
    }
    // slide current element out
    slideOut2(el2);
    // slide in next element in queue
    slideIn2($(el2).next());
}, hold2);
    }

    // function to add slide-out transition
    // args: element that needs to slide
    function slideOut2(el2) {
// remove current class and add slide-out transition
$(el2).removeClass('slide-in2').addClass('slide-out2');
// wait for slide tramsition to finish then
// call 'change' function
setTimeout(function(){
    change();
}, 200);
    }

    // function to re-arrange adjective list
    function change() {
// store last item index
var i2 = adjs2.length - 1;
// detach element that has slide-out class
// put to the bottom of the list after
// the last item
$('.adj2:eq(' + i2 + ')').after($('.slide-out2').detach());
// remove class to send element back to original position
$('.adj2').removeClass('slide-out2');
    }

    // build slider
    build(adjs2);
    // init loop
    slideIn2(getList2()[0]);

A: There are many ways to encapslate the code. A good pattern in this case would be as a jQuery plugin. The key to proper encapsulation is to remove global references in order to isolate the code and inject whatever the code needs to operate.
Global references can be tricky because they can come in many forms. In this case, the original code you linked in your question contains references to global variables in the JavaScript (e.g., the adjs array) and specific DOM elements by ID and class (e.g., $('#adjList') and $('.slide-out')). You have to be careful with classes because when you select by class, you get all the elements on the page with that class. This is a problem for the original code because you only want a subset of the elements with that class.
The style sheet can have a problem with global references as well. In the original code, the style sheet was using IDs to style the elements, which means there could only be one of the element on the page. You really want to use classes that can be applied to multiple elements.
The most basic things that the JavaScript code really needs to know about is the DOM element in which the text will be swapped (
), and the list of texts to be swapped. The call to a jQuery plugin for this would look something like this:
$('#adjList').textSlider(adjs);

I made a somewhat hacked up but functional jQuery plugin from the original code here:
http://codepen.io/anon/pen/JdVVje
The main changes were to wrap the appropriate code as a plugin, fix the ID references in the style sheet, and fix the style references in the JavaScript code. As you can see, there are two working text sliders on the page now.


text:
Q: The Secret World Combat Table In comparison to other games the combat table in the Secret World seems to differ in many ways. So far it appears to be built up of the following possible outcomes to each attack:

*

*Evade (miss)

*Block

*Glancing

*Hit

*Critical Hit

*Penetrative Hit

However, I've also seen instances of multiple of these effects that I would not expect to see together occur, for example a "Glancing Penetration" or a "Critical Block" which do not seem to make sense.
Has anybody else put any thought into the way the combat table in the Secret World works and if so do we have any ideas on this yet?

A: There is a very good FAQ about The Secret World that has a nice section about combat mechanics. I think the part that would be of interest to you is this section from the 'Hit roll order' part of it all (And is where the link above will take you directly to).

There are five rolls in the following order for every hit. Even for each individual "tick" of a multi-hit attack (Burst, Frenzy, Focus, and Chain)

*

*Evaded? (If yes, stop here)

*Glancing? (If yes, skip the Crit roll)

*Critical?

*Blocked? (If yes, skip the Penetration roll)

*Penetrated?

This will give you all of the possible effects that can be combined and hold up to the combinations you mention in your post. The article goes on a bit explaining the information above but then also gives a nice break down of how these combinations can scale the damage as follows:

*

*Critical (positive-scaled damage) AND Penetrated (reduced by negative-scaled Protection)

*roughly equal damage:

*

*Critical (positive-scaled damage and reduced by non-scaled Protection)

*Penetrated (non-scaled damage and reduced by negative-scaled Protection)

*Critical (positive-scaled damage) AND Blocked (reduced by positive-scaled Protection)

*Normal (non-scaled damage and reduced by non-scaled Protection)

*Blocked (non-scaled damage and reduced by positive-scaled Protection)

*Glancing (negative-scaled damage) AND Penetrated (reduced by negative-scaled > - Protection)

*Glancing (negative-scaled damage and reduced by non-scaled Protection)

*Glancing (negative-scaled damage) AND Blocked (reduced by positive-scaled Protection)

*Evaded (0 damage)

Now the article does go on to say that this is not the predominant conversation in this area on the forums and such but in my own playing this information has appeared to be fairly accurate to me. I will admit I am unaware of the information on the forums and such.


text:
Q: Date inputs cannot be aligned right on iOS7 tl;dr, Here the test, iOS7 can't right-align date inputs: http://cdpn.io/dxjHy
Consider this HTML:
<input type="date" id="test">

And this CSS:
#test {
  -webkit-appearance:none;
  -moz-appearance:none;
  appearance:none;

  text-align:right;
  padding:30px;
  width:400px;
  font-size:20px;
}

Safari on iOS7 doesn't want to right-align the text in the date input. My opinion is that Chrome's interpretation is the correct one. Any ideas on how to make Safari cooperate?
Chrome 30:

Safari Mobile on iOS7, iPad:

A: I've found a solution that works great. This seems to be the culprit, in Safari's stylesheet of input[type=date]
display: -webkit-inline-flex;

Add this to your CSS...
input[type=date] {
    display:block;
    -webkit-appearance:button;
    -moz-appearance:button;
    appearance:button;
}

...and now your input will be able to understand text-align:right; correctly.

A: We had the same problem in my office, we made a workaround.
<div>
    <input type="date" id="test">
</div>

and for the css
div{
    position:relative;
    width:100%
}
input[type="date"]{
    position:absolute;
    width:auto;
    right:0;
}

Hope, it can help you.

A: Using Hoshibe css trick did help but had to Add "left: 0;" to center the input box and not have overflow.
div{
    position:relative;
    width: 99%; <!--Can be any width you need.-->
}
input[type="date"]{
    position:absolute;
    width:auto;
    right:0;
    left: 0;
}

Then Adding below code to input[type="date"] will right align the text.
text-align: right;
display: block;

This fixed the issue in iOS 7 and 8.


text:
Q: Azure Devops requiring password every time I push from local to remote repository Relatively new git and azure-devops user here.
I am currently working on a project locally that I wish to push to my private azure-devops repository called 'Hello_World'.
So locally, I did the following:
git remote add origin https://dkennetz@dev.azure.com/dkennetz/Hello_World/_git/Hello_World

Then I wanted to push all my local code to the remote repo, so I simply did:
git push -u origin --all

and I was prompted:
[dkennetz@nodecn204  Hello_World]$ git push -u origin --all
Password for 'https://dkennetz@dev.azure.com':

Which is fine. I entered the token the first time and I thought all things would be handled accordingly for future pushes. I was wrong. Every time after this, I still have to enter my password for pushes.
I am doing this as a simple test case to try out azure-devops but I can see this becoming a serious issue if each user in a project has to enter username and password for CI/CD every time a user wants to push code to a repo.
I thought maybe I could add something to my config to handle this, but I am not sure.
If I run:
git config --list

I get (the space is because of code formatting issues):
user.name=Dennis Kennetz
user.email=funkyman@funky.org
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true

remote.origin.url=https://dkennetz@dev.azure.com/dkennetz/Hello_World/_git/Hello_World
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master

Thanks for the help!

A: After spending some time on this, I have found a solution that works for me (although it stores your token in plain text in your git credentials).
prior to pushing to your repo, enter the following:
git config --global credential.helper 'cache --timeout=3600'

This will store any usernames and passwords in your config for 3600 seconds before dumping. You can modify the time in timeout to the length of your session, or just leave off timeout for indefinite storage.
This way, you only have to type in your token once, and it will store until the time duration is reached, at which point you will have to type it again.


text:
Q: Wrap element(s) with a new tag determined by the total of their attribute values When transforming the following XML instance;
source.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<indd xmlns:aid="http://ns.adobe.com/AdobeInDesign/4.0/" xmlns:aid5="http://ns.adobe.com/AdobeInDesign/5.0/">

      <cell aid:theader="" aid:ccols="3">Head A</cell>
      <cell aid:theader="" aid:ccols="1">Head B</cell>
      <cell aid:ccols="2">A</cell>
      <cell aid:ccols="1">B</cell>
      <cell aid:ccols="1">C</cell>
      <cell aid:ccols="4"></cell>
      <cell aid:ccols="1">E</cell>
      <cell aid:ccols="1">F</cell>
      <cell aid:ccols="1">G</cell>
      <cell aid:ccols="1">H</cell>
      <cell aid:ccols="1">I</cell>
      <cell aid:ccols="1">J</cell>
      <cell aid:ccols="1">K</cell>
      <cell aid:ccols="1">L</cell>
      <cell aid:ccols="1">M</cell>
      <cell aid:ccols="1">N</cell>
      <cell aid:ccols="1">O</cell>
      <cell aid:ccols="1">P</cell>
      <cell aid:ccols="1">Q</cell>
      <cell aid:ccols="1">R</cell>
      <cell aid:ccols="1">S</cell>
      <cell aid:ccols="1">T</cell>
      <cell aid:ccols="1">U</cell>
      <cell aid:ccols="1">V</cell>
      <cell aid:ccols="1">W</cell>
      <cell aid:ccols="1">X</cell>
      <cell aid:ccols="1">Y</cell>
      <cell aid:ccols="3">Z</cell>

</indd>

using the following XSLT (1.0);
transform.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:aid="http://ns.adobe.com/AdobeInDesign/4.0/"
  xmlns:aid5="http://ns.adobe.com/AdobeInDesign/5.0/"
  exclude-result-prefixes="aid aid5"
  version="1.0">

  <xsl:output method="xml" indent="yes" />
  <xsl:strip-space elements="*"/>

  <xsl:template match="indd/article/table[@aid5:tablestyle='my-table']">

      <xsl:attribute name="class">
        <xsl:value-of select="@aid5:tablestyle"/>
      </xsl:attribute>

      <xsl:for-each select="cell">
        <xsl:choose>
          <xsl:when test="@aid:theader=''">

              <xsl:attribute name="colspan">
                <xsl:value-of select="@aid:ccols"/>
              </xsl:attribute>
              <xsl:value-of select="."/>

          </xsl:when>
          <xsl:otherwise>

              <xsl:attribute name="colspan">
                <xsl:value-of select="@aid:ccols"/>
              </xsl:attribute>
              <xsl:value-of select="."/>

          </xsl:otherwise>
        </xsl:choose>
      </xsl:for-each>

  </xsl:template>

</xsl:stylesheet>

It produces the following output:
result.xml
<?xml version="1.0" encoding="UTF-8"?>

   Head A
   Head B
   A
   B
   C

   E
   F
   G
   H
   I
   J
   K
   L
   M
   N
   O
   P
   Q
   R
   S
   T
   U
   V
   W
   X
   Y
   Z

Desired Result
However, my requirement is the transform source.xml to produce the following:
wanted.xml
<?xml version="1.0" encoding="UTF-8"?>

    Head A
    Head B

    A
    B
    C

    E
    F
    G
    H

    I
    J
    K
    L

    M
    N
    O
    P

    Q
    R
    S
    T

    U
    V
    W
    X

    Y
    Z

Currently transform.xsl does not transform source.xml to include the necessary tr elements that are present in wanted.xml.
Question
Is it possible to use XSLT (1.0) to include the necessary tr elements as shown in wanted.xml?
As you can see, the values of the aid:ccols attributes for each cell element that is present in source.xml could be utilized to inform the transformation as to when the resultant th or td element(s) should be wrapped in tr elements. Essentially it's when consecutive aid:ccols values total 4 as per the value of the table elements aid:tcols="4" attribute in source.xml.
For example:

*

*Consider the first two cell elements at positions 1 and 2 in source.xml. Their total value of aid:ccols attributes is 4 (3 + 1), therefore their resulant th elements should be wrapped with an opening and closing tr tag.

*Consider cell elements in source.xml at positions 3,4, and 5. Their total value of aid:ccols attributes is 4 (2 + 1 + 1) therefore their resulant th elements should be wrapped with an opening and closing tr tag.

*Consider the cell element in source.xml at positions 6. Its aid:ccols value already totals 4 therefore its resultant th element should be wrapped with an opening and closing tr tag.

A: If I understand this correctly, you want to do something like:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:aid5="http://ns.adobe.com/AdobeInDesign/5.0/"
xmlns:aid="http://ns.adobe.com/AdobeInDesign/4.0/"
exclude-result-prefixes="aid5 aid">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="table">

            <xsl:for-each select="cell[@aid:theader]">

                    <xsl:value-of select="."/>

            </xsl:for-each>

        <xsl:call-template name="body">
            <xsl:with-param name="cells" select="cell[not(@aid:theader)]"/>
            <xsl:with-param name="target-width" select="@aid:tcols"/>
        </xsl:call-template>

</xsl:template>

<xsl:template name="body">
    <xsl:param name="cells"/>
    <xsl:param name="target-width"/>
    <xsl:param name="row" select="/.."/>
    <xsl:param name="width" select="0"/>
    <xsl:choose>
        <xsl:when test="$width >= $target-width">

                <xsl:for-each select="$row">

                        <xsl:value-of select="."/>

                </xsl:for-each>

            <xsl:call-template name="body">
                <xsl:with-param name="cells" select="$cells"/>
                <xsl:with-param name="target-width" select="$target-width"/>
                <xsl:with-param name="row" select="/.."/>
                <xsl:with-param name="width" select="0"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:when test="$cells">
            <xsl:variable name="cell" select="$cells[1]" />
            <xsl:call-template name="body">
                <xsl:with-param name="cells" select="$cells[position() > 1]"/>
                <xsl:with-param name="target-width" select="$target-width"/>
                <xsl:with-param name="row" select="$row | $cell"/>
                <xsl:with-param name="width" select="$width + $cell/@aid:ccols"/>
            </xsl:call-template>
        </xsl:when>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

Another possible approach is a technique known as "sibling recursion" (look it up). Though the basic principle is same.


text:
Q: passport.js Linkedin OAuth returns "cannot fetch user profile" I use the passport.js strategy passport-linkedin-oauth2 to make users of my system log in via linkedin.
They do get to the "sign in" page, where they fill in their email address and password, and "grant access" but when they do, they return to my callback page, where an error is shown: "Cannot fetch user profile".
Navigating to / or /phone works
this is my code:
const express = require('express');
const passport = require('passport');
const plinkedin = require('passport-linkedin-oauth2').Strategy;
const works = path.join(__dirname, 'works.html');
const worksnot = path.join(__dirname, 'worksnot.html');

passport.use(
    new plinkedin({
        clientID: clientID,
        clientSecret: clientSecret,
        callbackURL: "http://localhost:4000/auth/linkedin/callback",
        profileFields: [
            "id",
            "positions"
        ],
        scope: ['r_emailaddress', 'r_liteprofile', 'w_member_social'],
        passReqToCallback: true
    }, function(req, accessToken, refreshToken, profile, done) {
        console.log('a');
        process.nextTick(function() {
            console.log('something is working'); //is not logged
        });
    }));

const server = express()
    .get('/auth/linkedin', passport.authenticate('linkedin', {
        state: 'gekkeSTATE'
    }), function(req, res) {
        console.log('authenticate1')
    }) //is not logged
    .get('/auth/linkedin/callback', passport.authenticate('linkedin', {
        successRedirect: '/works',
        failureRedirect: '/worksnot'
    }, console.log('authenticate2'))) //is logged first
    .get('/works', (req, res) => res.sendFile(works))
    .get('/worksnot', (req, res) => res.sendFile(worksnot))
    .listen(4000);
console.log(4000) //is logged 2nd

I expected the user being directed to either /works or /worksnot, but instead, the user is directed to http://localhost:4000/auth/linkedin/callback?code=AQSIbPg5hakpi_HnHl1azUGnTASZkLoqUwAP9cL4zqPwKnGNT792KCC9Q52HLbGOAqKSwE20moJy9poijiMLtIpPCEQkN-ld53aigyHb5dUXr3ef3PGjLVsk6nxAqzcOYKt3HN95uJXahiCAXLSWIRO_BecK-EwwY4bOsWm6emLipn4muDnwtGPTfDI1Sg&state=gekkeSTATE, where they see "InternalOAuthError: failed to fetch user profile".
The console output:
authenticate2
4000

InternalOAuthError: failed to fetch user profile
    at _oauth2.get (C:\Users\Maarten\iCloudDrive\node_modules\passport-linkedin-oauth2\lib\oauth2.js:62:21)
    at passBackControl (C:\Users\Maarten\iCloudDrive\node_modules\oauth\lib\oauth2.js:132:9)
    at IncomingMessage.<anonymous> (C:\Users\Maarten\iCloudDrive\node_modules\oauth\lib\oauth2.js:157:7)
    at IncomingMessage.emit (events.js:187:15)
    at endReadableNT (_stream_readable.js:1094:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)


text:
Q: How to use the sheet name from cell in formula? I'm trying to reference another sheet in a formula based on a cell value.
I have a workbook with 3 sheets 'Formulas', 'Letters', and 'Numbers'. On the Formulas sheet cell B1 is a list of the sheet names ie: 'Letters' or 'Numbers'. Cell B2 is a list of values 1-4.
I want to use a formula in B4 to VLookup on the 'Letters' or 'Numbers' sheet based on what is selected in Cell B1, ie: the sheet name.
When I try to put the cell with sheet names in it in the Vlookup formula it opens a dialogue for me to pick a workbook.
=VLOOKUP(B2,'B1'!A1:B4,2,0)

A: I found the solution using INDIRECT() here:
For my example:
=VLOOKUP(B2,INDIRECT("'"&B1&"'!A1:B4"),2,0)

A: Be aware that INDIRECT() is volatile, i.e. it can slow down workbooks because it causes re-calculation after ANYTHING changes in the workbook.
If your sheet name is in cell B1, you can use a non-volatile approach with modern functions like IFS() or SWITCH().
=IFS(B1="Formulas",VLOOKUP(B2,Formulas!A1:B4,2,0),B1="Letters",VLOOKUP(B2,Letters!A1:B4,2,0),B1="Numbers",VLOOKUP(B2,Numbers!A1:B4,2,0))

=SWITCH(B1,"Formulas",VLOOKUP(B2,Formulas!A1:B4,2,0),"Letters",VLOOKUP(B2,Letters!A1:B4,2,0),"Numbers",VLOOKUP(B2,Numbers!A1:B4,2,0))

The setup is a bit more work, but in the long run, the workbook will make up for that by calculating faster.


text:
Q: Typescript extend module (augmentation) i want to extend a installed module (Mongoose) with my own class and function.
I wrote the function and class and they work fine.
Now i wanted to add them to the mongoose module.
So what i have now is this file:
mongoInstance.ts
import * as mg from 'mongoose'

class _Schema extends mg.Schema {
    constructor(definition?: mg.SchemaDefinition, options?: mg.SchemaOptions) {
        super(definition, options)
        this.addData()
    }
    private addData() {
        //do stuff
    }
}

function _limitedRequest(schema: mg.Schema, options = 200) {
    schema.pre("find", function (next) {
        this.limit(options)
        next()
    })
}

declare module 'mongoose' {
    export class _Schema extends Schema {
        constructor(definition?: SchemaDefinition, options?: SchemaOptions)
        private addData(): void
    }
    export function _limitedRequest(schema: Schema, options?: number): void
}

Now anywhere in my app i can do:
otherFile.ts
import * as mg from 'mongoose'
//doesnt work
var test1= new mg._Schema({})
//works
var test2= new mg.Schema({})

So VSCode suggests me my class, and IntellIsense works. But it seems there is no implementation of the class.
Webpack doesn´t throw any errors when compiling my code to bundle.js but when i try to run my bundle.js with node bundle.js it says: TypeError: mg._Schema is not a constructor

A: You will need 2 things:

*

*Extend the type definition of mongoose with a declaration file.

*Add functionality so the module matches its new definition.

mongoose.d.ts
Create a declaration file (*.d.ts) and include it in your project.
import * as mg from 'mongoose';

declare module 'mongoose' {
  export class _Schema extends mg.Schema {
    constructor(definition?: mg.SchemaDefinition, options?: mg.SchemaOptions);
  }

  export function _limitedRequest(schema: mg.Schema, options: number): void;
}

mongoose-instance.ts
Add the functionality you just declared.
import mg from 'mongoose';

mg._Schema = class extends mg.Schema {
    constructor(definition?: mg.SchemaDefinition, options?: mg.SchemaOptions) {
        super(definition, options)
        this.addData()
    }
    private addData() {
        //do stuff
    }
}

mg._limitedRequest = function _limitedRequest(schema: mg.Schema, options = 200) {
  schema.pre("find", function (next) {
      this.limit(options)
      next()
  })
}

export default mg;

consumer.ts
From now on, use your local version of mongoose.
import mongoose from '../path/to/mongoose-instance';

console.log(mongoose._Schema);

If you encounter any problems related to default imports, make sure to enable these two flags in your tsconfig.json: allowSyntheticDefaultImports and esModuleInterop.

A: Import it like this in mongoInstance.ts:
import mongoose from "mongoose";

Export class in mongoInstance.ts
export class _Schema extends mg.Schema { ...

And in your otherFile.ts
import { _Schema} from "./otherFile";


text:
Q: How to make my app stay login even after power-off on ipad? I created a web service application. I want my user to allways stay login after installition but i have no idea about how to do this. I save user informations in NSUserDefaults. Thank in Advance
EDIT I log into the server, user informations are firstly created on server and i sen Username&Password ect via a GET to the server. If this data sent in GET are the same with ones in server, the user will login into the application. Anything(content) of application comes from server after logging in.

A: NSString *savedUserName = [[NSUserDefaults standardUserDefaults] stringForKey:@"userName"];
NSString *savedUserPass = [[NSUserDefaults standardUserDefaults] stringForKey:@"userPass"];

if (savedUserName && savedUserPass){ // check for length as well
  //don't show login, create user with these credentials
}
else{
  [[NSUserDefaults standardUserDefaults] setObject:@"newUserName" forKey:@"userName"];
  [[NSUserDefaults standardUserDefaults] setObject:@"newUserPass" forKey:@"userPass"];
  //then show login for logging in as a new user
}

Don't forget to save nil or empty string when user logs out.


text:
Q: Is there a VBScript implementation of Markdown? Does anybody know a VBScript implementation of Markdown?
I want to use it in my webpages written in Classic ASP to convert Markdown markup to HTML.
UPDATE Jan 26: Nobody?

A: Just posting an answer to this since I was just looking and this is what comes up at the top of the search.
There is a jScript implementation (e.g. server side js) wrapped in a classic asp/vbScript class for converting markdown into HTML:
https://github.com/nagaozen/asp-xtreme-evolution/blob/master/lib/axe/classes/Parsers/markdown.asp


text:
Q: Automation error when getting ReadyState of InternetExplorer object I get two different errors on the same line. Sometimes this one:

Automation error: object invoked has disconnected from its clients

and sometimes:

the interface is unknown

Minimal code to reproduce error:
Sub mcve()
    Dim ie As Object
    Dim www As String
    Set ie = New InternetExplorerMedium
    www = "http://www.stackoverflow.com"
    ie.navigate www
    ie.Visible = False
    While ie.ReadyState <> 4    ' <~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs here
        DoEvents
    Wend
End Sub

This requires a reference: Tools > References... > Microsoft Internet Controls
The error occurs on While ie.ReadyState <> 4 the second time.  How do I fix this?

A: This is a duplicate of a previously asked question. The problem seems to be caused by Internet Explorer security settings - when switching between security zones, the current instance of IE is killed and a new instance is created, so your reference to the old process is no longer valid.
Some of the suggested solutions were:

*

*Change IE security settings. Uncheck "enable protected mode" on the Security tab of Internet Options.

*Navigate to the IP address directly instead of the URL. This is the one that fixed it for me. For example, ie.navigate "64.233.177.106" (Google's IP address)

*Set ie = New InternetExplorerMedium instead of New InternetExplorer. Or in your case, vice versa.

A: Instead of
Set ie = New InternetExplorerMedium

just use
Set ie = New InternetExplorer

or, for late binding:
Set ie = CreateObject("InternetExplorer.Application")

This makes the error go away.
I'm not sure why you would use InternetExplorerMedium in the first place. Quoting the small print in the documentation:

Remarks
Windows Internet Explorer 8. On Windows Vista, to create an instance of Internet Explorer running at a medium integrity level, pass CLSID_InternetExplorerMedium (defined in exdisp.idl) to CoCreateInstance. The resulting InternetExplorerMedium object supports the same events, methods, and properties as the InternetExplorer object.

Are you really using IE8 on Windows Vista, and do you really want "medium integrity level", whatever that means? I didn't think so.

A: Open Internet Explorer, then, go to internet settings, open "Sites" ande clear the web page that need the server comprobation. The problema is for the server comprobation.


text:
Q: Not able to call values from feature file in Typescript implemented using Cucumber Framework Not able to call values from feature file in Typescript implemented using Cucumber Framework tool Protractor. How can i call these Examples values in my typescript method in When block.
Code for Feature file
Feature: Navigate to calculator site and add two number
Scenario: Add two number using calculator site
Given Navigate to calculator site url "cal"
When Provide two numbers to add first number  and
Then Click on add button on calculator site
Scenario Outline: Provide parameters
Examples:
| key1 | key2 |
| 2  | 3  |

|2    |60 |

Code of When block
When('Provide two numbers to add first number  and ', async (key1:string,key2:string)=> {
// Write code here that turns the phrase above into concrete actions

await cal.firstEditBox.sendKeys(key1);

await cal.secondEditBox.sendKeys(key2);

});
on Executing it is giving me Error

*

*Scenario: Add two number using calculator site # features\demo.feature:3
√ Given Navigate to calculator site url "cal" # stepDefinations\steps.ts:10
× When Provide two numbers to add first number  and  # stepDefinations\steps.ts:16
function has 2 arguments, should have 0 (if synchronous or returning a promise) or 1 (if accepting a callback)

*

*Then Click on add button on calculator site # stepDefinations\steps.ts:24

√ After # node_modules\protractor-cucumber-framework\lib\resultsCapturer.js:27

A: Feature: Navigate to calculator site and add two number
Scenario: Add two number using calculator site
Given Navigate to calculator site url "cal"
When Provide two numbers "<key1>" and "<key2>"
Then Click on add button on calculator site
Scenario Outline: Provide parameters

Examples:
| key1 | key2 |
| 2    |  3   |
| 2    | 60   |

When('Provide two numbers {string} and {string}', async (key1:string,key2:string)=> {

// Write code here that turns the phrase above into concrete actions

await cal.firstEditBox.sendKeys(key1);

await cal.secondEditBox.sendKeys(key2);
});


text:
Q: Django form error handling architecture In the clean method of my form class I am working with many different inputs from the billing, contact, and account sections of the form. As such there are many self.add_error statements and many fields that depend on other fields in order to validate.
I have noticed that after adding an error for a field I am unable to access that field any more. This is strange as you can add more than one error to a field, but that is not the issue.
I am seeing this method grow more complicated and unreadable, is there a good way to do this so the person that comes after me will understand it? I don't feel that the code ordering to prevent access after error is appropriate. My only thought is to set error variables in clean and call a different method at the end to add the errors to the fields.
Thanks
Edit: To add, I am only returning after clean has run in order to give the user all errors at once. I did not feel that returning after each found error was a good user experience

A: It's good practice to provide your code to help people see what you are doing. This includes your error reports/traceback info.  Use the markdown options to help make your post more readable.
I could be wrong but from my own experience, I usually clean each field individually as per the documentation unless they rely on each other such as passwords, etc.
you can read this part of the documentation to help get some clarity:
https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-a-specific-field-attribute


text:
Q: Remove the white screen a Slide window transition creates when it starts I am using an activity with a black background. That same activity has a toolbar and a DrawerLayout as well. This white screen makes the look inconsistent.
It can become more apparent when there is a very slow Slide transition when opening an activity.
Is there any way to remove this?
Code that sets the enter transition on the second activity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = activity.getWindow();

        Slide slide = new Slide();
        slide.setSlideEdge(Gravity.RIGHT);
        slide.excludeTarget(android.R.id.statusBarBackground, true);
        slide.excludeTarget(android.R.id.navigationBarBackground, true);
        window.setEnterTransition(slide);
        window.setExitTransition(slide);
    }

My styles
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:windowActivityTransitions">true</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">false</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowSoftInputMode">stateAlwaysHidden|adjustResize</item>
</style>

A: Seems like the old activity will not "stay" in view when you have a custom transition. I don't know when that started, but you definitely didn't need a stay animation in some previous API levels. The old 2.0 era overridePendingTransition still works fine:
anim/slide_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="100%"
        android:toXDelta="0%"
        android:duration="600"
        />
</set>

anim/slide_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="0%"
        android:toXDelta="100%"
        android:duration="600"
        />
</set>

anim/stay.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:duration="600"/>
</set>

Main activity's startActivity:
startActivity(intent);
overridePendingTransition(
        R.anim.slide_in,
        R.anim.stay
);

Second activity's return:
@Override
public void onBackPressed() {
    super.onBackPressed();

    overridePendingTransition(
            0,
            R.anim.slide_out
    );
}

A: How to fix the white screen during the slide in transition for the started activity:
karaokyos answer utilizes the pre Lollipop
activity transitions. These transitions target the whole activity screen and don't provide capabilities to exclude parts of the screen during the transition.
John Ernest Guadalupe approach utilizes the transitions introduced in Lollipop (Activity & Fragment Transitions). The observed "white screen" is the window background, that is fading in during the transition (more info about Activity & Fragment Transitions ). I guess you are setting the "black background" of your activities in the root view of your layout? Setting the window background to black should solve your problem.
Programmatically:
window.setBackgroundDrawable(new ColorDrawable(Color.BLACK));

Theme:
<item name="android:windowBackground">@android:color/black</item>

This is the resulting transition.

Edit: How to provide the required slide out (left) transition for the calling activity
First Activity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    Slide slide = new Slide();
    slide.setInterpolator(new LinearInterpolator());
    slide.setSlideEdge(Gravity.LEFT);
    slide.excludeTarget(android.R.id.statusBarBackground, true);
    slide.excludeTarget(android.R.id.navigationBarBackground, true);
    window.setExitTransition(slide); // The Transition to use to move Views out of the scene when calling a new Activity.
    window.setReenterTransition(slide); // The Transition to use to move Views into the scene when reentering from a previously-started Activity.
    window.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
}

Second Activity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    Slide slide = new Slide();
    slide.setInterpolator(new LinearInterpolator());
    slide.setSlideEdge(Gravity.RIGHT);
    slide.excludeTarget(android.R.id.statusBarBackground, true);
    slide.excludeTarget(android.R.id.navigationBarBackground, true);
    window.setEnterTransition(slide); // The Transition to use to move Views into the initial Scene.
    window.setReturnTransition(slide); // The Transition to use to move Views out of the Scene when the Window is preparing to close.
    window.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
}

You can try different interpolators to change the pace of the transition.
Resulting transition with LinearInterpolator:

If you want to get rid of the gap between the slide out of the first and slide in of the second activity you can set:
<item name="android:windowAllowEnterTransitionOverlap">true</item>

How to debug transitions:

It can become a lot more apparent when you set a very slow duration to the Slide transition when opening an activity.

To (visually) debug transitions there are 3 options ("Window animation scale","Transition animation scale", "Animation duration scale") in the development settings to multiply the duration of all transitions/animations.

A: I also had this problem but with fragment transitions and since all the solutions that came up were just setting the window background which probably works with activities I wasn't really getting anywhere. Than I thought => let's just try to set the background of rootview in the fragment I'm pushing in to transparent.. And voila, this did the trick. So the rootview of the fragment that I'm pushing looks like this in xml:
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent">

A: This is a little late, but I encountered the same thing myself, and found no answer for it in the internet.
The reason for the gap between the screens is that you call both an exit transition and an enter transition.
The exit transition happens as soon as you call startActivity, and the enter transition happens later, after the onCreate of the new activity.
Therefore, the order of events will be:

*

*Activity A exits

*Wait for activity B to finish loading

*Activity B enters

For me the solution was to simply remove the exit transition. The outcome looks pretty much the same, and the lack of the exit transition is barely noticeable as a new activity slides over it.
After removing the exit transition, the time when there was a "white screen" is not seen because in that time Activity A is still present.


text:
Q: How do I see the most recent updates installed in Windows 8.1 in "installed updates"? Windows 8.1 "installed updates" is one of two confusingly similar screens that let you view installed updates. It is the only non-useless one, because you can actually uninstall from this one. However it seems that there is some mandatory category groups that can not be removed, like "Microsoft Windows" and "Microsoft Visual Studio 2010", and so on. Hundreds of these categories.  Clicking on the "installed on" column only sorts items within their existing groups, making the sort feature useless for finding what was installed on what day, as you now have to consult each of 200 "group" sections and you can only sort INSIDE the groups. How do I turn off this "grouping" feature within Installed Updates, or otherwise see the most recently installed updates, by date, across all the categories or groups?
There is an Organize button, which is tantalizing, but the Organize button contains no way to hide the category names.

How can I see the most recent day (today, yesterday, 3 days ago) that any update was installed regardless of categories that they are sorted permanently into?
Known Workaround: Use the otherwise worthless "View update history" window instead.  (Review your windows update history). Then obtain a piece of paper and a pen, and write down the meaningless 10 digit KB number, then go find the meaningless 10 digit number in the other screen, and remove it.

A: Organize -> Layout -> Check 'Menu Bar' so you can see File, Edit, View at the top... (or tap Alt)
View -> Group By -> None


text:
Q: renv::restore() error: failed to retrieve 'package' (using private package) I am intending to use the renv package in R to set up a global cache on a linux server, where other users would be able to: i) use the packages by creating symlinks to the renv library I created (and therefore save on memory and time by not installing it into their own private library), and ii) quickly switch between several versions of a package (depending on the project).
The goal is to be able to quickly reproduce a persons code, with no prior installations or discussions on the set-up. The only thing the person would need is a lock-file, set up his/her environment identically according to the respective lock-file using renv, and run/reproduce the code.
Consider the following example:
I finished with one project that uses public packages from CRAN and also a package developed by myself. I now create a shared/global cache by setting:
Sys.setenv(RENV_PATHS_CACHE = "/path/to/global/cache")

And run:
renv::init()

Which creates a folder with all packages as expected.
Nevertheless, if I want to test this by creating a new project, copying the renv.lock file into the new project folder, and then run
renv::restore()

It fails to retrieve the private package, because it tries to retrieve it from the CRAN repository:

Error: failed to retrieve package 'rmvtools'
In addition: Warning message:
could not retrieve available packages for url 'https://cran.rstudio.com/src/contrib'
Traceback (most recent calls last):
9: renv::restore()
8: renv_restore_run_actions(project, diff, current, lockfile, rebuild)
7: renv_retrieve(packages)
6: handler(package, renv_retrieve_impl(package))
5: renv_retrieve_impl(package)
4: renv_retrieve_unknown_source(record)
3: renv_retrieve_repos(record)
2: stopf("failed to retrieve package '%s'", record$Package)
1: stop(sprintf(fmt, ...), call. = call.)

How do I "force" renv::restore to create so-called symlinks directly from the global cache (and not the CRAN repository)?
My workaround for now is to set the RENV_PATHS_LOCAL variable to the same path as the global cache, and copy the private_package.tar.gz file to the global cache. Nevertheless, this should not be necessary, as I already have installed the package when setting up the global cache. With this workaround, the user has to use the .tar.gz file to install the private package into his own private renv-library (which is not a symlink in this case and stores a duplicate version for every user).

A: Normally, renv::restore() will find and use packages from the global cache if the requested package(s) can be found there, so I think the underlying question is to why renv is failing to resolve that package in the cache.
What does the entry for your package in renv.lock look like? Does it have a Hash field? Does that Hash field resolve to the correct location in the renv cache? This is the key that renv uses when attempting to resolve a package in the global cache.
You can use:
renv:::renv_cache_list(packages = "<package>")

to see the cache entries for a particular package.
The other option would be to set up a local R package repository, with your private package made available from that repository. This could even be a package repository on a network filesystem referenced with a file URI; e.g. something like:
options(repos = c(ORG = "file:///path/to/local/repository"))

The miniCRAN package may be useful in creating such repositories.
If none of this information suffices, I would recommend filing an issue at https://github.com/rstudio/renv/issues.


text:
Q: how to popup jframe from jmenubar I use jmenubar, and one of the option is about. I want to popup new window after click "about" and show some information. How to do that? Thanks for you help :)
I enclose my code.
public class Frame extends JFrame{
public Frame(){
    JFrame frame = new JFrame("Program");
    final JFrame window = new JFrame("About");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(700,700);
    window.setSize(200,200);
    frame.setLocation(50,50);
    window.setLocation(150,150);
    frame.setResizable(false);
    window.pack();
    frame.setVisible(true);

    JMenuBar menu = new JMenuBar();
    frame.setJMenuBar(menu);

    JMenu file = new JMenu("File");
    JMenuItem exit = new JMenuItem("Exit");
    exit.setMnemonic(KeyEvent.VK_C);
    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    file.add(exit);

    JMenu about = new JMenu("About");
    //oprogramie.setMnemonic(KeyEvent.VK_C);
    about.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //JOptionPane.showMessageDialog(null, "Your message goes here!","Message", JOptionPane.ERROR_MESSAGE);
            window.setVisible(true);
        }
    });

    menu.add(file);
    menu.add(about);
    }

}

A: Take a look at How to Make Dialogs
General advice would be to use a JOptionPane as it provides a ready made dialog into which you can display stuff, for example...

JOptionPane.showMessageDialog(null, "Hello world", "About", JOptionPane.INFORMATION_MESSAGE);

For more complex output, you can use <html> text or even a container/component of some kind, like a JPanel, with other components laid out the way you want them


text:
Q: (Re-) Generating a draggable line in Matlab GUI I am currently building up a functionality in a Matlab GUI whereby the user can change the plot displayed on the screen (via a pop-up menu.... this isn't the issue FYI!) and move a vertical line across the plot with the mouse (the x-data is returned from the position of this line). I have no issues creating this mouse-interactive line when the GUI is first generated, but cannot "re-generate" the user-interactive line once the user selects a different dataset from the pop-up menu.
I establish the draggable line using the following code in the opening function of the GUI:
handles.yline1 = line([x_start x_start],[y_min,y_max],'ButtonDownFcn',@(hObject,eventdata)postprocessingtry1('startdrag1_Fcn',hObject,eventdata,guidata(hObject)));

Where:
function startdrag1_Fcn(hObject, eventdata, handles)

set(handles.figure2,'WindowButtonMotionFcn',@(hObject,eventdata)postprocessingtry1('dragging1_Fcn',hObject,eventdata,guidata(hObject)));

...and "dragging1_Fcn" is the function that returns the x-position.
The error occurs once I try to use the same "handles.yline1 = ..." declaration within the popupmenu callback function:
Error using handle.handle/set Invalid or deleted object.
Error in postprocessingtry1>dragging1_Fcn (line 341)
set(handles.yline1,'XData',pt.CurrentPoint(1,1)*[1 1]);
Any advice as to how I can regenerate the user-interactive line after selecting and plotting a new dataset (via the pop-up menu) would be IMMENSELY appreciated.  Thinking about it now, I think maybe referencing hObject and eventdata within the pop-up menu callback function may have something to do with the issue... but I'm not sure!
Thank you for your time, Colin Waldo

A: Here is a function which does what you ask for, its a gui built 100% from code - hopefully you can get the idea from it and convert it to do what you want:
function demoVerticalLine
  % Create the variable which is required to know if the line move is active or not.
  mouseDown = false;
  % Create the first value for the xlimMode (used in callbacks)
  xLimMode = 'auto';
  % create a dialog, with the mouse actions set
  hFig = dialog ( 'windowstyle', 'normal', 'WindowButtonMotionFcn', @MouseMove, 'WindowButtonUpFcn', @MouseUp );
  % create an axes
  ax = axes ( 'parent', hFig, 'position', [0.1 0.2 0.8 0.7], 'nextplot', 'add' );
  % create a popup menu
  pop = uicontrol ( 'parent', hFig, 'style', 'popupmenu', 'string', { 'sin', 'cos' }, 'Callback', @UpdatePlot );
  % some dummy data
  x = -pi:0.01:pi;
  % an initial X for my example
  vLineX = randi(length(x));
  % On first time through create a plot
  userPlot = []; % init a value -> this is used to clear the previous user data
  UpdatePlot();
  % get the y limits of the data to be plotted
  ylim = get ( ax, 'ylim' );
  % plot the vertical line
  hLine = plot ( ax, [x(vLineX) x(vLineX)], ylim, 'ButtonDownFcn', @MouseDown );
  % a callback for plotting the user data
  function UpdatePlot ( obj, event )
    % delete any user data which is already plotted
    delete ( userPlot );
    % plot the user data
    switch get ( pop, 'value' )
      case 1 % sin
        userPlot = plot ( ax, x, sin(x), 'r.-' );
      case 2 % cos
        userPlot = plot ( ax, x, cos(x), 'b.-' );
    end
  end
  % a function which is called whenever the mouse is moved
  function MouseMove ( obj, event )
    % only run this section if the user has clicked on the line
    if mouseDown
      % get the current point on the axes
      cp = get ( ax, 'CurrentPoint' );
      % update the xdata of the line handle.
      set ( hLine, 'XData', [cp(1,1) cp(1,1)] );
    end
  end
  % callback from the user clicking on the line
  function MouseDown ( obj, event )
    % get the current xlimmode
    xLimMode = get ( ax, 'xlimMode' );
    % setting this makes the xlimits stay the same (comment out and test)
    set ( ax, 'xlimMode', 'manual' );
    % set the mouse down flag
    mouseDown = true;
  end
  % on mouse up
  function MouseUp ( obj, event )
    % reset the xlim mode once the moving stops
    set ( ax, 'xlimMode', xLimMode );
    % reset the mouse down flag.
    mouseDown = false;
  end
end


text:
Q: grunt no longer compiling and minifying my stuff I ran npm install && bower install with no hiccup. Now I am trying to compile my assets but I am getting the following error:
--- (master) $ grunt
Usage: grunt INPUT_FILE [options]

grunt: error: Input file not provided.

Here is my package.json that I used to install grunt...
{
  "name": "foundation-libsass-template",
  "version": "0.0.1",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "grunt-debian-package": "^0.1.9",
    "grunt-sass": "~0.8.0",
    "node-sass": "~0.7.0"
  }
}

I am running the grunt command from the same directory as my Gruntfile.js. Here is my Gruntfile.js:
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    sass: {
      options: {
        includePaths: ['bower_components/foundation/scss']
      },
      dist: {
        options: {
          outputStyle: 'compressed'
        },
        files: {
          'css/babynet.css': 'scss/babynet.scss',
          'css/epals2.css': 'scss/epals2.scss',
        }
      }
    },

    watch: {
      grunt: { files: ['Gruntfile.js'] },

      sass: {
        files: 'scss/**/*.scss',
        tasks: ['sass']
      }
    }
  });

  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('build', ['sass']);
  grunt.registerTask('default', ['build','watch']);
}

A: This answer is just speculation. The grunt: error: Input file not provided. error makes me wonder if an older grunt is being run and is looking for the older grunt.js file rather than Gruntfile.js.
Check the output of grunt --version, if it is a pre 0.4 release then the problem may be what I outlined above. From http://gruntjs.com/upgrading-from-0.3-to-0.4:

The "Gruntfile" has changed from grunt.js to Gruntfile.js.


text:
Q: Moving angular 2 application to apache server environtment make error I have create an angular 2 application using the angular-cli like as follow
ng new my-angualr-app

after thay I have build this application on the production mode
ng build --prod

the I got the dist folder.
Finally I move the folder to my apache servers var/www/html directory but the angular 2 application is not working fine.
I could not figureout the issue. Why this is not working. The application working fine on the production mode in local environment, while running the command ng serve --prod
The console error output is here

The Network tab shows 404 status. But the files are resides in the same directory

A: Instead of copying the dist folder, copy the contents of the dist folder, and make sure the base href is correct

A: I Think You are doing it in wrong way, I am sharing my way of doing-
First of all I use git for repository. So I push my angular2 code which was created by angular-cli. By default, The dist folder is not added in the repository. So I let it as it is.
After that, I clone my angular2 code in the production server in var/www/html and run the ng build --prod there. So, It creates the dist folder for the production server.
I think you can try in this way. It really works for me(in my several projects)


text:
Q: Wordpress feed error on syndication: "...URI is missing at line 1, column 48" Using multiple RSS Feed aggregators on WordPress, the are throwing an error on my feed:

"This XML document is invalid, likely due to invalid characters. XML
  error: SYSTEM or PUBLIC, the URI is missing at line 1, column 48"

Feed URL
I was using FeedWordPress plugin to syndicate between wordpress websites and then all of a sudden it started throwing this error. It appears to be a problem with the actual feed as different plugins throw the same error.
Note: the feed passes W3 Validation.
Can anyone spot what is causing the error?

A: The reason I was getting this error was because my original Feed was on the same domain as the website I was syndicating to:
Original Feed: http://website.com/offers/feed/
Website to syndicate to:  http://website.com/site1/
By moving the original feed to a different sub domain such as http://offers.website.com/feed/ fixed the issue.

A: This normally happens when the feed is showing invalid characters that haven't been escaped properly. The most common issue is with characters <,> and &
If it's passing the W3 validation then it's more likely to be the reader which is at fault


text:
Q: js stops working when adding multple functions in same js file I run into a bug/problem when I try the following...
This is the HTML file:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Mathe einfach geübt</title>
    <link rel="stylesheet" type="text/css" href="CSS/mathElements.css">

  <?php require("PHP/latex2htmlparser.php"); ?>

<input type="text" id="tobeformatted" value="">

<button type="button" id="activatebutton" onclick='transform()'>Click Me!</button>

JavaScript can change HTML content.

And this the js
alert("done");

function transform() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}

Until here it works (Alert happens and if the button is clicked the text changes)
but when I now add some more functions to the js file it stops working (no alert and no change of text:
alert("done");
function transform() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}

function frac() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}

function expo() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}

function index() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}

(the HTML is the same for both files)
Also I have noticed that there are some similar questions (Javascript stops working when I adapt another snippet inside and can more than one function be added in an external javascript file? i.e .js file?) around but they all got downvoted and closed and had no useful solution included. So if this question isn't asked clearly enough, please contact me and I will elaborate.

A: If you put your code into a snippet, it works - see below.
So I suppose the error must be caused by this script which you are including:

So I would search for errors there.

alert("done");
function transform() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}

function frac() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}

function expo() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}

function index() {
    document.getElementById("formattedexpression").innerHTML = "Paragraph changed.";
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Mathe einfach geübt</title>
    <link rel="stylesheet" type="text/css" href="CSS/mathElements.css">

  <?php require("PHP/latex2htmlparser.php"); ?>

<input type="text" id="tobeformatted" value="">

<button type="button" id="activatebutton" onclick='transform()'>Click Me!</button>

JavaScript can change HTML content.


text:
Q: Como posso verificar se existe um arquivo em uma URL com IdHttp? Preciso verificar se um determinado arquivo online é existente, se for retornar True, se não, False. Alguém pode ajudar?

A: Isso pode ser feito através de uma requisição HTTP com o método HEAD para solicitar informações de um determinado recurso, sem que o mesmo seja retornado.
Segundo a Wikipedia:

Variação do GET em que o recurso não é retornado. É usado para obter metainformações por meio do cabeçalho da resposta, sem ter que recuperar todo o conteúdo.

Relacionado: Quais são os métodos de requisição HTTP, e qual é a diferença entre eles?
Veja um exemplo:
// Uses: IdHTTP, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient;

function CheckFileOnlineExists(const OnlineFile: string; var Size: Int64): Boolean;
var
 IdHttp: TIdHTTP;
begin
try
  IdHttp := TIdHTTP.Create(nil);
  try
    IdHttp.Head(OnlineFile);
    Size := IdHttp.Response.ContentLength;
    if Size > 0 then
      Result := True
    else
      Result := False;
  except on E: EIdHTTPProtocolException do begin
    // Fazer algo aqui caso você queira tratar alguma exceção do IdHttp
  end;
  end;
finally
  IdHttp.Free;
end;
end;

O primeiro parâmetro da função CheckFileOnlineExists é o link do arquivo a ser verificado, e o segundo parâmetro é uma variável do tipo inteiro que vai receber o content-length da requisição (embora não tenha sido pedido na questão).
Exemplo de uso:
Const
 LINK = 'http://cdn.sstatic.net/br/img/apple-touch-icon.png?v=3958fdf06794';
Var
 FileStatus: Boolean;
 FileSize: Int64;
begin
 FileStatus := CheckFileOnlineExists(LINK, FileSize);

 if FileStatus then
   ShowMessage(Format('Arquivo existente! Tamanho em bytes %d.', [FileSize]))
 else
   ShowMessage('Esse arquivo não existe!');