text:
Q: Counting in Strings of an Array, JavaScript //Solved
I have an array with strings.
I need to count how many letters from every letter in the array are.
My function:
...
    for (var k=0; k<=arrB.length; k++) { //Index of the array
        for(var t=0; t<arrB.length; t++) {
            if(p==arrB[k[t]]){
    count++;
    }}
    }numb.push(count);
    }
    var inNumber;
    for(var q=0; q< numb.length; q++) {
    if(numb[q]>0) {
        var letterR=q+65; //Number in letter
        inNumber=String.fromCharCode(letteR);
    showResult(inNumber);
    showResult(numb[q]);
    ...

Why is my counter always 0?
Ill be thankful for every little help and advice. Thanks!

A: Split each string into an array of letters counting each occurrence along the way.
function countLetters(arr) {
    return arr.reduce(function (counts, str){
        str.split('').forEach(function (letter) {
            counts[letter] ? counts[letter]++ : counts[letter] = 1;
        });
        return counts;
    }, {});
};

// Example

var arr = ['ABC', 'BCD', 'CDE'];
console.log(countLetters(arr));
// Logs: Object {A: 1, B: 2, C: 3, D: 2, E: 1}

A: First of all in you example you have an object {} not an array - please fix that. Solution
var arr = ["ABC", "CAG", "ZXZ"];

var result = {};

arr.forEach(function(item) {
  for(var i = 0; i < item.length; i++) {
    var letter = item.charAt(i);

    if (!result[letter]) {
      result[letter] = 0;
    }

    result[letter] += 1;
  }

});

A: Counting letters in an array of strings should be pretty straight forward. For example, you could do this:

var arr=["ABC","CAG","ZXZ"];

var letterCount = arr.reduce(function(p,c) {
    for (var i=0; i < c.length; i++) {
        if (p[c[i]]) {
            p[c[i]]++;
        }
        else {
            p[c[i]] = 1;
        }
    }
    return p;
},{});

Which will give you an object letterCount that looks like this:
{
    "A": 2,
    "B": 1,
    "C": 2,
    "G": 1,
    "Z": 2,
    "X": 1
}

What you are doing is iterating through the array and for each string iterating through the string. For each letter you check an object (p) which is keyed off the letter. If the letter doesn't already exist in the object, you add it and set it's value to 1. If it does exist, you just increment it by one.


text:
Q: Execute animation while scroll down (Flutter web) I am creating a simple flutter web app where is created a top bar with some buttons on top bar.
When i click on any button the scroll animation works and the page scroll to that specific portion of the web.I also added slide animation to be play when scrolled to the position. you can see my previous question for getting idea of the previous work done by clicking the link.
Preview the last question related to this app
Now my question is that i want the same execution of slide animation when we scroll down using mouse as well as if we click on top-bar button.
Any little example how to solve this would be appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to switch to speaker when my headphone is plugged on Android I have to keep the Audio Speaker even if my headset is plugged into my device using AudioManager, but when wrote this code the AudioManager automatically switched to normal mode after 6 sec.
There is another way to do this on android 12?
public void onCreate() {
     m_amAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
     m_amAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
     if (android.os.Build.VERSION.SDK_INT \>= android.os.Build.VERSION_CODES.S) {
         setCommunicationDevice(AudioDeviceInfo.TYPE_WIRED_HEADSET);
     } else {
         m_amAudioManager.setSpeakerphoneOn(true);
     }
}

@RequiresApi(api = Build.VERSION_CODES.S)
public void setCommunicationDevice(Integer targetDeviceType) {
    List<AudioDeviceInfo> devices = m_amAudioManager.getAvailableCommunicationDevices();
    for (AudioDeviceInfo device: devices) {
        if (device.getType() == targetDeviceType) {
            boolean result = m_amAudioManager.setCommunicationDevice(device);
        }
    }
}


text:
Q: Saving model without writing to db in Django I have a many-to-many to many type models. I use a script to populate the database. However I want to print the objects and save it only if i want it to be saved using a y/n style input. The problem is I can't create the objects without saving them as you can see below.
>>> mov = Movie(name="completenothing")
>>> direc = Director(name="Someone")
>>> direc.movie_name.add(mov)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
    return self.related_manager_cls(instance)
  File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
    (instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Director: Someone>" needs to have a value for field "id" before this many-to-many relationship can be used.
>>> direc.save()
>>> direc.movie_name.add(mov)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add
    self._add_items(self.source_field_name, self.target_field_name, *objs)
  File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 1060, in _add_items
    (obj, self.instance._state.db, obj._state.db)
ValueError: Cannot add "<Movie: completenothing N/A>": instance is on database "default", value is on database "None"
>>> mov.save()
>>> direc.movie_name.add(mov)

Director and Movie are in a many-to-many relation and i want their information displayed before saving. Is there some mechanism to allow this ?

A: If you use a pre_save signal, you can try this.
from django.db.models.signals import pre_save

def confirm_save(sender, instance, **kwargs):

    # do something with your instance (display information)

    ans = input("Do you want to save(y/n)")

    if ans == 'y':
        print("Your instance saved successfully")

    else:
        raise Exception("Not saved")

pre_save.connect(confirm_save, sender=MyModel)


text:
Q: APP crashes when remove KVO observer I have a scroll view in controller. The scroll view has one subview. The subview is an observer of the scroll view at the same time. I remove the observer when subview's willMoveToSuperview: called. But when the controller dismissed, app crashed. Here are the sample codes:
@interface MyView : UIView

@property (nonatomic, weak) UIScrollView *scrollView;

@end

@implementation MyView

- (instancetype)initWithFrame:(CGRect)frame scrollView:(UIScrollView *)scrollView {
    self = [super initWithFrame:frame];
    if (self) {
        self.scrollView = scrollView;
        [scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];

    if (!newSuperview) {
        [self.scrollView removeObserver:self forKeyPath:@"contentOffset"];
        self.scrollView = nil;
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
}

@end

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:scrollView];

    MyView *view = [[MyView alloc] initWithFrame:CGRectMake(100, 200, 100, 100) scrollView:scrollView];
    [scrollView addSubview:view];
}

@end

When I print self.scrollView in willMoveToSuperview, it shows null. When I change the property scrollView in MyView to unsafe_unretained, app will not crash.
So I am confused. Why not weak scrollView work. Am I reading dangling pointer when scrollView is unsafe_unretained? Are there better solution to that situation?

A: The issue here is by the time willMoveToSuperview is called the scrollView weak pointer is already nil(deallocated).
But it think scrollView not completely deallocated(memory not released) thats why when you use unsafe_unretained reference to remove observer it works somehow. But it is a dangling pointer reference and you should not rely on that.


text:
Q: Replacing elements of a vector I have the following string:
string <- c("100 this is 100 test 100 string")

I would like to replace the 100's in the above string with elements of another vector:
replacement <- c(1000,2000,3000)

The first 100 of string should be replace by 1000, second 100 by 2000 and so on. The resulting string should look as follows:
result <- c("1000 this is 2000 test 3000 string")

Is there an efficient way to do this in R?
Thank you.
Ravi

A: one way:
> cs <- strsplit(string," ")[[1]]
> cs[cs == "100"] <- replacement
> cat(cs)
1000 this is 2000 test 3000 string

A: Not very elegant, but this should do..
string <- c("100 this is 100 test 100 string")
temp <- unlist(strsplit(string, split = "\\s+"))
replacement <- c(1000, 2000, 3000)
temp[temp == "100"] <- replacement
result <- paste(temp, collapse = " ")

result
## [1] "1000 this is 2000 test 3000 string"

A: Another way (need change replacement to a list):
string <- c("100 this is 100 test 100 string")
replacement <- list(1000, 2000, 3000)
result <- do.call(sprintf, c(gsub('100', '%d', string), replacement))

A: Late to the party, but regmatches has a regmatches(...) <- value assignment function which allows you to do this sort of thing cleanly in a one liner:
regmatches(string, gregexpr("100",string)) <- list(replacement)
string
# [1] "1000 this is 2000 test 3000 string"

If you don't want to overwrite your original string, you could call the function directly via:
`regmatches<-`(string, gregexpr("100",string), value=list(replacement))
#[1] "1000 this is 2000 test 3000 string"

A: Here is a way to do it with strsplit :
split <- unlist(strsplit(string, "100", fixed=TRUE))
split <- split[nchar(split) > 0]
paste0(replacement, split, collapse="")
# [1] "1000 this is 2000 test 3000 string"

The second line is here because strsplit add an empty string at the beginning of its results because 100 appears in the first position.

A: how about using sub and *apply
tail(sapply(replacement, function(x) {string <<- sub("\\b100\\b",x,string)}), 1)


text:
Q: Why is the browser complaining for import declarations position (js/vue/vitejs)? I've got a file like this:
import { createApp } from 'vue';
import router from './router'
import App from './App.vue';

createApp(App).use(router).mount('#products-category-app');

Does not contain any other row.
Still, when the broswer loads the compiled file (which properly starts with an import statement), I get this:

Uncaught SyntaxError: import declarations may only appear at top level
of a module

I'm currently compiling with Vitejs (thus rollup), pretty much basic/default options. The compiled file is something like this:
import{c as t,a as e,t as l,n as a,o as s,r as o,F as r,b as i,m as n,d as c,e as d,f as u,g as _,h as p,i as f,j as b}from"./vendor.13912ed1.js";const m={name:"ProductsTableColumn",props:["name","field_name","value","link","link_title"],computed:{classes()
[ETC..]

And here, there's only one import statement. So why is my browser complaining?


text:
Q: drag and drop in datatable not working on next second page correct position not updating in database I am using drag and drop jquery code for datatable. My drag and drop for row first(1) 10 recorders working correctly in datatable when move on next page second(2) it's not working correctly. On the second page of datatable row not drag and drop correctly and in database position column not updating correctly its make column position with value 1 on second page.
my problem now how to update position column in datatable on all pages first, second, third so on...
i have tried to change position with
$value['position'] = ('$pages_row * $page_size) + $key;

controller
  public function updatePositions() {
foreach ($_POST["value"] as $key => $value) {
     $data["position"] = $key; // i am unable to change position on next page
       $this->Athlete_classes->updatePosition($data,$value);
     }
echo "Sorting Done";
 }

model
function updatePosition($data,$id){
    if(array_key_exists("from", $data)){
        $data["from"]=$this->real_escape_string($data["from"]);
    }
    foreach ($data as $key => $value) {
        $value="'$value'";
        $updates[]="$key=$value";
    }
        $imploadAray =  implode(",", $updates);
                  $query=$this->db->query("Update dev_athlete_class SET $imploadAray Where id='$id'");
}

my html code is

                                <input type="checkbox" id="check-all" class="flat check_all" data-check="athlete_class_list" >
                               id
                                Position
                                From Time
                                To Time
                                Edit

                            <?php foreach ($data['Exercise_multiplier_datas'] as $key => $value) { ?>

                           <tr id="<?php echo $value["id"]; ?>">
                                    <input type="checkbox"    id="<?php echo $value['id']; ?>" class="flat athlete_class_list multiple_delete">
                                    <?php echo $value["id"]; ?>
                                    <?php echo $value["position"]; ?>
                                    <?php echo $value['from']; ?>
                                    <?php echo $value['to']; ?>

                                   <a href="#/pencil-square-o" class="edit_Athlete_class option_icon" data-json='<?php echo htmlspecialchars(json_encode($value, TRUE), ENT_QUOTES, 'UTF-8'); ?>'  data-block="school_form_block" data-form="school_form" >

                                  <input type="hidden" value="<?php echo $value["id"]; ?>" id="item" name="item">

                             <?php } ?>

my datatable is like that
on the sencod page its show position id 10 same id show
id | from    | to    | position
1    18:00    19:00      1
2    20:00    21:00      2
3    18:00    22:00      3
4    12:00    23:00      4
5    18:00    24:00      5
6    12:00    25:00      6
7    18:00    26:00      7
8    12:00    27:00      8
9    18:00    28:00      9
10   12:00    29:00      10
11   18:00    19:00      1
12   12:00    01:00      2

I want an actual result in datatable like this with current position id
id | from    | to    | position
1    18:00    19:00      1
2    20:00    21:00      2
3    18:00    22:00      3
4    12:00    23:00      4
5    18:00    24:00      5
6    12:00    25:00      6
7    18:00    26:00      7
8    12:00    27:00      8
9    18:00    28:00      9
10   12:00    29:00      10
11   18:00    19:00      11
12   12:00    01:00      12


text:
Q: Actionscript 3 : MovieClip control Hello I have a SWF clip that I got from a friend. the code looks like this:
[Embed(source="assets/gorilla_run.swf", mimeType="application/octet-stream")]private   var gorillaRun:Class;

public var loader:Loader = new Loader();
private var movie:MovieClip= new MovieClip;

loader.loadBytes(new gorillaRun());
movie.addChild(loader);

stage.addChild(movie);

I would like to access the frames of this movieclip so that I can control its action. There are many frames to this SWF however when I use this command:

trace(movie.totalframes);

I get "1" as my output.

A: You get number of frames in the container (movie). When you make this movie.addChild(loader);, you do not insert timeline from gorilla_run.swf to the movie. If you want to get total farmes try this:
trace(MovieClip(loader.contentLoaderInfo.content).totalFrames);


text:
Q: Generalized assignment I have a problem like this: there are Y people that need to be
assigned to no more than X sessions at different times according to
their availability, ensuring that no session contains more or less than a
given amount of people (Y/X +/- 20% for example).
The specific problem in which the number of people and the number of
sessions are the same seems to be the same as an assigmnent problem.
However, does anyone have an idea on how to solve this more genral
case?
I'm ok with both pseudo-algorithms or with suggestions on how to use
the GLPK. I could code this in perl or javascript.

A: I think you are referring to Generalized assignment problem. which fits into your case. The generalized assignment problem is NP-hard


text:
Q: ldifde command is failing with "Invalid Parameter: Bad argument '-i'. And also any equivalent PS Cmdlet? OS - Windows Server 2008 R2
Localhost: DC as well as running an AD LDS instance
Here are the command(s) I used:
ldifde -i -u -f differences.ldf -s localhost:50004 -b myUserAccount MyDomain MyPassword -j . -c "cn=Configuration, dc=X" #configurationNamingContext

ldifde -i -u -f differences.ldf -s localhost:50004  -j C:\Windows\ADAM\logs -c "cn=Configuration, dc=x" #configurationNamingContext

All of them failing and saying that '-i' is invalid parameter. But the documentation clearly says "-i" simply turns on import mode.
(please note my local host is DC as well as running a AD LDS instance at 50004 port. And also note that i can connect to the service instance with ASDI EDIT or ldp etc. admin utils)
Not sure what I am missing - I am just following this Step-by-Step guide, trying to understand how to sync AD DS users to my account. Not sure why it's too complex :)
Also, are there any PowerShell Cmdlet(s) to do the same - since I am a .NET developer, I can probably get used to the tools if it's cmdlets, I guess.
Any thoughts or help is appreciated :)

Please note the following Cmd is working fine:
C:\Windows\ADAM>ldifde -i -s localhost:50004 -c CN=Configuration,DC=X #Configura
tionNamingContext -f MS-AdamSchemaW2k3.ldf
Connecting to "localhost:50004"
Logging in as current user using SSPI
Importing directory from file "MS-AdamSchemaW2k3.ldf"
Loading entries.................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
.................................................................
1009 entries modified successfully.

The command has completed successfully

C:\Windows\ADAM>

Best Regards!


text:
Q: 'NSInvalidArgumentException', reason: 'keypath Patient.nachname not found in entity ' Why I am getting a NSInvalidArgumentException?
My table view controller code:
- (NSFetchedResultsController *)fetchedResultsController {

CoreDataHelper *cdh = [(MRMedSafeAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];

if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

NSFetchRequest  *fetchRequest = [[NSFetchRequest  alloc] init];
NSEntityDescription  *entity = [NSEntityDescription
                                entityForName:@"Patient" inManagedObjectContext:cdh.context];
[fetchRequest setEntity:entity];

NSSortDescriptor  *sort1 = [[NSSortDescriptor  alloc]
                            initWithKey:@"Patient.nachname" ascending:YES];
NSSortDescriptor  *sort2 = [[NSSortDescriptor  alloc]
                            initWithKey:@"Patient.vorname" ascending:YES];

[fetchRequest setSortDescriptors:[NSArray  arrayWithObjects:sort1, sort2, nil]];

[fetchRequest setFetchBatchSize:20];

NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                    managedObjectContext:cdh.context
                                      sectionNameKeyPath:nil
                                               cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;

return _fetchedResultsController;

}
My Patient.h:
@interface Patient : NSManagedObject
@property (nonatomic, retain) NSDate * geburtsdatum;
@property (nonatomic, retain) NSString * nachname;
@property (nonatomic, retain) NSString * vorname;
@property (nonatomic, retain) NSNumber * weiblich;
@end

My Patient.m:
#import "Patient.h"
@implementation Patient
@dynamic geburtsdatum;
@dynamic nachname;
@dynamic vorname;
@dynamic weiblich;
@end

Patient.h and Patient.h generated by XCode 5 out of the Model.xcdatamodeld file.
Why I am getting an exception?

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath Patient.nachname not found in entity '

Patient is the only class, there are no other model classes and no relationships in the model.

A: Just use "nachname" instead of "Patient.nachname" in
NSSortDescriptor  *sort1 = [[NSSortDescriptor  alloc]
                        initWithKey:@"Patient.nachname" ascending:YES];

I.e. it should read
NSSortDescriptor  *sort1 = [[NSSortDescriptor  alloc]
                        initWithKey:@"nachname" ascending:YES];

Likewise for the next sort descriptor and "vorname".


text:
Q: Is the JobScheduler API over engineering for an alarm clock app? So the job scheduler api is for tasks at a later time. It seems as if these tasks are meant to be like downloading from the internet at a certain time or whatever. I simply want to make an alarm clock app. Would this be over engineering?
What are the components necessary to activate and set an alarm at a later date? I want to be able to have my app set the alarm and activate it, not rely on another alarm clock app
edit:
according to http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html it seems as if alarmmanager is outdated and jobscheduler is its replacement?

A: It's not only overengineering, JobScheduler won't really work well in your case.
JobScheduler is good if you want to schedule some tasks for later, and these tasks require some additional resources - like network. Also, relying on JobScheduler won't work for pre-Lollipop devices (but you can use GcmNetworkManager from Google Play Services as a replacement).
In your case AlarmManager will be enough. It's not deprecated - just some usecases that were usually implemented using AlarmManager are currently better supported by JobScheduler (like recurring tasks that require WIFI in order to succeed). This is also what article that you linked says.
Summarizing:

*

*AlarmManager is usually more reliable in terms of timing. Your code can run as the exact time you scheduled it to run. Sounds like a pretty important thing for an alarm app, huh?

*AlarmManager doesn't know anything about the state of a device - it's not a right choice if you want to perform some tasks in the future and they rely on a working Internet connection. JobScheduler covers that - but that's not your case.

*JobScheduler works on Android 5.0 and newer (but you can use GcmNetworkManager from Google Play Services as a replacement, in that case you drop support for devices distributed without Google Play, like Amazon phones).

*Android 6.0 introduced the Doze mode. This is a new battery-optimization mechanism that puts your device into sleep when it's not used for some longer period of time. AlarmManager has an ability to fire your code even if your phone is in Doze. JobScheduler has not.

A: That doesnt seem like the right answer.  It may be made to work, but that seems more for scheduling jobs in a semi-realtime manner.  What you generally use for an alarm type app is just AlarmManager.


text:
Q: Changing style of active thumbnail image Ninja Slider For some reason I can't target / Select image in span in div and change it when clicked or active and toggle the rest off.
So in other words there is a span over the image, when I rollover or click on it it should change styles, why you not change style bro?
Here is an example of exactly what I need to happen: http://www.menucool.com/slider/jquery-slideshow

Here is my html:

For the hover I am using css which works fine:
  div#thumbs > span img {
   opacity:0.8;
   }

  div#thumbs > span:hover img{
   opacity:1;
    }

But I need the image to  STAY "ACTIVE" when clicked and rest to NOT be active.
/<<<<<------This is the original style I want to add this------>/
 div#thumbs img.thumb-img {
  opacity:1;
  border:6px solid #666666;

  }

Pleeeeease help, I'm in trouble. I am a noob

A: add this code to your css
#thumbnail-slider ul li{
   opacity:1;
}


text:
Q: Distribution of the difference of order statistics Let $X_1$ and $X_2$ be a random sample of size 2 from a uniform distribution over the interval $[0,1]$, let $Y_1$ and $Y_2$ be the corresponding order statistics. Find

*

*the conditional density function of $Y_1$ given $Y_2$

*the probability density function of $Y_2-Y_1$

I first had to find the order statistics of $Y_1$ which is $2(1-y)$ and of $Y_2$ which is $2y$. In both cases $0<y<1$.
Should I use these two to find (1.)?
I also feel (2.) can only be done using convolution theorem of discrete random variables.
Am I in the right direction?

A: We will need the joint comulatice distribution function $F_{Y_1,Y_2}(u,v)=P(Y_1<u,Y_2<v).$
Now,
$$P(Y_1<u,Y_2<v)=P(Y_1<u,Y_2<v, X_1\le X_2)+P(Y_1<u,Y_2<v ,X_2<X_1)=$$
$$=P(X_1<u,X_2<v, X_1\le X_2)+P(X_2<u,X_1<v ,X_2<X_1).$$
First,
$$P(X_1<u,X_2<v, X_1\le X_2)=
\begin{cases}
-\frac{u^2}{2}+uv,&\text{ if }& 0\le u\le v \le 1\\
\frac{v^2}{2},&\text{ if }& 0\le v<u \le1
\end{cases}.$$
The figure below explains how I calculated the two pieces of surface area:

Second,
$$P(X_2<u,X_1<v ,X_2<X_1)=P(X_2<u,X_1<v, X_2\le X_1)=
\begin{cases}
-\frac{u^2}{2}+uv
,&\text{ if }& 0\le u\le v \le 1\\
\frac{v^2}{2},&\text{ if }& 0\le v<u \le1
\end{cases}.$$
(A figure similar to the one above would explain the latter result.)
We can calculate the joint cdf:
$$F_{Y_1,Y_2}(u,v)=$$$$=P(X_1<u,X_2<v, X_1\le X_2)+P(X_2<u,X_1<v ,X_2<X_1)=$$
$$=\begin{cases}
-u^2+2uv,&\text{ if }& 0\le u\le v \le 1\\
v^2,&\text{ if }& 0\le v<u \le1
\end{cases}.$$
The joint pdf can be calculated the following way:
$$f_{Y_1,Y_2}(u,v)=\frac{{\partial} ^2}{\partial u \partial v}F_{Y_1,Y_2}(u,v)=\begin{cases}
2,&\text{ if }& 0\le u\le v \le 1\\
0,&\text{ otherwise. }
\end{cases}$$

Then we will need the following marginal density:
$$f_{Y_2}(v)=\int_0^vf_{Y_1,Y_2}(u,v)du=2\int_0^v\ du=2v;\  0\le v\le 1.$$
To answer the first question: By definition
$$f_{Y_1 \mid Y_2=v}(u)=\frac{f_{Y_1,Y_2}(u,v)}{f_{Y_2}(v)}=\begin{cases}
\frac{1}{v},&\text{ if }& 0\le u\le v \le 1\\
0,&\text{ else. }
\end{cases} \tag 1$$
To answer the second question: First let's calculate the cdf of $Y_2-Y_1$. By definition
$$F_{Y_2-Y_1}(x)=P(Y_2-Y_1<x)=E[P(Y_2-Y_1<x \mid Y_2)]. $$
Then
$$P(Y_2-Y_1<x \mid Y_2=v)=
\begin{cases}
0,&\text{ if } x<0\\
P(Y_1>v-x\mid Y_2=v),& \text{ if } 0\le x \le v \le 1\\
1,&\text{ if } x>v
\end{cases}$$
where $0\le v \le 1$.
Considering $(1)$ we have for $0\le x \le v \le 1$
$$P(Y_1>v-x\mid Y_2=v)=\frac 1v\int_{v-x}^v\ du=\frac xv.$$
So, for a given $0\le x \le 1$
$$P(Y_2-Y_1<x \mid Y_2=v)=\begin{cases}
1,& \text{ if } 0\le v\le x\\
\frac xv,&\text{ if } x\le v\le 1.\\
\end{cases}$$
As a result, for $0\le x \le 1$
$$F_{Y_2-Y_1}(x)=\int_0^1P(Y_2-Y_1<x \mid Y_2=v)f_{Y_2}(v)\ dv=$$
$$=2\int_0^x v \ dv + 2x\int_x^1 \ dv=2x-x^2.$$
Finally, $$f_{Y_2-Y_1}(x)=\begin{cases}
2-2x,& \text{ if } 0\le x \le 1 \\
0,&\text{ otherwise. }
\end{cases}$$


text:
Q: How do I build an concrete implementation of a Java Class from an interface using Byte-Buddy? I have an interface, lets say it looks like this.
public interface TestObject {
    String getString();

    Long getLong();
}

I want to actually build a concrete implementation of this object using ByteBuddy.
Here's what I tried.
public class Runme {

    public static void main(String[] args) {
        ByteBuddy bb = new ByteBuddy();

        Class<?> clz = bb
                .subclass(TestObject.class)
      .method(any()).intercept(MethodDelegation.to(Interceptor.class))
            .make()
            .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();

    try {
        Object test = clz.newInstance();

    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

}

public class Interceptor {

    public Object intercept(@Origin String method, @AllArguments Object[] args) throws Throwable {
        System.out.println("I have intercepted a call");

        return "Hello";

    }

}

}
I get this error
Exception in thread "main" java.lang.IllegalArgumentException: None of [] allows for delegation from public boolean java.lang.Object.equals(java.lang.Object)
at net.bytebuddy.implementation.bind.MethodDelegationBinder$Processor.process(MethodDelegationBinder.java:881)
at net.bytebuddy.implementation.MethodDelegation$Appender.apply(MethodDelegation.java:1218)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:510)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:444)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:3193)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1481)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:234)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$AbstractDelegatingBuilder.make(DynamicType.java:2177)
at com.meta.testbytebuddy.Runme.main(Runme.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

What am I doing wrong ++.. What if I want to implement multiple interfaces?
I am using ByteBuddy for code generation purposes.

A: The problem is that you are delegating to the interceptor's static methods by MethodDelegation.to(Interceptor.class) while the interceptor class only declared non-static members. You can either declare your interceptor method to be static or you delegate to an instance instead of to the class. I think the former approach would be more suitable.
This alone will however still not work. You are returning an Object type from your interceptor while, at the same time, you are intercepting any() method. This includes the methods of your TestObject interface but also the methods declared by Object, the implicit super class. You could define your interceptor as follows to make your class compile but then Byte Buddy will cast the return type to each method's return type what will result in a ClassCastException:
public class Interceptor {
  @RuntimeType
  public static Object intercept(@Origin String method, @AllArguments Object[] args) {
    System.out.println("I have intercepted a call");
    return "Hello";
  }
}


text:
Q: Will Spring 3.5 abandon IoC or XML Bean Configurations? I have heard that Spring - after establishing annotations with version 2 - might be abandoning IoC and XML bean definitions altogether in Spring version 3.5.
Is that a known fact or nonsense?
update
My colleague is pretty sure he was told by a spring instructor that
as of Spring 3.5 annotation style progamming would be focused on exclusively.
(If that would mean desupporting the older approaches I do not know)
Since that information is 1-2 years old it might be outdated allready though.
(changed Spring v4 to v3.5 with this edit)

A: I'd say it's nonsense (though I've never heard any plans about spring 4)

*

*IoC is a concept behind spring, related to "dependency injection", so that's perhaps a term misunderstanding

*XML - frameworks like CDI that don't use XML have plugins that enable XML configuration because in some scenarios it is the better approach. For example for establishing configurations in the project. I don't think spring will abandon such a rich xml support (and break backward compatibility completely)


text:
Q: How can I read Microsoft Bot composer properties like user.name or $(feelings) in code? I have a bot, that welcome user and asks for it name, I store the name to user.name and greet the user. My dialog flow continues and I ask user with different questions using triggers and store them is variables like $(feelings) and same. I want to extend my Bot composer with code, I need to store some of the properties to the database. Please help me doing that. I have seen Middleware component but it does not give me the access to the properties for a particular dialog. I am stuck into it. Please help me in this regard.
Note: I only need to have track the activeDialog so that I could get the property value when user has already given his input. Input could be in Text or suggested action.


text:
Q: ClipboardManager throws the following error: Can't create handler inside thread that has not called Looper.prepare() using WorkManager I'm creating an app where the user has the possibility to copy the text to clipboard for 30 seconds. After 30 seconds the text needs to be removed from clipboard, even if the app has been closed

In my main activity I have the following code:
OneTimeWorkRequest worker = new OneTimeWorkRequest.Builder(clipboardWorker.class)
                .setInitialDelay(30, TimeUnit.SECONDS).build();
        WorkManager.getInstance().enqueue(worker);

The clipboardWorker looks like this:
public class clipboardWorker extends Worker {
    private static final String TAG = "clipboardWorker";

    public clipboardWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {

        ClipboardManager clipboardManager = (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("clp", "");
        clipboardManager.setPrimaryClip(clip);

        return Result.success();
    }
}

This works on Android version 28 but on 27 it throws the following error:
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Here is the stack trace:
2019-04-07 11:41:15.948 18924-18944/com.example.clipboard E/WM-WorkerWrapper: Work [ id=fa06342b-0130-4562-b323-5871ea0e67fb, tags={ com.example.clipboard.clipboardWorker } ] failed because it threw an exception/error
    java.util.concurrent.ExecutionException: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at androidx.work.impl.utils.futures.AbstractFuture.getDoneValue(AbstractFuture.java:516)
        at androidx.work.impl.utils.futures.AbstractFuture.get(AbstractFuture.java:475)
        at androidx.work.impl.WorkerWrapper$2.run(WorkerWrapper.java:289)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:204)
        at android.os.Handler.<init>(Handler.java:118)
        at android.content.ClipboardManager$2.<init>(ClipboardManager.java:62)
        at android.content.ClipboardManager.<init>(ClipboardManager.java:62)
        at android.app.SystemServiceRegistry$11.createService(SystemServiceRegistry.java:254)
        at android.app.SystemServiceRegistry$11.createService(SystemServiceRegistry.java:252)
        at android.app.SystemServiceRegistry$CachedServiceFetcher.getService(SystemServiceRegistry.java:962)
        at android.app.SystemServiceRegistry.getSystemService(SystemServiceRegistry.java:914)
        at android.app.ContextImpl.getSystemService(ContextImpl.java:1667)
        at android.content.ContextWrapper.getSystemService(ContextWrapper.java:714)
        at com.example.clipboard.clipboardWorker.doWork(clipboardWorker.java:26)
        at androidx.work.Worker$1.run(Worker.java:85)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)

The error is thrown here:
ClipboardManager clipboardManager = (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);

Below are the gradle plugins:
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.work:work-runtime:2.0.0'

A: That's because The Worker Class of the WorkManager Api run on a Background Thread,
In the Worker Class you could try to declare an Handler attached to the Main Thread :
Handler mainThreadHandler = new Handler(Looper.getMainLooper());

Then use the Handler's post() Method to run your ClipBoard Code


text:
Q: Cannot connect to remote desktop Connecting from Windows 7 Home to Windows 7 Enterprise.
Done the following:

*

*port forwarding for 3389

*enabled RD in System properties

*connected to it with Teamviewer, so it's running

*allowed RD in Windows Firewall for private/public

This is still unsolved - thanks for all suggestions so far and any further help would be much appreciated

A: Well, here is a sort of summary for others.
nmap was used for examining RDP port state. http://nmap.org/
Port Forwarding and Port triggering was set on router for port 3389.
From internet it was stated as closed, meaning that we got response icmp destination-unreachable.
Windows by default is not responding, but silently drops packets, so nmap instead of closed would say filtered(as without response).
Reason was Port triggering, port wasn't triggered to open from lan. After disable Port triggering, port 3389 was open on router and nmap was showing port filtered.
It was caused by routers dhcp server, that assigned another IP address to Windows PC. So after wezten assinged IP to MAC address of computer with RDP, it just works.


text:
Q: Spivak, Ch. 15, Trigonometric Functions", Proof of $\arcsin{\alpha}+\arcsin{\beta}=\arcsin{(\alpha \sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$. The following problem is from Chapter 15 "Trigonometric Functions" from Spivak's Calculus

*Prove that

$$\arcsin{\alpha}+\arcsin{\beta}=\arcsin{(\alpha
 \sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$$
indicating any restrictions on $\alpha$ and $\beta$.

My question is about the restrictions on $\alpha$ and $\beta$. I will show the solution from the solution manual first, and then specify my question.
Here is the solution manual solution

From the addition formula for $\sin$ we obtain, for $|\alpha|\leq 1$
and $|\beta|\leq 1$,
$$\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\sin{(\arcsin{\alpha})\cos{(\arcsin{\beta})}}+\cos{(\arcsin{\alpha})\sin{(\arcsin{\beta})}}$$
$$=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}$$

Note that though it is not mentioned a significant step is taken in showing that
$$\cos{(\arcsin{x})}=\sqrt{1-x^2}$$
This is done by computing the derivative of $\sin(x)$ as the reciprocal of the derivative of $\arcsin$ at $\sin{x}$.

Consequently
$$\arcsin{\alpha}+\arcsin{\beta}=\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}\tag{1}$$
provided that $-\pi/2\leq\arcsin{\alpha}+\arcsin{\beta}\leq\pi/2$. [If
$\pi/2<\arcsin{\alpha}+\arcsin{\beta}\leq \pi$, the right side must be
replaced with
$\pi-\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$, and if
$-\pi\leq \arcsin{\alpha}+\arcsin{\beta}\leq -\pi/2$, replaced with
$-\pi-\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$.]

My question is about the last paragraph.
Let's start at the point where we have
$$\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}$$
and we want to take the $\arcsin$ of each side to obtain $(1)$.
Now, $\arcsin{\alpha}$ and $\arcsin{\beta}$ are each in $(-\pi/2, \pi/2)$. Their sum is in $(-\pi, \pi)$, and the whole left expression is thus in $[-1,1]$.
$\pm 1$ occur when $\arcsin{\alpha}+\arcsin{\beta}=\pm \frac{\pi}{2}$.
If one of these two cases occurs, then $\arcsin$ isn't defined for $\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\pm 1$.
EDIT: the sentence above is is incorrect. I confused $\arcsin$ with its derivative $\arcsin'$.
So my first question is about the following snippet of the solution manual solution

provided that $-\pi/2\leq\arcsin{\alpha}+\arcsin{\beta}\leq\pi/2$

where the values $\pi/2$ and $-\pi/2$ are included in the possibilities. Are these values really allowed?
EDIT: given the first edit above, yes, these values are allowed.
My second question is about the discussion when $\pi/2<\arcsin{\alpha}+\arcsin{\beta}\leq \pi$ or $-\pi\leq \arcsin{\alpha}+\arcsin{\beta}\leq -\pi/2$. What is happening in these cases, I don't know what Spivak's solution manual did there.

A: I'd start from the conditions first.
When it exists, the right-hand side is an angle in the interval $[-\pi/2,\pi/2]$, so the left-hand side must as well.
The existence condition is (with $a=\alpha,b=\beta$ for ease of typing)
$$
\textstyle \lvert\, a\sqrt{1-b^2}+b\sqrt{1-a^2}\,\rvert\le 1\tag{*}
$$
In particular, $|a|\le1$ and $|b|\le1$, but this was already known from examining the left-hand side.
Condition (*) is satisfied for $|a|\le 1$ and $|b|\le 1$ by using Cauchy-Schwarz with the vectors
$$
\textstyle v=(a,\sqrt{1-a^2}\,)\qquad w=(\sqrt{1-b^2},b)
$$
and the standard CS inequality $|v\cdot w|\le\|v\|\,\|w\|$ becomes
$$
\textstyle \lvert\, a\sqrt{1-b^2}+b\sqrt{1-a^2}\,\rvert\le\sqrt{a^2+1-a^2}\sqrt{1-b^2+b^2}=1
$$
OK, this leaves only the condition that
$$
-\frac{\pi}{2}\le \arcsin a+\arcsin b\le\frac{\pi}{2} \tag{**}
$$
Under this condition, we can take the sine of both sides. From the left-hand side we get
$$
\textstyle
\sin(\arcsin a)\cos(\arcsin b)+\cos(\arcsin a)\sin(\arcsin b)
=a\sqrt{1-b^2}+b\sqrt{1-a^2}
$$
because, for $|x|\le 1$, we have
$$
\textstyle\cos(\arcsin x)=\sqrt{1-\sin^2(\arcsin x)}=\sqrt{1-x^2}
$$
because $-\pi/2\le\arcsin x\le\pi/2$ and so $\cos\arcsin x\ge0$.
Thus we conclude that, for $|a|\le1$ and $|b|\le 1$,

$\arcsin a+\arcsin b=\arcsin\bigl(a\sqrt{1-b^2}+b\sqrt{1-a^2}\,\bigr)$ if and only if $\lvert\arcsin a+\arcsin b\rvert\le \pi/2$

A: Let's start at the point where we have
$$\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}\tag{1}$$
and we want to take the $\arcsin$ of each side to obtain $(1)$.
First, let's just note that $\alpha$ and $\beta$ are each in $[-1,1]$, and thus $\arcsin{\alpha}$ and $\arcsin{\beta}$ are each in $[-\pi/2,\pi/2]$. The sum $(\arcsin{\alpha}+\arcsin{\beta})$ is thus in $[-\pi,\pi]$.
We need to consider what happens for all such possible values of $(\arcsin{\alpha}+\arcsin{\beta})$.
Case 1: $-\pi/2\leq \arcsin{\alpha}+\arcsin{\beta}\leq\pi/2 $
The equation
$$\arcsin{(\sin{(\arcsin{\alpha}+\arcsin{\beta})})}=\arcsin{\alpha}+\arcsin{\beta}\tag{2}$$
is true.
We can thus take the $\arcsin$ of both sides of $(1)$ and end up with
$$\arcsin{\alpha}+\arcsin{\beta}=\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$$
Case 2: $\pi/2\leq \arcsin{\alpha}+\arcsin{\beta}\leq\pi $
Equation $(2)$ is no longer true (indeed, it doesn't even make sense because of the domain of $\arcsin$).
However, it is true that $\sin{x}=\sin{\pi-x}$. Thus,
$$(\pi-\arcsin{\alpha}-\arcsin{\beta}) \in (-\pi/2,0]$$
and
$$\sin{(\pi-\arcsin{\alpha}-\arcsin{\beta})}=\sin{(\arcsin{\alpha}+\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}\tag{3}$$
Now it is true that
$$\arcsin{(\sin{(\pi-\arcsin{\alpha}-\arcsin{\beta})})}=\pi-\arcsin{\alpha}-\arcsin{\beta}$$
So we can take the $\arcsin$ of the first and last expressions in $(3)$ to obtain
$$\pi-\arcsin{\alpha}-\arcsin{\beta}=\arcsin{(\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2})}$$
and the desired
$$\arcsin{\alpha}+\arcsin{\beta}=\pi-\arcsin{(\alpha\sqrt{1-\beta^2}-\beta\sqrt{1-\alpha^2})}$$
Case 3: $-\pi\leq \arcsin{\alpha}+\arcsin{\beta}<-\pi/2$
This case is similar to case 2. Since
$$\sin{(-\pi-x)}=\sin{x}$$
we have that
$$(-\pi-\arcsin{\alpha}-\arcsin{\beta}) \in (-\pi/2,0]$$
$$\sin{(-\pi-\arcsin{\alpha}-\arcsin{\beta})}=\alpha\sqrt{1-\beta^2}+\beta\sqrt{1-\alpha^2}\tag{3}$$
and taking the $\arcsin$ of each side we obtain
$$-\pi-\arcsin{\alpha}-\arcsin{\beta}=\arcsin{(\alpha\sqrt{1-\beta^2}-\beta\sqrt{1-\alpha^2})}$$
$$\arcsin{\alpha}+\arcsin{\beta}=-\pi-\arcsin{(\alpha\sqrt{1-\beta^2}-\beta\sqrt{1-\alpha^2})}$$
$\blacksquare$
Spivak's solution manual sure does skip a lotta steps.

A: HINT

*

*$\arcsin(\sin\alpha)=\alpha$ only when $\alpha\in[-\frac\pi2,\frac\pi2]$

*$\arcsin(\sin\alpha)=\pi-\alpha$ when $\alpha\in[\frac\pi2,\pi]$

*$\arcsin(\sin\alpha)=-\pi-\alpha$ when $\alpha\in[-\pi,-\frac\pi2]$


text:
Q: Setting up PHP opcode caching under WampServer 2.1 I've been trying to find information on installing(or enabling?) APC under WampServer 2.1, but every reference to it is either fragmentary or misleading. One forum post actually claimed it was already bundled and just left out of the php.ini file, but adding the enabling line did nothing, nor do I see any evidence the dll file even exists in the Wamp dir.
Can anyone provide the basic steps needed here?
I'm not particularly set on using APC, it's just recommended by the apps I'm trying to use. If xcache or eaccelerator are easier or better-documented, that's fine also. Thanks.


text:
Q: Autocomplete items disappearing I have a strange problem regarding suggestion items for an AutocompleteView on Android 2.2. I am using a custom ArrayAdapter and Filter class implementation.
When I type into the AutocompleteView the suggestion drop-down pops up after entering two characters as shown in the following screenshot:

When I enter a third character the drop-down disappears:

After entering a fourth character the suggestion drop-down is displayed again:

I don't understand why the drop-down disappears when an uneven amount of characters is entered.
While debugging I noticed that getView() is called twice when an even amount of characters is entered, but ony once for an uneven amount. Might this be the reason for the faulty behavior?
Here is my source code:
public class AutoCompleteActivity extends Activity {

protected AutoCompleteTextView autoCompleteView;
protected AutoCompleteAdapter suggsAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.autocomp);

    autoCompleteView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    autoCompleteView.setAdapter(new AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line, new String[1]));
}

private class AutoCompleteAdapter extends ArrayAdapter implements Filterable {

    protected LayoutInflater mInflater;
    protected Filter filter;

    public AutoCompleteAdapter(Context context, int textViewResourceId, String[] items) {
        super(context, textViewResourceId, items);
        filter = new SuggestionsFilter();
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            v = mInflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
        }

        TextView tt = (TextView) v.findViewById(android.R.id.text1);
        tt.setText("Suggestion item");

        return v;
    }

    public Filter getFilter() {
        return filter;
    }

    private class SuggestionsFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            return null;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            notifyDataSetChanged();
        }
    }
}

}
...and my layout file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<!-- Pretty hint text, and maxLines -->
<AutoCompleteTextView android:id="@+id/autocomplete"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:maxLines="1"
    android:imeOptions="actionSearch"
    android:layout_toLeftOf="@+id/spinner"  />

A: I found a solution to my problem. I did not set results.count in my performFiltering method. Setting this property to e.g. results.count = 1 resolved the issue with the dissapearing suggestion items.


text:
Q: Paypal Express - Hide Shipping Methods and Shipping Costs I'm using PayPal Express in my shop and determine the shipping costs after the user comes back to the shop after signing in via PayPal Express.
Right now I'm passing no shipping costs, because I want to hide the entire shipping costs/methods (marked yellow)
How is this possible? My current requests looks like this:
     ["CALLBACKVERSION"]=>
  string(4) "84.0"
  ["LOCALECODE"]=>
  string(5) "de_DE"
  ["SOLUTIONTYPE"]=>
  string(4) "Mark"
  ["BRANDNAME"]=>
  string(8) "Foo"
  ["CARTBORDERCOLOR"]=>
  string(0) ""
  ["RETURNURL"]=>
  string(168) "..."
  ["CANCELURL"]=>
  string(111) "..."
  ["PAYMENTREQUEST_0_PAYMENTACTION"]=>
  string(4) "Sale"
  ["CALLBACK"]=>
  string(158) "..."
  ["CALLBACKTIMEOUT"]=>
  int(6)
  ["NOSHIPPING"]=>
  string(1) "2"
  ["PAYMENTREQUEST_0_AMT"]=>
  string(4) "1.19"
  ["PAYMENTREQUEST_0_CURRENCYCODE"]=>
  string(3) "EUR"
  ["PAYMENTREQUEST_0_ITEMAMT"]=>
  string(4) "1.25"
  ["PAYMENTREQUEST_0_DESC"]=>
  string(50) "..."
  ["PAYMENTREQUEST_0_CUSTOM"]=>
  string(50) "..."
  ["MAXAMT"]=>
  string(5) "32.25"
  ["L_PAYMENTREQUEST_0_NAME0"]=>
  string(12) "Gesamtsumme:"
  ["L_PAYMENTREQUEST_0_AMT0"]=>
  string(4) "1.25"
  ["L_PAYMENTREQUEST_0_QTY0"]=>
  int(1)

This results in an error from PayPal

"Flat-rate shipping options are missing; you must specify flat-rate
  shipping options when you specify a callback URL."

But if I pass any shipping costs, it is shown as above. How can I hide them?

A: Found out that according to documentation, FlatRateShippingOptions - ebl:ShippingOptionsType is required if you are specifying the Callback URL.
When I look at the documentation about ShippingOptionsType here, this looks like something you want to do;

false — PayPal does not display this flat-rate shipping option and its
  amount as the default shipping option.

There are three (plus 2) fields you need to add:
1. "L_SHIPPINGOPTIONISDEFAULTn":
    If you specify false, you can adjust either or both of these values:
     - PAYMENTREQUEST_n_TAXAMT
     - PAYMENTREQUEST_n_INSURANCEAMT

2. "L_SHIPPINGOPTIONNAMEn"
3. "L_SHIPPINGOPTIONAMOUNTn"

Hope this can help you!


text:
Q: How to Bulk Insert and update record in mongodb using c# I have on requirement in that i want to read bulk record from Mongo DB A and Want to Insert and update based on the record exist or not in DB B.
Suppose in DB A i have 10 record initially so these record should be inserted in DB B. But after some time if some record are got updated in DB A and already as i have inserted in DB B. Now it should fire bulk update only.
Let me know if anyone having any idea about it using c#

A: You can take advantage of the $merge aggregation pipeline stage for this (https://docs.mongodb.com/manual/reference/operator/aggregation/merge/).
This is easy to execute in C# but depending on what you need to achieve you can configure the parameters accordingly
var client = new MongoClient();
var databaseA = client.GetDatabase("A");
var databaseB = client.GetDatabase("B");

var collectionA = databaseA.GetCollection<BsonDocument>("test");
var collectionB = databaseB.GetCollection<BsonDocument>("test");
await collectionA.Aggregate()
    .Merge(collectionB)
    .ToListAsync();


text:
Q: httpservice result format I use flex and php to retrieve information from my sql database. What i have been doing is formatting the result from the database query into xml and then putting the result into an arraycollection. It all works fine except one of my database fields contains a lot of text that website users enter and as xml doesn't like tags like <>  so I leave it un formatted but I would like to format it. Would I be better using flashvars or text than xml? Or is there another way?

A: You should have your database code that produces the XML escape special XML characters (e.g. <, > and &) with the standard entities (<, > and &) and stick with XML.

A: Or wrap text within CDATA.


text:
Q: Flexbox how to have child elements fill the height I have a jsfiddle example here.  What I'm trying to do is have the right side .inside-right fill the height of .right.  You can see the black background is only taking up a small space at the top.  I've tried various heights 100%, auto, but can't seem to get it to fill all the way.  Any suggestions would be great!

    .container {
        margin: 0;
        padding: 0;
        display: flex;
        flex-flow: row;
    }

    .container > .field {
        width: 100%;
        background: #dddd88;
        order: 2;
    }

    .container > .left {
        width: 4px;
        background: #ccccff;
        order: 1;
    }

    .container > .right {
        width: 4px;
        background: #ccccff;
        order: 3;
    }

    .top, .bottom {
        display: block;
        height: 4px;
        background: red;
    }

    .inside-right {
      background: black;
      width: 4px;
     }

    Main Body

        -

A: just add a min-height
.inside-right {
  background: black;
  width: 4px;
  min-height:100%;
 }

complete working code:

    .container {
        margin: 0;
        padding: 0;
        display: flex;
        flex-flow: row;
    }

    .container > .field {
        width: 100%;
        background: #dddd88;
        order: 2;
    }

    .container > .left {
        width: 4px;
        background: #ccccff;
        order: 1;
    }

    .container > .right {
        width: 4px;
        background: #ccccff;
        order: 3;
    }

    .top, .bottom {
        display: block;
        height: 4px;
        background: red;
    }

    .inside-right {
      background: black;
      width: 4px;
   min-height:100%;
     }

    Main Body

working jsFiddle here

A: Another way to do it is make .right display: flex and by default, the children (or child, in this case) will stretch to fill the height of the parent.

    .container {
        margin: 0;
        padding: 0;
        display: flex;
        flex-flow: row;
    }

    .container > .field {
        width: 100%;
        background: #dddd88;
        order: 2;
    }

    .container > .left {
        width: 4px;
        background: #ccccff;
        order: 1;
    }

    .container > .right {
        width: 4px;
        background: #ccccff;
        order: 3;
        display: flex;
    }

    .top, .bottom {
        display: block;
        height: 4px;
        background: red;
    }

    .inside-right {
      background: black;
      width: 4px;
     }

    Main Body

        -


text:
Q: How do I pass object from array within one component? Const App references two other components above it. At run time, it compiles successfully with no errors but I'm not getting the result I want.
Inside const App = () => {}, I have no problems rendering the Header tag within the return statement. In fact, it does what I want it to do which is to print "Half Stack application development" as a header in html.
The problem is with the Total tag underneath it. Underneath the header I want to render the number 342 as a paragraph tag onto the web page, but its not working.
Any help would be greatly appreciated to a newbie like me who just started learning React. Thank you :)
// Header takes care of rendering the name of the course.

const Header = (props) => {
    return (

{props.course}

    )
}
// Total renders the total amount of exercises.

const Total = (props) => {
    return (

Total number of exercises:{props.parts}

    )
}

// Header takes care of rendering the name of the course.

const App = () => {
    const course = {
        name: 'Half Stack application development' ,
        parts: [{name:'One' , exercises:342}]

      }

    return (

            <Total parts={course.parts.exercises} />

            {/*
            <Content parts={parts} />
            */}

    )
}

ReactDOM.render(<App />, document.getElementById('root'))

A: This is not really a react problem but a problem with accessing the parts array:
Try:
<Total parts={course.parts[0].exercises} />


text:
Q: FaunaDB: how to fetch a custom column I'm just learning FaunaDB and FQL and having some trouble (mainly because I come from MySQL). I can successfully query a table (eg: users) and fetch a specific user. This user has a property users.expiry_date which is a faunadb Time() type.
What I would like to do is know if this date has expired by using the function LT(Now(), users.expiry_date), but I don't know how to create this query. Do I have to create an Index first?
So in short, just fetching one of the users documents gets me this:
{
  id: 1,
  username: 'test',
  expiry_date: Time("2022-01-10T16:01:47.394Z")
}

But I would like to get this:
{
  id: 1,
  username: 'test',
  expiry_date: Time("2022-01-10T16:01:47.394Z"),
  has_expired: true,
}

I have this FQL query now (ignore oauthInfo):
Query(
  Let(
    {
     oauthInfo: Select(['data'], Get(Ref(Collection('user_oauth_info'), refId))),
     user: Select(['data'], Get(Select(['user_id'], Var('oauthInfo'))))
    },
    Merge({ oauthInfo: Var('oauthInfo') }, { user: Var('user') })
  )
)

How would I do the equivalent of the mySQL query SELECT users.*, IF(users.expiry_date < NOW(), 1, 0) as is_expired FROM users in FQL?

A: Your use of Let and Merge show that you are thinking about FQL in a good way.  These are functions that can go a long way to making your queries more organized and readable!
I will start with some notes, but they will be relevant to the final answer, so please stick with me.
The Query function
https://docs.fauna.com/fauna/current/api/fql/functions/query
First, you should not need to wrap anything in the Query function, here.  Query is necessary for defining functions in FQL that will be run later, for example, in the User-Defined Function body.  You will always see it as Query(Lambda(...)).
Fauna IDs
https://docs.fauna.com/fauna/current/learn/understanding/documents
Remember that Fauna assigns unique IDs for every Document for you.  When I see fields named id, that is a bit of a red flag, so I want to highlight that.  There are plenty of reasons that you might store some business-ID in a Document, but be sure that you need it.
Getting an ID
A Document in Fauna is shaped like:
{
  ref: Ref(Collection("users"), "101"), // <-- "id" is 101
  ts: 1641508095450000,
  data: { /* ... */ }
}

In the JS driver you can use this id by using documentResult.ref.id (other drivers can do this in similar ways)
You can access the ID directly in FQL as well.  You use the Select function.
Let(
  {
   user: Get(Select(['user_id'], Var('oauthInfo')))
   id: Select(["ref", "id"], Var("user"))
  },
  Var("id")
)

More about the Select function.
https://docs.fauna.com/fauna/current/api/fql/functions/select
You are already using Select and that's the function you are looking for.  It's what you use to grab any piece of an object or array.
Here's a contrived example that gets the zip code for the 3rd user in the Collection:
Let(
  {
   page: Paginate(Documents(Collection("user")),
  },
  Select(["data", 2, "data", "address", "zip"], Var("user"))
)

Bring it together
That said, your Let function is a great start.  Let's break things down into smaller steps.
Let(
  {
   oauthInfo_ref: Ref(Collection('user_oauth_info'), refId)
   oauthInfo_doc: Get(Var("oathInfoRef")),

   // make sure that user_oath_info.user_id is a full Ref, not just a number
   user_ref: Select(["data", "user_id"], Var("oauthInfo_doc"))
   user_doc: Get(Var("user_ref")),
   user_id: Select("id", Var("user_ref")),

   // calculate expired
   expiry_date: Select(["data", "expiry_date"], Var("user_doc")),
   has_expired: LT(Now(), Var("expiry_date"))
  },

  // if the data does not overlap, Merge is not required.
  // you can build plain objects in FQL
  {
    oauthInfo: Var("oauthInfo_doc"), // entire Document
    user: Var("user_doc"),           // entire Document
    has_expired: Var("has_expired")  // an extra field
  }
)

Instead of returning the auth info and user as separate points if you do want to Merge them and/or add additional fields, then feel free to do that
  // ...
  Merge(
    Select("data", Var("user_doc")),  // just the data
    {
      user_id: Var("user_id"),        // added field
      has_expired: Var("has_expired") // added field
    }
  )
)


text:
Q: .NET Core SignalR "Channel" Purpose? I am using SignalR 1.1 in .NET Core, with a strongly typed hub. E.g.
await _hub.Clients.All.FooBar(someData);

Then the Angular front end picks up that message here:
this.hubConnection.on('fooBar', (data) => {
  console.log('data');
});

I am transitioning this code from a legacy SignalR system (we switched from .NET to .NET Core). I keep encountering the idea of "channels", but I can't find anything in the documentation. When I google "SignalR channel", I get nothing.
If a channel is an actual concept, what is it used for? Also, is there any danger/performance hit due to NOT using channels?
The old code looks something like this:
let channelName = `${Constants.GeneralChannel}${comp.eventId}${comp.deskId}`;
comp.channelService.sub(channelName).subscribe(

Is there some SignalR good practice that I am missing here? Or is "channelName" just a concept that our team came up with (can't ask them, they are all gone).

A: Most likely referring to "groups". Back to basics of SignalR examples, the chat room. Everyone who joins might be in a group or channel called "lobby". Now when they join a chat room named "Room1" there may be a group/channel for that the user gets added to so they can then see the "chat" going on in that room.
I use groups to put users together and send messages to groups based on content that is tailored for those groups.
Hope that helps... google "signalr groups" and you find more detailed info.


text:
Q: Closing a doc file after converting it to pdf I am converting a doc file to a pdf file but with my current code it seems that the file is open even after the conversion. I see the pdf file in the output folder but if i try to reupload it tells me that it is opened in another program(which i don't see anywhere).
Code section error:
if (getExt == ".doc")
{
    Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
    wordDocument = appWord.Documents.Open(DocumentUNCPath.Text);

    wordDocument.ExportAsFixedFormat(@"c:\temp\DocTo.pdf", WdExportFormat.wdExportFormatPDF);
}

The full method:
private void btnSubmitStep2_Click(object sender, EventArgs e)
{
    string getExt = Path.GetExtension(DocumentUNCPath.Text);
    if (getExt == ".doc")
    {
        Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
        wordDocument = appWord.Documents.Open(DocumentUNCPath.Text);

        wordDocument.ExportAsFixedFormat(@"c:\temp\DocTo.pdf", WdExportFormat.wdExportFormatPDF);
    }

    // Frame up the record of submission
    using (var dc = new DocMgmtDataContext())
    {
        DocumentLibrary.Document doc = new DocumentLibrary.Document()
        {
            LibraryID = (AssignmentListStep2.SelectedItem as Library).ID,
            OwnedByUserID = (StudentListStep2.SelectedItem as User).ID,
            UploadedByUserID = (StudentListStep2.SelectedItem as User).ID,
            UploadDT = DateTime.UtcNow,
            ID = Guid.NewGuid()
        };

        dc.Documents.InsertOnSubmit(doc);
        dc.SubmitChanges();

        // Copy file into managed storage
        doc.StoragePath = FILESTORELOCATION + doc.ID + ".pdf";
        File.Copy(DocumentUNCPath.Text, doc.StoragePath);

        doc.Pages = CompatiblePdfReader.VerifyAndFixPdfDocument(doc.StoragePath);
        dc.SubmitChanges();
    }

    // Refresh the list of student submissions
    UpdateStudentSubmissionGrid();
}

A: Try closing the document at the end of your sub with wordDocument.Close SaveChanges:=wdDoNotSaveChanges, as ExportAsFixedFormat doesn't close the file for you.


text:
Q: what is AllowEmptyStrings in Required Data Annotation? I have Added Required Data Annotation to my Data Model Class.
[Required(ErrorMessage = "Name Required", AllowEmptyStrings = true)]
public string Name { get; set; }

I am wondering what does it do actually,
because results are some what confusing to me.
Input to textbox : Only few Spaces("     ") passes the model Validation ,where as
Input To Textbox: empty ("") ,fails the model validation.
But earlier i thought  "" is empty string,so this case should be one to pass the model validation.
Why this unexpected behaviour?Where did i get thing wrong?

A: It will check any non-null string values. Because the string type is inherently nullable, empty strings passed to the ModelBinder are read as null


text:
Q: unable to access public ip on occasion? my server is configured to have a public ip on one network card,
and a private ip on the other network card...
the server was running fine after some time...
suddenly i'm unable to access my server from outside my isp network...
at first i thought it's because i recently changed my ip address,
until the same thing happen to 3 other servers (that i'm in charged to) on totally different network...
one is running with the same isp (same network as my previous server),
one is running with different isp (not even in the same country),
and the other one is running with different isp (same country)...
the conditions i checked :
from outside the server isp network:

*

*able to ping to the server

*traceroute to the server has no problem

*unable to access the webserver

*unable to access the ssh

*unable to access the sftp

from inside the server isp network (using public ip):

*

*able to ping to the server

*traceroute to the server has no problem

*able to access the webserver

*able to access the ssh

*able to access the sftp

there's no firewall set on the servers...
is there anything i should check?
i'm also asking to my isp as i put this question...
this also happens only on occasion...

A:

*

*able to ping to the server

*traceroute to the server has no problem

*unable to access the webserver

*unable to access the ssh

*unable to access the sftp

Is it possible that there's some kind of IP address conflict or routing issue, and that you're not actually pinging your server, but a different machine that is using your IP? Try do to a port scan + OS detection with nmap:
nmap -O <IP or hostname of your server>

and compare the results - how does the output change when the issue occurs?

A: turns out there's a problem with the routing...
the server accepts the incoming packages, but when replying it uses a wrong address...
there are 2 default route on the server, one directly to the isp, and the other one to the local server...


text:
Q: Построение графиков на основе отредактированного в python csv-файла Есть множество файлов в формате csv, с дробными значениями, примерно следующего формата:

Значения эти отображают амплитуды колебания сигналов с платы в какой-то момент времени, где каждая строчка - это шаг. Графическое отображение раньше удавалось вполне успешно реализовывать средствами пайтона и его модулей, но, будучи в нем начинающим, наткнулся на определенные проблемы. Чтобы отобразить значения во времени, я добавил слева столбец, инкрементирующий на каждом шагу, символично отсчитывающий время. Сверху я добавил заголовки, для удобства отображения на графике столбцов в виде каналов.

Выглядит результат так.
Но разнести значения каналов по времени у меня не выходит - в листинге видно, что наименования столбцов программа не считывает.
Использую Anaconda на базе 2.7 и Pyzo. Код (на pastebin):
import csv
import numpy as np
import matplotlib.pyplot as plt
import pylab
import pandas as pd
from Tkinter import*
import tkFileDialog as filedialog
root=Tk()
root.fileName=filedialog.askopenfilename(filetypes=(("csv files","*csv"),("All files","*.*" )))
k=root.fileName
print(k)
root.destroy()
pd.read_csv(k).mul(0.8).to_csv('minitest.csv', index=False)

with open('minitest.csv', 'rb') as input, open('temp.csv', 'w') as output:
    reader = csv.reader(input, delimiter = ',')
    writer = csv.writer(output, delimiter = ',')

    all = []
    row = next(reader)
    row.insert(0, '0')
    all.append(row)
    for k, row in enumerate(reader):
        all.append([str(k+1)] + row)
    writer.writerows(all)

with open('temp.csv','rb') as f:
    r = csv.reader(f, delimiter='\t')
    data = [line for line in r]
with open('temp.csv','w') as f:
    w = csv.writer(f, lineterminator='\n')
    w.writerow(['Time','CH1','CH2','CH3','CH4','CH5','CH6','CH7','CH8'])
    w.writerows(data)
    print(data)

my_data = pd.read_csv('temp.csv',sep=u',', header=0, skip_footer=0)
my_data.plot(x='Time',y=['CH1','CH2','CH3','CH4','CH5','CH6','CH7','CH8'],figsize=(14, 10))
plt.show()

Может кто-то подсказать, что мне в нем исправить для корректного отображения?
То, что получилось у меня:

Примерно то, что должно было быть (сделано средствами экселя)

A: вот что у меня получилось:
Code:
import pandas as pd
import matplotlib.pyplot as plt

def plot_df(df, out_plot_fn=None, mult_factor=0.8,
            cols=None, x_axis=None, figsize=(12,10)):
    if x_axis:
        df = df.set_index(x_axis)

    if cols:
        df.columns = cols

    if mult_factor and mult_factor != 1:
        df *= mult_factor

    ax = df.plot.line(figsize=figsize)

    if out_plot_fn:
        plt.savefig(out_plot_fn)
    else:
        plt.show()

fn = r'D:\temp\.data\7.csv.gz'

df = pd.read_csv(fn, skipinitialspace=True)

plot_df(df, out_plot_fn=r'd:/temp/bad.png')

# пропускаем 7-ю колонку (Python/Pandas считают с нуля, поэтому - 6-ю)
# иначе по Y-axis будет неправильное масштабирование
# и все графики будут выглядеть слишком сглаженными
usecols = [0,1,2,3,4,5,7]

df = pd.read_csv(fn, usecols=usecols, skipinitialspace=True)

plot_df(df, out_plot_fn=r'd:/temp/a.png')

# переименуем названия колонок в DF
cols = ['ch1','ch2','ch3','ch4','ch5','ch6','ch8']
plot_df(df, cols=cols, out_plot_fn=r'd:/temp/b.png')

# только первые 50 строк
plot_df(df.head(50), out_plot_fn=r'd:/temp/c.png')

Результаты:
a.png:

b.png:

c.png:

вот что получается если не вырезать 7ю (8) и последнюю пустую (Unnamed: 8) колонку:


text:
Q: Layout constraints for custom UITtableViewCell not working I'm creating custom UITableViewCells with a UILabel in each but can't get the label to display anywhere else than the top left corner of the cell, looks like this.
Constraints don't seem to be applied yet they're being called (reaching breakpoint). I tried to replace the UILabel by an UIImageView and apply the same constraints but nothing appears (i.e. table view cells are blank).
What am I missing?
View for cells:
import UIKit

class myTableViewCell: UITableViewCell {

    override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupViews()
    }

    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
    }

    let label: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightLight)
        label.text = "Sample"
        label.backgroundColor = UIColor.red
        return label
    }()

    func setupViews () {
        addSubview(label)
        //add constraints
        let marginsGuide = self.contentView.layoutMarginsGuide
        label.leadingAnchor.constraint(equalTo: marginsGuide.leadingAnchor).isActive = true
        label.trailingAnchor.constraint(equalTo: marginsGuide.trailingAnchor).isActive = true
        label.topAnchor.constraint(equalTo: marginsGuide.topAnchor).isActive = true
        label.bottomAnchor.constraint(equalTo: marginsGuide.bottomAnchor).isActive = true
    }

}

View controller:
import UIKit

class myViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var myTableView: UITableView = UITableView()

    var myArray = [Int]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //... do stuff incl. loading data into my myArray
        let screenSize: CGRect = UIScreen.main.bounds
        self.myTableView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
        self.myTableView.delegate = self
        self.myTableView.dataSource = self
        self.myTableView.register(IngredientListTableViewCell.self, forCellReuseIdentifier: "cell")
        self.view.addSubview(myTableView)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.myTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! myTableViewCell
        return cell
    }

}

A: Change this
addSubview(label)

to this
contentView.addSubview(label)


text:
Q: Change Installshield project in configuration manager to debug I have a WPF application.. I need to create 3 setups, each setup is for an environment(development, staging and production), I've put each environment configuration into App.config file of my main UI project. I need Installshield to pull the appropriate configuration file while creating the setup file.
A question: Is there a way to do it differently?
thanks,

A: There are several approaches you could take. Here's one:
In recent versions of InstallShield (Professional and higher editions), you can override Path Variables on a per-Release basis. If you craft your source filesystem and source path correctly, this should let you select from multiple source app.config files just by building a different release.


text:
Q: Fire notifications once USB device is connected to MAC I am very new to Macintosh Application Development. I have a question that, is it possible to open my application when  user connects a USB device to the Macintosh? I am very curious on this. Because I have a device and when I connect it to MAC system I need to open my application installed in the app and get the data from the USB device. Is this possible?

A: If it's just a storage device with a mountable file system, use NSWorkspace's NSWorkspaceDidMountNotification/NSWorkspaceWillUnmountNotification/NSWorkspaceDidUnmountNotification notifications to listen for it.
If you're looking for any other type of device, you'll have to dive a lot deeper. Check out the USB Device Interface Guide.


text:
Q: Google Webmaster Tools says sitemap has error, it doesn't So a client has this autogenerated sitemap: http://nordwest-najad.se/sitemap.xml
And when I try to add it to google webmaster tools I get this error:
Missing XML tag
This required tag is missing. Please add it and resubmit.

The problem is that the xml tag is there and there is nothing wrong with the document.
I have validated the document with these sites:
http://www.validome.org/google/
http://sitemapxml.net/sitemap-validator.php
http://www.xml-sitemaps.com/validate-xml-sitemap.html
And all three sites says that there is no errors.

A: I fixed it for my case
I checked www.dhakalist.com/sitemap.xml was working but not dhakalist.com/sitemap.xml
so i added these lines in my .htaccess file and problem solved.
RewriteCond %{HTTP_HOST} !^www\.

RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Now google is taking sitemap.

A: From: http://support.google.com/webmasters/bin/answer.py?hl=en&answer=183668
Your Sitemap file must specify the following XML namespace: xmlns="http://www.sitemaps.org/schemas/sitemap/0.9".

A: Google webmaster tool showing right error because you are completely missing your XML tag.
Because your starting line
"http://www.google.com/schemas/sitemap/0.9/sitemap.xsd">" have error.
Change it with
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
This is necessary for validating the process that defines the elements and attributes. You can define in your sitemap file according to XML schema guidelines.


text:
Q: how to convert textarea value into meaningful content without reloading the page? I'm getting value typed, from textarea and pasting into a div. Typed value might contain smileys. In these case smileys needed to be converted into presentable smileys rather than just copy paste typed text as it is now.
var composer = $('[data-textarea]');
var message = $.trim(composer.val());
var wrapper = $('[data-wrapper]');

here the smileys has to be converted
wrapper.append(message);

Note: I do not want to play replacing the possible smileys like in these posts:
Replacing text with smiley image using Jquery
I want jquery itself to translate to meaningful smileys depending on the browser setting.
Do not want replacing like this:
$("body").html($("body").html().replace(/:sick;/g,'

'));

A: You can look up the unicode representation of your desired smileys and use it to create a mapping of "text to unicode" couples, then replace the input text with that. I have found this handy little website for smileys but there are many more : http://character-code.com/emoticons-html-codes.php.
Here is a small setup and script added to the body tag to do exactly what I described above:

$(document).ready(function() {
  var smileyMap = {
    ':)': '😊',
    ':(': '😣'
      // etc...
  };
  // on every character added
  $('#myInput').keyup(function(value) {
    // get the whole value
    var progressiveText = $('#myInput').val();
    // replace textual smileys with unicode representation
    for (var key in smileyMap) {
      while (progressiveText.indexOf(key) >= 0)
        progressiveText = progressiveText.replace(key, smileyMap[key]);
    }
    // update the html
    $('#myDiv').html(progressiveText);
  });
});

  <input id="myInput" type="text" name="text" />


text:
Q: Why got rejected on posting open graph message? I have an iOS app with integration of Facebook. This app used facebook open graph and post some activity message when the player does something important in the game. The open graph message are tagged as explicit_shared. But I got rejected after reviewed by facebook and the reasons are as below:
Posting Explicitly Shared content must be optional. In the Open Graph action flow, users need to know that they are sharing content back to Facebook and have the ability to opt-out.
I know what it means. But the point is, the app didn't automatically post the open graph message. Only when the player click a specific button, the message will be sent. For example, there is a button like "share my score on facebook", and when the player clicks on it, the app will post an open graph message. So I think what I did confirms to the guideline. I don't understand why it's rejected in this case.

A: Excerpts from the docs:
It represents something they would have entered or uploaded into the Facebook composer for sharing.
Even though in your app the users are clicking the share button, it does not count as explicit sharing because users are not providing with any status message when they are sharing.
More Reading
Hope this helps.


text:
Q: Continuous pdf and cdf Could someone explain what comes from pdf and what comes from cumulative distribution function (cdf) as far as: Probabilities ( $x < a,$ or $a < x < b$), standard deviation, Expected value, and variance?
Edit: to elaborate on what I've tried and where I am having a lapse in understanding,
I understand you can go from pdf to cumulative distribution function by taking the integral from negative infinity to infinity.
But once I have both, I'm having difficulty calculating probabilities, standard deviation and the mean due to not knowing when to use pdf vs cdf to calcuate it.
for example: to get the probability of x being between A and B, do I integrate from A to B the pdf dx, or do I integrate from A to B the cdf dx


text:
Q: MEAN.JS module factory Im using MEAN.JS, and I can't figure out exactly what this piece of code does:
File:
public/modules/users/services/authentication.client.service.js

Code:
'use strict';

// Authentication service for user variables
angular.module('users').factory('Authentication', [

    function() {
        var _this = this;

        _this._data = {
            user: window.user
        };

        return _this._data;
    }
]);

Why does it make a copy of 'this', add a property and then return that property instead of doing something like:
'use strict';

// Authentication service for user variables
angular.module('users').factory('Authentication', [

    function() {

        return {
            user: window.user
        };

    }
]);


text:
Q: firebase v3 - google auth "internal-error" I try to migrate my google-auth-only project from firebase 2.x to 3.0 using the web-sdk example from:
https://github.com/firebase/quickstart-js/blob/master/auth/google-redirect.html
After setting up the initialisation-code with apiKey (via Google-Developer-Console - used the server-option) and all the other needed options, i use the "login with google"-button.
After this, an redirect-screen appears, then redirecting back to starting page and getting an "auth/internal-error".
Any suggestions?

A: I would recommend importing your project in the Firebase Console rather than configuring keys manually if possible, but appreciate there are some cases where that isn't ideal.
For the API key, try switching to the "Browser" type key rather than the "Server" one for anything running in the browser, and make sure it is approved for the domain you are using.
Google Sign In will need a client ID as well. The easiest way to implement is to use the signInWithPopUp method, but there are instructions for manually configuring the Google Sign In lib too.
If you do need to create a client ID, you can see the full instructions in the Google Sign In documentation.


text:
Q: p divides the index $[G: N_G(P)]$? Suppose G is a finite group with order $p^at, p\nmid t$, where $p$ is a prime number, and suppose $P$ is any $p-$subgroup of G, not necessarily to be Sylow $p-$subgroup, let $N_G(P)$ be its normalizer and asume $P$ is a sylow $p-$subgroup in $N_G(P)$, then is $p\nmid [G:N_{G}(P)]$ always true?

A: Good question, and yes it is true. Because in general if $P$ is a $p$-subgroup of $G$ then $[G:P] \equiv [N_G(P):P]$ mod $p$. This can be proved by looking at the action of $P$ on the left coset space $G\backslash P$ by left multiplication. See for example here, chapter 2. In other words, $P$ is a Sylow $p$-subgroup in $G$ iff it is a Sylow $p$-subgroup in its normalizer.


text:
Q: tailwindcss 50% width all div

w-first

w-second

w-third

w-fourth

I wants 2 div per row, i can use a div wrap to (first, second) div, then use w-1/2 that times it works fine.
but if i have unlimited div its not possible to wrap all div in same time.

A: It looks like a perfect scenario for the grid layout.
While flex is designed for one-dimensional layouts, for a two-dimensional layout like the one you have, grid would be a better fit.
Switch the flex utility with the grid utility. Then, specify the number of columns by using grid-cols-2. This utility will limit the number of elements of each row to 2.
You can read more about the grid-cols-{n} utility here.

w-first

w-second

w-third

w-fourth

Tailwind-Play


text:
Q: Regex all uppercase with special characters I have a regex '^[A0-Z9]+$' that works until it reaches strings with 'special' characters like a period or dash.
List:
UPPER
lower
UPPER lower
lower UPPER
TEST
test
UPPER2.2-1
UPPER2

Gives:
UPPER
TEST
UPPER2

How do I get the regex to ignore non-alphanumeric characters also so it includes UPPER2.2-1 also?
I have a link here to show it 'real-time': http://www.rubular.com/r/ev23M7G1O3
This is for MySQL REGEX
EDIT: I didn't specify I wanted all non-alphanumeric characters (including spaces), but with the help of others here it led me to this: '^[A-Z-0-9[:punct:][:space:]]+$' is there anything wrong with this?

A: Try
'^[A-Z0-9.-]+$'

You just need to add the special characters to the group, optionally escaping them.
Additionally if you choose not to escape the -, be aware that it should be placed at the start or the end of the grouping expression to avoid the chance that it may be interpreted as delimiting a range.

To your updated question, if you want all non-whitespace, try using a group such as:
^[^ ]+$

which will match everything except for a space.
If instead what you wanted is all non-whitespace and non-lowercase, you likely will want to use:
^[^ a-z]+$

The 'trick' used here is adding a caret symbol after the opening [ in the group expression. This indicates that we want the negation of the match.
Following the pattern, we can also apply this 'trick' to get everything but lowercase letters like this:
^[^a-z]+$

I'm not really sure which of the 3 above you want, but if nothing else, this ought to serve as a good example of what you can do with character classes.

A: I believe you are looking for (one?) uppercase-word match, where word is pretty much anything.
^[^a-z\s]+$

...or if you want to allow more words with spaces, then probably just
^[^a-z]+$

A: You just need to put in the . and -. In theory, you don't need to escape because they are inside the brackets, but I like to to remind myself to escape when I have to.
'^[A-Z0-9\.\-]+$'

A: Try regular expression as below:
   '^[A0-Z0\\.\\-]+$'


text:
Q: wxpython: issue with layout in example I am trying to learn wxPython and I get a problem when I run the example code from the wiki:

The main frame isn't resizing properly. What's missing?
I am running under Enthought Python Distribution 7.3-2 (Python 2.7.3)
# from http://wiki.wxpython.org/Getting%20Started
import wx
class ExamplePanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        # create some sizers
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        grid = wx.GridBagSizer(hgap=5, vgap=5)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.quote = wx.StaticText(self, label="Your quote: ")
        grid.Add(self.quote, pos=(0,0))

        # A multiline TextCtrl - This is here to show how the events work in this program, don't pay too much attention to it
        self.logger = wx.TextCtrl(self, size=(200,300), style=wx.TE_MULTILINE | wx.TE_READONLY)

        # A button
        self.button =wx.Button(self, label="Save")
        self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)

        # the edit control - one line version.
        self.lblname = wx.StaticText(self, label="Your name :")
        grid.Add(self.lblname, pos=(1,0))
        self.editname = wx.TextCtrl(self, value="Enter here your name", size=(140,-1))
        grid.Add(self.editname, pos=(1,1))
        self.Bind(wx.EVT_TEXT, self.EvtText, self.editname)
        self.Bind(wx.EVT_CHAR, self.EvtChar, self.editname)

        # the combobox Control
        self.sampleList = ['friends', 'advertising', 'web search', 'Yellow Pages']
        self.lblhear = wx.StaticText(self, label="How did you hear from us ?")
        grid.Add(self.lblhear, pos=(3,0))
        self.edithear = wx.ComboBox(self, size=(95, -1), choices=self.sampleList, style=wx.CB_DROPDOWN)
        grid.Add(self.edithear, pos=(3,1))
        self.Bind(wx.EVT_COMBOBOX, self.EvtComboBox, self.edithear)
        self.Bind(wx.EVT_TEXT, self.EvtText,self.edithear)

        # add a spacer to the sizer
        grid.Add((10, 40), pos=(2,0))

        # Checkbox
        self.insure = wx.CheckBox(self, label="Do you want Insured Shipment ?")
        grid.Add(self.insure, pos=(4,0), span=(1,2), flag=wx.BOTTOM, border=5)
        self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, self.insure)

        # Radio Boxes
        radioList = ['blue', 'red', 'yellow', 'orange', 'green', 'purple', 'navy blue', 'black', 'gray']
        rb = wx.RadioBox(self, label="What color would you like ?", pos=(20, 210), choices=radioList,  majorDimension=3,
                         style=wx.RA_SPECIFY_COLS)
        grid.Add(rb, pos=(5,0), span=(1,2))
        self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, rb)

        hSizer.Add(grid, 0, wx.ALL, 5)
        hSizer.Add(self.logger)
        mainSizer.Add(hSizer, 0, wx.ALL, 5)
        mainSizer.Add(self.button, 0, wx.CENTER)
        self.SetSizerAndFit(mainSizer)

    def EvtRadioBox(self, event):
        self.logger.AppendText('EvtRadioBox: %d\n' % event.GetInt())
    def EvtComboBox(self, event):
        self.logger.AppendText('EvtComboBox: %s\n' % event.GetString())
    def OnClick(self,event):
        self.logger.AppendText(" Click on object with Id %d\n" %event.GetId())
    def EvtText(self, event):
        self.logger.AppendText('EvtText: %s\n' % event.GetString())
    def EvtChar(self, event):
        self.logger.AppendText('EvtChar: %d\n' % event.GetKeyCode())
        event.Skip()
    def EvtCheckBox(self, event):
        self.logger.AppendText('EvtCheckBox: %d\n' % event.Checked())

app = wx.App(False)
frame = wx.Frame(None)
panel = ExamplePanel(frame)
frame.Show()
app.MainLoop()

A: Aha, figured it out. A call of frame.Fit() was missing before frame.Show().
Instead of
app = wx.App(False)
frame = wx.Frame(None)
panel = ExamplePanel(frame)
frame.Show()
app.MainLoop()

it should be
app = wx.App(False)
frame = wx.Frame(None)
panel = ExamplePanel(frame)
frame.Fit()
frame.Show()
app.MainLoop()


text:
Q: Visual studio 2017 diagram designer toolbox only have comment in my C++ project I want to use VS diagram designer tool but I can't find class or interfaces or other things to add only comments and pointers are shown.
How could I fix this problem?

A: Probably it's seemingly an IDE problem. You can try the following methods step-by-step:

*

*Try resetting the Toolbox by selecting Reset Toolbox after right-clicking on it.

*If the above method doesn't works, try resetting IDE preferences to its factory settings (located in Tools > Import & export settings of the Top Menu bar):


text:
Q: Is there a method in MPI that acts like a MPI_Bcast but for an individual process, instead of operating on an entire communicator? Essentially what I am looking for here is a simple MPI_SendRecv() routine that allows me to synchronize the same buffer by specifying a source and a destination processor.
In my mind the function call for my Ideal_MPI_SendRecv() function would look precisely like MPI_Bcast() but would contain a destination process instead of a Communicator.
It might be called as follows:
Ideal_MPI_SendRecv(&somebuffer, bufferlength, datatype, source_proc, destination_proc);

If not, is there any reason? It seems like this method would be the perfect method to synchronize a variable's values between two processes.

A: No, there is no such call in MPI since it is trivial to implement it using point-to-point communication. Of course you could write one, for example (with some rudimentary support for error handling):
// Just a random tag that is unlikely to be used by the rest of the program
#define TAG_IDEAL_SNDRCV     11223

int Ideal_MPI_SendRecv(void *buf, int count, MPI_Datatype datatype,
                       int source, int dest, MPI_Comm comm)
{
   int rank;
   int err;

   if (source == dest)
      return MPI_SUCCESS;
   err = MPI_Comm_rank(comm, &rank);
   if (err != MPI_SUCCESS)
      return err;
   if (rank == source)
      err = MPI_Send(buf, count, datatype, dest, TAG_IDEAL_SNDRCV, comm);
   else if (rank == dest)
      err = MPI_Recv(buf, count, datatype, source, TAG_IDEAL_SNDRCV, comm,
                     MPI_STATUS_IGNORE);
   return err;
}

// Example: transfer 'int buf[10]' from rank 0 to rank 2
Ideal_MPI_SendRecv(buf, 10, MPI_INT, 0, 2, MPI_COMM_WORLD);

You could also add another output argument of type MPI_Status * and store the status of MPI_Recv there. It could be useful if both processes have different buffer sizes.
Another option would be, if you have to do that many times within a fixed set of ranks, e.g. always from rank 0 to rank 2, you could simply create a new communicator and broadcast inside it:
int rank;
MPI_Comm buddycomm;

MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_split(MPI_COMM_WORLD, (!rank || rank == 2) ? 0 : MPI_UNDEFINED, rank,
               &buddycomm);

// Transfer 'int buf[10]' from rank 0 to rank 2
MPI_Bcast(buf, 10, MPI_INT, 0, buddycomm);

This, of course, is an overkill since the broadcast is more expensive than the simple combination of MPI_Send and MPI_Recv.

A: Perhaps you want to call MPI_Send on one process (the source process, with the values you want) and MPI_Recv on another process (the one which doesn't initially have the values you want)?
If not, could you clarify how what you're trying to accomplish differs from a simple point-to-point message?


text:
Q: Is there a negative for Courier new font? I want to make a text highlight in flex textArea but its htmlText doesn't support  part of my text  so I'm searching for a font witch is the opposite of Courier new, when I embed it in flash, and write with that color I get highlight effect for that part of my text , as I type   part of my text

A: white text goes here
Note:I tried to post it formatted, but SO doesn't appear to accept font tags.
Edit: You can find this stuff out for yourself by going to http://www.w3schools.com.

A: You should use a StyleSheet for that.
Example:
var theCSS:String = ".normaltext{color:#FFFF00;font-family:Courier}.highlightedtext{color:#FFFF00;font-family:Arial}";
var theStyle:StyleSheet = new StyleSheet();
theStyle.parseCSS(theCSS);
theTextArea.styleSheet = theStyle;
theTextArea.htmlText = 'Normal text here, and the highlighted text here';


text:
Q: SSIS Development- how to handle with new Table creation at source every 15 days I am developing a SSIS Package, which consume data from Source SQL and target FLATFILE.
The one challenges I am facing, please help me how to solve it.
The New table got created in SQL Source by Upstream every 2 week, How to handle such scenario. I don't want to modify SSIS Package every time for new table which got created.
The Schema of new table are not same.
Is There any way to handle this by config file or any control file.
Or to achieve this, do I need to shift to different technology stack.
Please help
Many Thank

A: "The Schema of new table are not same"
Then an SSIS Data Flow is not the right technology for you. A Data Flow is tightly bound to the source and destination metadata and changing schema ain't gonna work1.
"do I need to shift to different technology stack"
Maybe? Maybe not. SSIS can still offer benefits as an execution framework with the native logging, configuration, and access to a host of native components plus the .NET runtime for anything else you might need to do.
How would I solve this?
Given that you need to export the contents of an arbitrary table to a flat file, I would use my trust friend BCP
As a sample invocation, the following would export a table named MyTable to a tab delimited file using integrated security
bcp dbo.MyTable out "C:\temp\AdventureWorks.dbo.MyTable.txt" -S ERECH\DEV2019UTF8 -d AdventureWorks -T -c -a 32768

You can invoke bcp from SSIS via an Execute Process Task.
How do you handle the changing table name? Probably a query like
-- Generate a list of tables created in the past 16 days
-- Make the table name safe for consumption by BCP via quotename
SELECT
    CONCAT(QUOTENAME(S.name), '.', QUOTENAME(T.name)) AS QualifiedTable, T.create_date
FROM
    sys.schemas AS S
    INNER JOIN
        sys.tables AS T
        ON T.schema_id = S.schema_id
WHERE
    T.create_date > DATEADD(DAY, -16, GETDATE())
ORDER BY T.create_date DESC;

1 You could conceivably make it work assuming there are always common core elements and you only need to export those entities.
For example, given these table definitions, you could extract the first 3 columns, with some type casting in the source queries and always fill an output file
CREATE TABLE dbo.Week0
(
    id varchar(10)
,   Col1 float
,   Col2 int
,   ExtraColumn varchar(50)
);

CREATE TABLE dbo.Week1
(
    externalId int
,   Col11 float
,   Col2 varchar(50)
);

It would be a lot of dynamic query generation and hope and guesswork but it can be done, but probably shouldn't be.


text:
Q: Encoding with url and api So I have this web app set up and running and it works fine for any username that you request, but when i try http://mrcastelo.pythonanywhere.com/lol/euw/Nazaré, it simply doesnt work - the error that I get on the server is the following:
iddata= getJSON(urllolbase+region+urlid+username) #SummonerID
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)

It is annoying me greatly, I've tried some other threads but none of them came to a fix. The api that I am using (www.legendaryapi.com) does accept this because this works.
Any idea on how to fix this?
urllolbase = 'http://www.legendaryapi.com/api/v1.0/'
urlid = '/summoner/getSummonerByName/'
urlps = '/summoner/getAllPublicSummonerDataByAccount/'

def getJSON(url):
    response = urllib2.urlopen(url)
    data = json.load(response)
    return data