text:
Q: FMDB to Read from Database for an iPhone Application I am using the following code to read the records from the customers table. For some reason the resultset returned is always empty.
    -(NSMutableArray *) getCustomers
{
    NSMutableArray *customers = [[NSMutableArray alloc] init];

    NSString *databaseName = @"Customers.db";

    NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentsPath objectAtIndex:0];

    NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    if(![db open])
    {
        return nil;
    }

    FMResultSet *results = [db executeQuery:@"SELECT * FROM customers"];

    while([results next])
    {
        Customer *customer = [[Customer alloc] init];

        customer.firstName = [results stringForColumn:@"firstname"];
        customer.lastName = [results stringForColumn:@"lastname"];

        [customers addObject:customer];

    }

    [db close];

    return customers;

}

I have checked in the database multiple times and it shows the data but for some reason the FMDB is not able to retrieve it!

A: set db log errors to true, this will show you log in console where you can find the problem.
FMDatabase *db = [FMDatabase databaseWithPath:databasePath];
db.logsErrors = YES;


text:
Q: how to emit a change in rxjs based on a value I can get the observable to fire the value once. But I want it to occure whenever the value of the variable changes. Effectively I need a watcher. Which is what I thought the point of an observable was. To observe a value or state of things and update anything that was subscribed to it.
Anyways, here's the code
import { Component, OnInit } from '@angular/core';

var Rx = require('rxjs/Rx');

import { Subject } from "rxjs/Rx";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  private testBool: boolean = false;
  private observable;

  constructor() {

    this.observable = Rx.Observable.of(this.testBool);

    this.observable.subscribe(
      (value) => console.log(value)
    )
  }

  toggleBool() {
    this.testBool = !this.testBool;

  }

}

so whenever the value of this.testBool changes, I want the subscribe to get updated. In it's current state, I get one console log and then nothing. I click the button that updates the boolean but the observer subscriber never fires again.
Am I missing some crucial point and this isn't how I'm supposed to use this?
And I know that I can bind the observer to the button click, but that's not how I want to achieve this. This would be a service level example. So anything anywhere could update the value.
I've read about subjects but I'm still learning. So maybe I'm supposed to be doing something with that?
Thanks

A: You want to subscribe and send a new value to the observable. In that case you will need a Subject. In this case we are using a BehaviorSubject, in a BehaviorSubject you can set a default value.
import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from "rxjs/Rx";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  private testBool: boolean = false;
  private observable: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  constructor() {
    this.observable.subscribe((value) => console.log(value))
  }

  toggleBool() {
    this.testBool = !this.testBool;
    this.observable.next(this.testBool);
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Decrypt LUKS partition by a script in udev rules I am trying to decrypt a LUKS partition when I plug in an external HDD. Thus, I have configured the udev rules with the following:
ACTION=="add", KERNEL=="sdb1", SUBSYSTEM=="block", ATTR{size}=="1048576000", RUN+="/home/user/myfile.sh

myfile.sh script:
password=`su - user -c 'export DISPLAY=:0;kdialog --password "Decrypt HDD"'`
sleep 5
echo "$password" | cryptsetup luksOpen /dev/sdb1 backups
mount /dev/mapper/backups /media/backups/

The script read the password through kdialog, after decrypt the partition and mount it. If I run manually it works. The problem is that when I plug in the USB, the kdialog is launched but the /dev/sdb1 encrypted partition is not detected until the script has finished. Therefore the cryptsetup luksOpen and mount do not anything (because are launched before the encrypted partition is detected)...
The file with the udev rules is 90-crypt.rules in /etc/udev/rules.d

A: Finally I found the problem. With RUN you can not execute long programs/scripts. And the solution is create a service that run your script and use the rule SYSTEMD_WANTS with your service.
From man udev:
RUN{type}
Add a program to the list of programs to be executed after processing all the rules for a specific event, depending on "type":
   "program"
       Execute an external program specified as the assigned value. If no absolute path is given, the program is expected to live in /lib/udev; otherwise, the absolute path must be specified.

       This is the default if no type is specified.

   "builtin"
       As program, but use one of the built-in programs rather than an external one.

   The program name and following arguments are separated by spaces. Single quotes can be used to specify arguments with spaces.

   This can only be used for very short-running foreground tasks. Running an event process for a long period of time may block all further events for this or a dependent device.

   Starting daemons or other long-running processes is not appropriate for udev; the forked processes, detached or not, will be unconditionally killed after the event handling has finished.

   Note that running programs that access the network or mount/unmount filesystems is not allowed inside of udev rules, due to the default sandbox that is enforced on systemd-udevd.service.

Solution:
Create a service in /etc/systemd/system/myservice.service>
[Unit]
Description=Auto backup

[Service]
ExecStart=/home/manu/Sysadmin/auto-backup.sh

And change the udev rule:
ACTION=="add", KERNEL=="sdb1", SUBSYSTEM=="block", ATTR{size}=="1048576000", ENV{SYSTEMD_WANTS}="myservice.service"


text:
Q: Code at Stackoverflow under any license?
Possible Duplicate:
Do I have to worry about copyright issues for code posted on StackOverflow?

A very basic doubt: the answers that are quoted on SO, do they come under any license?
Is it OK(/Legal) to copy whole/parts of code provided in answers by users?
I personally make sure to just take cue from the idea and try to re-write the solution but it might not be a case for every problem, hence the question.
My main concern is if I ask a particular question for which someone gets answer off the net and pastes it and that particular code was under some license. This can also be for ideas/solutions provided by users.
I did not find anything on FAQ or previous posts regarding this.

*

*Ivar
(marked post as community wiki just in case)

A: They're licensed under CC-BY-SA, so your code must be under CC-BY-SA as well if you want to copy snippets, and your code probably isn't. See the CC-wiki logo at the footer of trilogy sites.


text:
Q: iphone:How to stream and play youtube video with in application using MPMoviePlayer? I want to make a youtube app like this (Youtube Stream) http://itunes.apple.com/us/app/youtube-stream/id384383425?mt=8# app for the iphone, where some videos are streamed/downloaded from a youtube and played within same app without launching iphone's youtube app..
I searched lot but couldn't find a clue on how to do it..can any one suggest a solution...

A: I found a way to stream/play youtube video inside iphone app, but i don't know apple will recognize it or its under youttube  terms and condictions. Bellow i attach my .h and .m file plz check and say how it works..
YoutubePlayerViewController.h
#import<UIKit/UIKit.h>
#import<MediaPlayer/MediaPlayer.h>

@interface YoutubePlayerViewController : UIViewController
{
    UITextField *yurl;
    NSMutableData *responseData;
    NSString *cacheLink;
    MPMoviePlayerController *moviePlayer;

}

@property(nonatomic,retain)IBOutlet UITextField *yurl;
@property(nonatomic,retain)NSString *cacheLink;

-(IBAction)Play:(id)sender;
-(IBAction)removeKeyboard;
@end

//--------------------------------------------------------------------------------
//YoutubePlayerViewController.m
#import "YoutubePlayerViewController.h"

@implementation YoutubePlayerViewController
@synthesize yurl,cacheLink;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"view did load");
}

-(IBAction)removeKeyboard
{

    [yurl resignFirstResponder];

}

-(IBAction)Play:(id)sender
{

    //1.get the url
    NSString *url=yurl.text;
    //NSString *url=@"http://www.youtube.com/watch?v=t2o5MhaSWRs";
    //2.show loding view

    //3.make http request
    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];

    //3.parse jason string for itag=18
    //5.create an NSURL with that string
    //6.start the player with url

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"did receving response");
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //NSLog(@"receving data");
    [responseData appendData:data];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Connection failed: %@", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%d",responseData.length);
    NSString* strServerResponse= [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

    NSLog(@"%@",strServerResponse);
    NSLog(@"\n***********************************************\n");

    NSArray *temp=[strServerResponse componentsSeparatedByString:@"swfConfig"];
    strServerResponse=[temp objectAtIndex:1];

    temp=[strServerResponse componentsSeparatedByString:@".c.youtube.com,18|"];
    strServerResponse=[temp objectAtIndex:1];

    temp=[strServerResponse componentsSeparatedByString:@"||"];
    strServerResponse=[temp objectAtIndex:0];

    strServerResponse=[strServerResponse stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    NSLog(@"%@",strServerResponse);
    self.cacheLink=strServerResponse;

    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"link" message:self.cacheLink delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
    [alert show];
    [alert release];

    NSURL *url=[[NSURL alloc] initWithString:self.cacheLink];
    moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
    [self.view addSubview:moviePlayer.view];
    moviePlayer.view.frame = CGRectMake(5,150,310,230);
    moviePlayer.view.backgroundColor=[UIColor blackColor];
    [moviePlayer play];

    [connection release];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@end

A: It's easy
Here is my example: https://github.com/comonitos/youtube_video
I used PSYouTubeExtractor.h class by Peter Steinberger It can get youtube mp4 video url and than downloading and viewing is not a problem
NSURLConnection + NSNotificationCenter + PSYouTubeExtractor + NSMutableData


text:
Q: Angular - how to do a dynamic alert with different type of errors? In my web app I am showing alerts for loading content and another alert when there is an error.
I am using AngularJS/AngularStrap
right now this is what I have:
var noLinesAlert = $alert({
  title: 'Sorry, no lines at this moment :(',
  container: '.no-lines-alert',
  type: 'danger',
  dismissable: false,
  show: false
}),

loaderAlert = $alert({
  content: 'Loading content. Please wait...',
  container: '.alerts-container',
  type: 'info',
  show: true
  });

and I am calling these alerts this way, example noLinesAlert.show() or loaderAlert.hide() and so on... but just imagine that I will have 4 more alerts for special cases, do I have to create those vars with the object inside every time or is there a way to do it more programmatically? and how.

A: For every alert the title, container, type, and show property changes. You need to give the program that information, so you can't do this any shorter.

A: Well, you can store "default" settings for those 4 special cases in dedicated object, for example: ALERTS_SETTINGS = { notice: {} }, and then the call would be much more concise:
var noticeOptions = angular.extend(ALERTS_SETTINGS.notice, { title: "My custom property one" })
var notice = $alert(noticeOptions)

Using angular.extend you can override any default setting from the original object by those you provide in the second argument.

A: Make it dynamic by putting the $alert into a function. Allow the function to pass parameters to the $alert. Set the show property to true.
Call the function when needed. For example:
var displayAlert = function(alertTitle, className) {

    var alertOptions = {
       title: alertTitle,
       container: className,
       type: 'danger',
       dismissable: false,
       show: true
    };

    var alert = $alert(alertOptions);

}

// Call the function when needed
$scope.displayAlert('Sorry, no lines at this moment :(','.no-lines-alert')


text:
Q: I get script error on the line 0 in p5js editor p5js editor enviroment
hello I'm a beginner programmer and I wanted to play around a little bit, but right at the start I get this error, I'm following everything as in the reference, so I don't really get what's the problem, can anyone explain to me what's happening?

A: try changing the img variable to something else like img123.
As the error msg shows there is already a variable with the same name.


text:
Q: Local parameter label naming convention in initializers Let assume that I have a class like this:
class Foo {

    private let userId: String

    init(userId givenUserId: String) {
        userId = givenUserId
    }
}

When I have initializers (or functions) like the above one, so ones setting some internal variable, I like them to have their external parameter name as descriptive as it can be. On the other hand, it is also good to use the same name in the internal class implementation. But then I have to use some local parameter label and the way I do it is by adding a prefix "given" before the external parameter label. Is this a good way to do this or is there any better method or convention to solve the issue?

A: In Swift initializers, you can use the local labels identical to property names. With self. notation, the compiler automatically figures out which one to use for simple assignments. That way, you can have expressive external parameters and avoid the burden of defining both external and internal parameter labels.
class Foo {

    private let userId: String

    init(userId: String) {
        self.userId = userId
    }
}

A: To avoid to be ambiguous, you could write your class like that:
class Foo {

    private let userId: String

    init(userId userId: String) {
       self.userId = userId
    }
}

self keyword, will automatically take the internal var.
If you want some precision on how to have a good coding style, I recommend you : swift-style-guide


text:
Q: Google drive webhook add/modify/remove file I would like to know how to know when you receive a webhook if it is a new file added to google drive, a file modified or a file removed.
@POST
@Path("/webhook")
public void webhook(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
    Credential credential = initFlow().loadCredential("user");
    Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();

    String pageToken = GDrive.savedPageToken;

    while (pageToken != null) {
        ChangeList changes = service.changes().list(pageToken).execute();

        for (Change change : changes.getChanges()) {

            if (!change.getFile().getMimeType().equalsIgnoreCase("application/vnd.google-apps.folder")) {
                //IGNORE FOLDERS
                Log.info("Removed file: "+ change.toString());
            }
        }
        if (changes.getNewStartPageToken() != null) {
            GDrive.savedPageToken = changes.getNewStartPageToken();
        }
        pageToken = changes.getNextPageToken();
    }
    response.setStatus(200);
}

I'm just interested in file changes, so I ignore application/vnd.google-apps.folder.
How I can differentiate from these?

*

*Case that file is added.

*Case that file is modified.

*Case that file is removed permanently.


text:
Q: JS / Jquery - Remove multiple elements from an array by keys I have a set of keys (for example 2,3,4,101,102,454).
I'd like to remove elements with these keys from an array.
Is there a way to remove them all at once?
I tried iterating through for loop, and using splice
to remove elements one by one, but that never removed
all elements - my guess is because it modifies the
array I'm looping through.

A: go backwards.
If you loop thru from 0 -> n, you modify the indexes of the elements coming after an item you just removed.
If you go backwards, from n -> 0, you don't have that problem.

A: You can sort your indexes to remove largest first-
//array=array, removal=[2,3,4,101,102,454]
var i=0, L=removal.length;
removal.sort(function(a,b){return b-a});
while(i< L){
    array.splice(removal[i],1);
}


text:
Q: Proper way to error handle This is more of a architectural question. I like to know what people's opinion on how to properly handle errors in a fully Object Oriented PHP environment.
For example I have a class that retrieves all user data from the database. So I would use it in this way:
$userData = new UserDataConnection();
$userData->openDatabase();
$userData->retrieveData();
$userData->showData();
$userData->closeDatabase();

At each of these steps, an error could have potentially occurred. So would I return a boolean from each step stating whether the function has successfully executed (hence the error checking is within each function), or do I do a try-catch exception handling around the whole thing? or is there a better way?
Is it also better to always go to some kind of error page when some kind of error occur?

A: <?php

$ERROR = false;
try {

    $userData = new UserDataConnection();
    $userData->openDatabase();
    $userData->retrieveData();
    $DETAILS = $userData->showData();
    $userData->closeDatabase();

} catch( Exception $e ) {

    $ERROR = $e->getMessage(); // exit;

}

if( $ERROR ) {
    $DETAILS = array();
}

?>

If you are using PDO you can throw a PDOException.

A: It typically boils down to a simple question:
May this function "legitimately" fail or is any failure a sign of something being really wrong?
If a function expects a certain kind of input and should never ever be called with a different kind of input, any failure to supply the correct input is an InvalidArgumentException. This is especially true for functions which do not directly handle user input. This works even better with type hinting.
If a function should always produce a certain result given the correct input, any failure of the function to produce that result is a RuntimeException or LogicException or some other kind of exception.
If a function may or may not produce some kind of result, false is a legitimate return value. Functions which deal with user input and therefore get very arbitrary input values are often fine with returning false.
Some examples:

*

*getDatabaseConnection() is perfectly correct in throwing a RuntimeException or similar if it cannot establish a connection to the database. This is an exceptional circumstance in which case no work can continue.

*transformFooIntoBar(Foo $foo) is correct in throwing some form of exception if it cannot return a Bar instance, for whatever reason that may be. The function has a clear purpose and a type checked input value. If it cannot do its job under such clear conditions, something is clearly wrong and must be fixed. Ergo, an exception.

*checkIfUserExists($id) may well return false, because its job is to return a thumbs up or thumbs down. A user not existing is not an exceptional circumstance given this job description.

Where to catch a thrown exception depends on where you want to deal with it. Database connection errors should probably be caught at the very top of the call stack, since you probably cannot do anything if the database is down.
On the other hand, if some module is calling some submodule and half expects that submodule to fail and/or has a contingency plan in case it does fail, the module may catch the exception of the submodule and continue on doing its job. For instance getRSSUpdates() makes a call to a HTTP::fetchContents($url). If the URL returns a 404, the HTTP module may throw an exception, since it cannot return contents under these circumstances. The getRSSUpdates() function is prepared for this though and handles this case as "no updates at this time".


text:
Q: ES6 how to export all item from one file I want to export all methods of a file from another file.
currently I am doing this, and it works. How can I merge below two into 1 export expression
import  * as db  from './web/query';
export default db;

I tried below written 1 line exports but all failed
export *   from './web/query';  //==error
export *  as default  from './web/query';  //==error
export *  as {default}  from './web/query';  //==error
export from from './web/query'; //== error
export default from './web/query'; //== error

Error means
import db from '../db/index';

db is undefined here. However the the first methods works
Inside of file './web/query' looks like
export function foo(){}
export function baar(){}

A: You cannot in ES2016. To create a module namespace object, you need to give it an identifier (like db) in your current module scope, and then re-export that. There's no way around it.
There is however a stage 1 proposal to add the export * as default from … syntax you were trying.

A:
How can I merge below two into 1 export expression

You cannot.
ES2015 (and ES2016) does not provide a syntax that would allow you to import all the named exports from a file and export the object (with those as its properties) as default in a single statement.

A: You can export the named exports of another file with export * from '<FILE>';.
// a.js
export const one = '1';
export const two = '2';

// b.js
export * from './a.js';

// c.js
import { one, two } from './b.js';

A: you can do something like this:
a.js:
const fakeName = "Blabla";
const fakeAge = 33;

module.exports = {fakeName, fakeAge}

b.js:
 const name = "Someone";
 let age = 22;

module.exports = { name, age}

c.mjs:
export  * from './a.js';
export * from './b.js';

index.mjs:
import * as  AllClass from './c.mjs'
export default AllClass

use it in e.g server.mjs:
import AllClass from './index.mjs'

console.log("fakeName:", AllClass.fakeName);
console.log("NAME:",AllClass.name);

It's just hard not to get confused with ESModule imports/exports and CommonJS imports and exports...


text:
Q: Defining a forms auth path erratically redirecting to ReturnUrl after logon I'm having a very erratic problem with forms auth I'm hoping someone can shed some light on. Here's what's in the web.config:
<location path="Admin">
  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>
</location>

And for the auth:
<authentication mode="Forms">
  <forms loginUrl="~/Admin/LogOn.aspx" name="MyAppAdmin" requireSSL="false" path="/Admin" cookieless="UseCookies"/>
</authentication>

There's also a custom membership provider implementing ValidateUser against a credential repository. The app has a master page with a LoginName control.
What seems to be happening is that sometimes a user logs on successfully but the logon page remains rather than redirecting them to the ReturnUrl in the query string. We know they've successfully authenticated because the LoginName control shows their identity and they can always browse off to other secured content.
Unfortunately we can't identify the pattern which causes this. Different browsers, different servers, removing cookies, SSL or no SSL; there's no discernible pattern. The only thing which is clear is that after removing the "path" attribute from the forms node the problem couldn't be reproduced.
Is there anything obviously wrong with this configuration? Any thoughts on a possible cause? Obviously the path attribute isn't essential but it's nice to isolate things a bit further.

A: So I actually found the answer for this right before clicking the submit but have put it in for the sake of having the info on SO. Rick Strahl actually nailed it in this post; it's a case sensitivity problem.
Basically, if you hit "/admin" it redirects you to "/Admin/LogOn.aspx?ReturnUrl=%2fadmin%2fdefault.aspx" then after authentication the cookie is set against the path "/Admin" (defined in the web.config), then you're redirected to "/admin/Default.aspx". The path comparison is case sensitive therefore you're not being identified as authenticated so you're looped back around to the form.
The reason my results were erratic was due to some people manually typing "Admin" and others typing "admin". I wasn't next the the guys doing this and it all sounded just fine over the phone.
Simple answer; get rid of the path attribute. It's too much trouble unless you have absolute confidence the case won't change.


text:
Q: Unity Повернуться в направление и повторять рельеф поверхности 2D Всех с наступающим! Спасибо этому чудесному сообществу!!!

Я не могу решить задачу уровня 7го класса : нужно повернуть 2D объект в направление пути.
Путь представляет множество WayPoints, каждый WayPoint знает нормаль поверхности.
Я умею вращать объект в зависимости от нормали поверхности, В этом случае мы вращаемся вокруг синей мировой оси - повторяя поверхность.:
    transform.rotation = Quaternion.LookRotation(Vector3.forward, wayPoint.normal);

Я могу изменить Scale, чтобы повернуться, но изменять размер мне не подходит, я хочу развернуть на 180 градусов. Выше я получил Quaternion но, я не знаю как с ним работать дальше и как его повернуть...
Так же у меня выходило, что я стаю зависим от компонентов X,Y вектора по отдельности и получается, что начинаются скачки туда сюда, мне хотелось бы не зависеть от отдельных компонентов вектора, а зависеть только от направления (NextWaypoint.Position - WayPoint.Position).normalized. Но при использовании направления мой объект в обратном направлении переворачивается, что вообще не допустимо..
Я нарисовал примерно то, что я имею ввиду - пути и направления в которых надо меняться и немного описания маркировки:

*

*Красные стрелки - направление в сторону куда направляется объект

*Красная сплошная - путь из WayPoints

*Y - ось во круг которой я хочу вращаться и значения вращения.

*Синие линии - это Normal поверхности, где синих линий нет, в этих местах будет игнорироваться повторение поверхности.

*Зеленые стрелочки - объект для вращения

A: я подумал и решил свою задачу. Выкладываю код, который подходит в рамках моей задачи:
// находим направление движения
var dir = nextNode.position - currentNode.position;

// находим угол между направлением пути - dir и взглядом объекта transform.right в 2D
// проверяем если угол больше чем 170 градусов то, вектор направления в другой стороне
// LookLeft булевое публичное свойство, изменяется если направление не правильное
// LookLeft установлено по умолчанию false так как мой объект смотрит изначально вправо.
// LookLeft = !LookLeft применятся пинг-понг, чтобы сменить значение.
if(Vector2.Angle(transform.right, dir) > 170)
{
    LookLeft = !LookLeft;
}

// в моём графе путей, ноды хранят нормаль поверхности всегда статично (это важно)!!!
// получаем нормаль поверхности если RepeatSurface булевое свойство - разрешено.
var surfaceNormal = RepeatSurface ? nextNode.normal : Vector2.up;

// surfaceRotatation - создаем вращение повторяя поверхность
var surfaceRotatation = Quaternion.FromToRotation(Vector2.up, surfaceNormal);

// pathDirectionRotation - создаем вращение в направление пути с помощью булевой LookLeft
// определяем на сколько повернуть объект то есть 180 - влево или 0 вправо.
var pathDirectionRotation = Quaternion.Euler(0, LookLeft ? 180 : 0, 0);

// Умножаем Quaternions чтобы объединить вращение относительно поверхности и
// вращение в сторону пути. Применяем полученное вращение к объекту.
transform.rotation = surfaceRotatation * pathDirectionRotation;

Если я не прав или я допустил ошибку, пожалуйста поправьте меня, я решал задачу несколько дней и я допускаю возможность ошибки!!!


text:
Q: MAUI App Failed to Install (Local device) when built in Release mode I am new to .NET maui, When I try to run my ecommerce app (MVVM databinding)(debug mode) to my locally connected phone then all fine(installing succefully).
But When I change to Release mode and try the same then I am getting error in vs2022 17.5-P1 is that "Failed to install APK".
Thanks in advance.

A: I have come across the same issue and solved it by disabling compiled bindings either globally or at least those that are bound to the class.
e.g)
[XamlCompilation (XamlCompilationOptions.Skip)]
public partial class HomePage: ContentPage
{
…
}


text:
Q: why does Pthread Signal from main, hangs the code? The requirement for the sample application creating using pthread is given below:

*

*A single thread is created from main using Pthread

*Inside thread, Mutex is locked, a counter counts the value and while loop is incremented, While is set to the max count of 10.

*after while loop finishes, the mutex is unlocked.

The above requirement I have tried implementing using pthread
Code is shown below:
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;

int samples = 10;
int count = 0;

struct example
{
    int i;
    int a;
};

void *inc_x(void *x_void_ptr)
{
    pthread_mutex_lock(&count_mutex);
    printf("Thread is locked \n");

    while(count < samples)
    {
    printf("inside While loop \n");

    struct example *E2_ptr;
    E2_ptr = (struct example *)x_void_ptr;
    printf("inside thread count = %d\n",count);
    E2_ptr->a = count;
    E2_ptr->i = (count + 1);
    count ++;
    //pthread_cond_wait(&count_threshold_cv, &count_mutex);
    }

    pthread_mutex_unlock(&count_mutex);
    printf ( "\n Test Successful for Thread\n");

    pthread_exit(NULL);
}

int main()
{

    int x = 100, y = 0,i = 0;
    struct example *E1_ptr;

    E1_ptr->a = 0;
    E1_ptr->i = 0;

    printf("Before\t E1_ptr->a = %d\t, E1_ptr->i = %d\n",E1_ptr->a,E1_ptr->i);

    pthread_t inc_x_thread;

    if(pthread_create(&inc_x_thread, NULL, inc_x, E1_ptr))
    {
    printf("Error creating thread\n");
    }

    if(pthread_join(inc_x_thread, NULL))
    {
    printf("Error joining thread\n");
    }

    for(i  = 0; i<(samples-1); i++)
    {
    if(pthread_cond_signal(&count_threshold_cv))
    {
         printf("Error Signaling thread at sample = %d\n",i);
    }
    }

    printf("after\t E1_ptr->a = %d\t, E1_ptr->i = %d\n",E1_ptr->a,E1_ptr->i);

    pthread_mutex_destroy(&count_mutex);
    pthread_cond_destroy(&count_threshold_cv);
    pthread_exit (NULL);

    return 0;
}

Doubt:
In the above code, the thread executes its function properly and exits.
Once the condition is applied, i.e. the below shown code is uncommented then,
pthread_cond_wait(&count_threshold_cv, &count_mutex);

Then the thread is stopped after 1st iteration of while loop as expected.
The signal is generated from main by the code shown below:
for(i  = 0; i<(samples-1); i++)
{
    if(pthread_cond_signal(&count_threshold_cv))
    {
         printf("Error Signaling thread at sample = %d\n",i);
    }
}

observed that the signal is never sent.
Can someone please guide me, where am I going wrong. I'm a newbie to Pthreads.
Thanks in advance.

A: count_mutex and count_threshold_cv are not initialized, add:
int main()
{
    pthread_mutex_init(&count_mutex, NULL);
    pthread_cond_init(&count_threshold_cv, NULL);
    //...

E1_ptr is not initialized.
There are many ways to solve it:
You can call malloc to allocate memory:
struct example *E1_ptr = malloc(sizeof(struct example));

E1_ptr->a = 0;
E1_ptr->i = 0;

or holds pointer to local variable:
struct example ex;
struct example *E1_ptr = &ex; //malloc(sizeof(struct example));

E1_ptr->a = 0;
E1_ptr->i = 0;

or
struct example ex;
ex.a = 0;
ex.i = 0;

then create thread with pthread_create(&inc_x_thread, NULL, inc_x, &ex)

pthread_cond_signal function does not wait. If a thread is blocked by condition variable pthread_cond_signal function unblocks this thread, otherwise returns immediately without waiting and does nothing. So your for loop with 10 iterations is executed as soon as possible, without any waiting for pthread_cond_wait is called.
So can rewrite your for loop to infinite loop, calling pthread_cond_signal repeatedly.
if(pthread_create(&inc_x_thread, NULL, inc_x, E1_ptr)) {
   printf("Error creating thread\n");
}

while(1) { // INFINITE LOOP
    if(pthread_cond_signal(&count_threshold_cv)) {
         printf("Error Signaling thread at sample = %d\n",i);
    }

    if (taskDone) // testing global flag, if 1 break
        break; // it means inc_x thread has ended
}

if(pthread_join(inc_x_thread, NULL)) { // it was pointed out in comment
printf("Error joining thread\n"); // you need to join at the end of main function
}

taskDone is global int, with 0 as default value. It is set to 1 before pthread_exit is called in inc_x function. Setting/checking taskDone should be wrapped with some synchronization mechanism, for example by adding new mutex or use count_mutex.


text:
Q: How to center buttons when one is larger than the other? Hiyya,
So much like the title says, I've stumbled upon a issue where I cannot get two buttons that are inline centered, when one has more content than the other.
First and foremost, this is what it's currently looking like:

As we can see, the buttons seem okay in the perspective of the text immediately above and below, but since the black button has more text, it seems off in the perspective of the image.
The code is as follows (project is using ancient v2 Bootstrap):

                        <button type="button" class="btn btn-default">Ja, tack!</button>

                        <button type="button" class="btn btn-inverse">Nej tack, avsluta</button>

Proposed solutions have been to set an uniformal width for the buttons (for example 200px), and while it technically works as a plan B, we'd like to consider other possibilities first. Another solution would be to simply not have the buttons inline, but such design changes shouldn't be necessary for something like this (atleast in my opinion/thought process).
We have also experimented with the "hack" of shifting the buttons to the left using margin-properties, but since we allow our clients/customers to change the text at their own discretion, this would not be viable either.
Thankful for any and all help/pointers!

A: Check the code it will be in the center not matter of the buttons width

.span6 {
  display: inline-block;
}
.visible-desktop {
  width: max-content;
  margin: auto;
}

        <button type="button" class="btn btn-default">Ja, tack!</button>

        <button type="button" class="btn btn-inverse">Nej tack, avsluta</button>

A: I would consider using a grid layout so that it can account of varying lengths of text. However, from a UI / UX point of view, equal button sizes in this scenario would look and feel much nicer.

.wrapper {
  width: 500px;
  background: #ebebeb;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  padding:10px;
  text-align: center;
}
.button-wrapper {
  display: grid;
  grid-template-columns: repeat(6, minmax(0, 1fr));
  row-gap: 1.5rem;
  column-gap: 1rem;
}
button {
  box-sizing: border-box;
  border-radius: 5px;
  padding:5px;
  grid-column: span 3 / span 3;
}
.button1 {
  background: blue;
  color: white;
}
.button2 {
  background: black;
  color: white;
}

 Some text some text some text

 Some text some text some text

    <button class="button1"> Ja, Tack! </button>
    <button class="button2"> New tack, avsluta </button>

A: Something like this should work, making it one div instead of two.

        <button type="button" class="btn btn-default">Ja, tack!</button>
        <button type="button" class="btn btn-inverse">Nej tack, avsluta</button>

Maybe fix the gap between between buttons with some margin, or wrap both buttons with a div that has some padding.
There are definitely better ways of doing this (without bootstrap) though :)


text:
Q: How to get the updated values after an APEX call from Javascript I am currently calling an APEX method (in a controller) with variables from Javascript. I would like to reflect the changes made in the controller in the page. I am using an apex:actionFunction to call the method and then I am using another actionFunction to reRender a block of the page. I believe the changes are taking place in the controller (I can make logs of the changes) and I think the rerender is working, but the new values are not being shown on the page. They will only be shown if I force a refresh by pressing a button, or similar.
I have been looking at a number of examples, but I have not found anything useful for this particular issue. Here is a summarized version of my code:
//page

<apex:actionFunction name="rerenderInfoBlock" rerender="InfoBlockContainer" />

...
<apex:actionFunction action="{!runControllerMethod}" name="newCustomerRecruitMonitorSelected" rerender="">
    <apex:param name="monitorId" assignTo="{!monitorId}" value="" />
</apex:actionFunction>

...
runControllerMethod(parameterVar);
rerenderInfoBlock();
alert("{!objectReference.changedProperty}");//this property will not be changed

//controller
public PageReference runControllerMethod(){
    //get the parameters etc and make a change to a few properties
    return null;
}

Is there some step I am missing? I am guessing I have to tell the javascript to somehow go back to the server and get the updated values, but I am not sure how to do this... Would be great if any answers contained links to references. Thanks.

Edit, Here is the output panel that I am trying to rerender:
<apex:outputPanel id="InfoBlockContainer">
    <apex:pageBlock id="InfoBlock" rendered="{!showBlock == true}">
        ...

A: Several possibilities here.

*

*I'm not sure an actionFunction that has no controller action is guaranteed to re-poll the controller. You should just move your rerender property of "InfoBlockContainer" to your newCustomerRecruitMonitorSelected actionFunction.

*Your JS code should be calling newCustomerRecruitMonitorSelected(parameterVar), not runControllerMethod(parameterVar) -- the "name" param of an actionFunction becomes the JS function, while JS knows nothing about the controller param names. (To reduce errors like this on my own part, I generally name my controller methods and my actionFunctions the same thing, where appropriate.) This error would show up in a JS console/debugger.

*a JS actionFunction method fires instantly, and asynchronously does the rerender. Therefore, your alert statement will always return the unchanged property, since it's pretty much a guarantee that the browser will fire it before the async request returns and does the rerender.

Without a little more detail about what you're rerendering and how, it's hard to diagnose further, but start with those.


text:
Q: Why so bad the performance of the NodeJS object creation if num of props greater than 8? I would like to know that there are any limit in NodeJS when create an object which has more than 8 properties? I made a benchmark test and it seems if the object has more than 8 properties, the performance will be bad.
Test suite: https://github.com/icebob/js-perf-benchmark/blob/master/suites/properties.js (full copy at end of question)
The result:

*

*Create object with 1 prop             0%     (62,695,620 rps)   (avg: 15ns)

*Create object with 8 prop        -31.95%     (42,662,752 rps)   (avg: 23ns)

*Create object with 9 prop        -95.79%      (2,640,046 rps)   (avg: 378ns)

Code:
bench.add("Create object with 8 prop", () => {
    let opts = {
        prop1: 5,
        prop2: "",
        prop3: false,
        prop4: 1,
        prop5: 0,
        prop6: null,
        prop7: "Hello",
        prop8: 12345
    };
    return opts;
});

bench.add("Create object with 9 prop", () => {
    let opts = {
        prop1: 5,
        prop2: "",
        prop3: false,
        prop4: 1,
        prop5: 0,
        prop6: null,
        prop7: "Hello",
        prop8: 12345,
        prop9: "asd"
    };
    return opts;
});

Environment:

*

*Windows_NT 6.1.7601 x64

*Node.JS: 6.9.5

*V8: 5.1.281.89

*Intel(R) Core(TM) i5-2400 CPU @ 3.10GHz × 4

Here's the content of the linked test suite above:
"use strict";

let Benchmarkify = require("benchmarkify");
let benchmark = new Benchmarkify("Object properties").printHeader();

let bench = benchmark.createSuite("Create object with many properties");

// ----

bench.add("Create object with 1 prop", () => {
    let opts = {
        prop1: 5
    };
    return opts;
});

bench.add("Create object with 8 prop", () => {
    let opts = {
        prop1: 5,
        prop2: "",
        prop3: false,
        prop4: 1,
        prop5: 0,
        prop6: null,
        prop7: "Hello",
        prop8: 12345
    };
    return opts;
});

bench.add("Create object with 9 prop", () => {
    let opts = {
        prop1: 5,
        prop2: "",
        prop3: false,
        prop4: 1,
        prop5: 0,
        prop6: null,
        prop7: "Hello",
        prop8: 12345,
        prop9: "asd"
    };
    return opts;
});

bench.add("Create object with 20 prop", () => {
    let opts = {
        prop1: 5,
        prop2: "",
        prop3: false,
        prop4: 1,
        prop5: 0,
        prop6: null,
        prop7: "Hello",
        prop8: 12345,
        prop9: "asd",
        prop10: false,
        prop11: 5,
        prop12: "",
        prop13: false,
        prop14: 1,
        prop15: 0,
        prop16: null,
        prop17: "Hello",
        prop18: 12345,
        prop19: "asd",
        prop20: false
    };
    return opts;
});

bench.run();

A: As far as I know - yes.
Object in v8 engine has two object representations:

*

*fast with limited amount of props

*slow with unlimited props

For new objects V8 engine allocates memory for "FAST 8 properties object" by default which should cover most use cases.
If the amount of properties exceeds this limit - it rebuild object into more SLOW form, but which allows to have unlimited amount of props inside.
By the way this doesn't related to the new object instantiation (like new X()):
Time from time V8 engine recounts amount of props for new objects(per class/internal type). So if your code creates complex classes - engine will start to create FAST objects with more properties by default for this class/internal type.

PROOF:
The details about memory management for V8 engine can be found here http://jayconrod.com/posts/52/a-tour-of-v8-object-representation
For the new object constructed without a class (like var a = {}) - all properties go to fixed array, called in article "Extra properties"
Engine allocates space for 8 elements in fixed array by default
After fixed array is full - object is rebuilt into dictionary here
Prototypes and system objects are always FAST, they use different rebuilding procedure when fixed array is full.


text:
Q: DataGridView null при чтение данных Программка многопоточно вставляет / забирает данные из ячеек таблицы.
И есть одно узкое место, поток вставляет данные в ячейку и он же через какое то количество мс забирает эти вставленные данные.
И тут бывает вылетает исключение - якобы там null, ну т.е. null - я думал меня спасёт Thread.Sleep(1000), но если я правильно понял - подобное ожидание не спасёт оно тупо вешает всё и отрисовке не поможет.
Я ещё умудрился над этим Thread.Sleep(1000) поставить метку и в случае исключения переходить туда с помощью goto - ну и конечно же у меня всё зациклилось.
Правильно я понимаю ? Они ещё не успели каким то образом зарегистрироваться в ячейке, а я пытаюсь их уже забрать ?
Как всё же получить такие данные ?
Так заливаю:
BeginInvoke(new Delegate(() => { dataGridView["column1", nomStroki].Value = value; }));

И в другом методе этого же потока забираю:
if (dataGridView["column1", nomStroki].Value.ToString() == "Нет данных")

NullReferenceException


text:
Q: Me da como respuesta el texto incorrecto Tengo que hacer un programa en el que me diga si un numero es perfecto, Ejemplo: 6 es perfecto porque 6 = 1+2+3. Soy bastante nuevo así que ténganme paciencia, gracias.
#include <iostream>

using namespace std;

bool EsPerfecto(int num);

int main(){
    int n;
    bool sumadivisor;
    cout << "Digite numero para comprobar si es perfecto: " << endl;
    cin >> n;
    sumadivisor = EsPerfecto(n);
    if(sumadivisor) {
        cout << "Es perfecto." << endl;
    } else {
        cout << "No es perfecto." << endl;
    }
    return 0;
}
bool EsPerfecto(int num)
{
    int i;
    for (i = 1; i < num; i++)
    if (num % i == 0)
    return true;
    else return false;
}

A: El fallo principal que veo es que la función EsPerfecto no devuelve si un número es perfecto o no, simplemente va incrementando la variable i de 1 en 1 y comprueba si el siguiente valor de i es módulo del número introducido. Esto quiere decir que si metes cualquier número te dirá siempre true porque el módulo 1 de cualquier número es siempre 0 y el valor de i comienza siempre en 1 en el bucle.
Además de que tienes puestos los dos return dentro de la comprobación del for, de forma que ya directamente el primer valor que comprueba del for será decisivo para que salga del bucle y no podrá comprobar los siguientes (Por ejemplo, en caso de que empieces por i=2 te devolverá false siempre que num sea impar porque no pasará del primer caso)
Una posible solución sería modificar la función EsPerfecto por otra que vaya acumulando el valor de i en otra variable y sea esa variable nueva la que se compruebe si es igual al número introducido:
bool EsPerfecto(int num)
{
    int i;
    vector<int> divisores;
    for (i = 1; i < num; i++) {
        if(num % i == 0)
            divisores.push_back(i);
    }
    int sumRes = 0;
    for (int divisor : divisores) {
        sumRes += divisor;
    }
    if (num == sumRes)
        return true;
    return false;
}

Probablemente haya soluciones más optimizadas pero esta es la solución más rápida que he podido proporcionarte dado el código que has pasado, simplemente modifica tu función EsPerfecto por esta nueva y debería ir.
EDIT: Con esta nueva modificación he utilizado la clase vector para acumular los divisores, podrías utilizar cualquier otra de la stl o utilizar la tuya propia, en este caso bastaría con añadir #include <vector> al principio del código.


text:
Q: ActiveDataProvider not returning actual data if merged with other params for REST api - Yii2 I made an application which is providing data to my mobile devices via rest api.
I am having data coming from various tables based on the relations established between them via keys(Foreign/Index).
I am using ActiveDataProvider to extract required data from tables.
$dataProvider = new ActiveDataProvider([
   'query'=>$query
]);

This is working great based on the query I set and returning data in JSON format as I needed when I return it as follows:
return $dataProvider;

What I want is:

*

*Return data of this ActiveDataProvider along with some other data. Like all data from ActiveDataProvider in one object and other data say some flag values in another object.

For example:
[
  "some_other_data":{
     -----
  },
  "dataProvider": {
    "device_id": "552255445511",
    "dated": "2016-03-15 23:00:04",
    "speed": "73.30",
    "power": null,
    "ignition": null,
    "ac": null,
    "address": "52",
    "latitude": "30.4575",
    "longitude": "76.1",
    "devices": {
      "vehicle_number": "UK 6S Z 5555",
      "vehicle_type": "0"
    }
  }
]

The issue is when I return it as:
return array('some_other_data'=>$somedata, 'dataProvider'=>$dataProvider);

then the result is like:
{
  "some_other_data": 0,
  "dataProvider": {
    "query": {
      "sql": null,
      "on": null,
      "joinWith": null,
      "select": null,
      "selectOption": null,
      "distinct": null,
      "from": null,
      "groupBy": null,
      "join": null,
      "having": null,
      "union": null,
      "params": [],
      "where": {
        "tk103_current_location.device_id": {
          "sql": null,
          "on": null,
          "joinWith": null,
          "select": [
            "device_id"
          ],
          "selectOption": null,
          "distinct": null,
          "from": null,
          "groupBy": null,
          "join": null,
          "having": null,
          "union": null,
          "params": [],
          "where": {
            "transporter_id": 22
          },
          "limit": null,
          "offset": null,
          "orderBy": null,
          "indexBy": null,
          "modelClass": "api\\modules\\v1\\models\\Tk103Devices",
          "with": null,
          "asArray": null,
          "multiple": null,
          "primaryModel": null,
          "link": null,
          "via": null,
          "inverseOf": null
        }
      },
      "limit": null,
      "offset": null,
      "orderBy": null,
      "indexBy": null,
      "modelClass": "api\\modules\\v1\\models\\Tk103CurrentLocation",
      "with": null,
      "asArray": null,
      "multiple": null,
      "primaryModel": null,
      "link": null,
      "via": null,
      "inverseOf": null
    },
    "key": null,
    "db": null,
    "id": null
  }
}

i.e. ActiveDataProvider is returning the schema like data in the result, not the actual result.
Please give me a clue or hint how to force this dataProvider to return actual data, not the architecture by which it is trying to return data.

A: Try
return array('some_other_data'=>$somedata, 'dataProvider'=>$dataProvider->getModels());


text:
Q: How to receive POST response from another application through browser Error:

Cannot POST /responsehandler

In app-routing.module.ts configured like below
{path:'responsehandler',component:ResponsehandlerComponent},

My doubt is how to get the post response body (data) in Angular through the browser.
Actually from Angular, I did redirect to another URL (another project), They validating the request and show some information in the browser, at last, they redirect to my angular using a browser, they sent in a post (method type) and data in the body through browser redirection.
   <form action="http://localhost:4200/responsehandler" method="post">
      <input type="text" id="name" name="name" value="Some">

      <input type="text" id="age" name="age" value="11">

      <input type="submit" value="Submit">
    </form>

Image:

A: the routes you configure in the routing module is for page navigation via routes only, Angular is not an api for server interaction.
you can call an api in angular to get response from a server.


text:
Q: Isomorphism between multiplicative R and R x integers modulo 2 Got this question on a recent exam, and though it may seem trivial, I cannot seem to figure it out.
Show that $\mathbb{R}^{*} \cong \mathbb{R} \times \mathbb{Z}/2\mathbb{Z}$.
I had one of these questions in the past, however the underlying set of multiplicative $\mathbb{R}$ was given to be only positive ($\mathbb{R}_{>0}$) making it easy to define the isomorphism using a logarithm.
I can see intuitively that the integers modulo 2 group is ment to preserve whether the input is even or uneven, however I cannot figure out a suiting isomorphism. Any tips?

A: Rough idea: Write $x\in\mathbb{R}$ as $x=\sigma t$ where $\sigma=\pm 1$ and $t=|x|$. Then apply the log idea to the $t$ part; the $\sigma$ part will behave like the integers mod 2.


text:
Q: Polymer LitElement & Angular - render never called, no content displayed I want to use Polymers LitElement in my Angular application.
For that, I created an example component (test.js) in the assets folder of my application, and imported it in the index.html.
test.js:

// Import the LitElement base class and html helper function
import { LitElement, html } from '../../../node_modules/lit-element/lit-element';

// Extend the LitElement base class
class Test extends LitElement {

  render(){
    return html`

Test works!

    `;
  }
}
// Register the new element with the browser.
customElements.define('ti8m-test', Test);

index.html:

<!doctype html>

  <meta charset="utf-8">
  <title>NgInAction</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

I installed lit-element in the comp-new directory, using npm install --prefix ./ lit-element.
I also did a npm install lit-element in the project itself, so the npm module is definitely available.
However, when I run my Angular application using ng serve, and navigate to the URL where I included my test component, I find my component in the DOM (using the inspector), but there is no content displayed.
Also, when I put a console.log into the render function, I never see the output in the browser. So it looks like the method is never actually called.
Here's how it looks in the DOM:

Here's my project structure:

A: Alright. Once again, solving my own problems, hoping to help anyone with a similar issue ;)
First off: My approach was not the best. I wouldn't recommend putting your custom elements into the assets folder. Usually you would get your custom elements by installing an npm module, so I moved the components into the project structure. Like this, I could also get rid of the additional node_modules and the imports got a lot easier to handle.
How to use Lit Element Custom Components in Angular:

*

*Install lit-elemnt in your project: npm install --save lit-element

*Create a folder in your src/app folder for all the custom components (i.e. custom-components)

*Create your component (JS or TS, I chose TS)

import { LitElement, html } from 'lit-element';

// Extend the LitElement base class
// export the class, so it can be imported where it is needed
export class Ti8mTestComponent extends LitElement {

  /**
   * Implement `render` to define a template for your element.
   *
   * You must provide an implementation of `render` for any element
   * that uses LitElement as a base class.
   */
  render() {
    /**
     * `render` must return a lit-html `TemplateResult`.
     *
     * To create a `TemplateResult`, tag a JavaScript template literal
     * with the `html` helper function:
     */

    console.log('test-component', this);
    return html`

Test works!

For real though!

    `;
  }
}

Notice how I left out the customElements.define('ti8m-test', Ti8mTestComponent) part. We'll get to this in a second.

*You can define your custom elements wherever you want in your code. I suggest either main.ts, an NgModule, or in the constructor of the component where you want to use the element.
import {Ti8mTestComponent} from './app/custom-elements/ti8m/test';
...
customElements.define('ti8m-test', Ti8mTestComponent);
That's it! Your Lit Element should be visible in your application now! :-)
Notes:

*

*I had to update to Angular 7, since that's the first version to use Typescript > 3, which is needed for the Lit Element npm module. (Lit Element is using type unknown in its code, which was introduced by Typescript 3)

*Also I had to change the target in tsconfig.json to es2015. (otherwise you'll run into class constructors must be invoked with |new| console errors)

Have fun! I hope it helps.


text:
Q: Upper 3-dB frequency of differential amplifier with current mirror load vs with resistive load In the BJT case, why is it that the upper 3-dB frequency of a differential amplifier with a current-mirror load (1st picture) is lower than that of a differential amplifier with a purely resistive load (2nd picture)?

A: Resistors as loads immediately reduce the potential DC gain of your circuit compared to using a current source. But, using resistors also means that the 3 dB point is higher compared to using a current source load. However, if you looked at both circuits side-by-side and compared gain numbers at the 3 dB point of the resistor loaded circuit, you will find that their absolute gain values are pretty similar or slightly favouring the current source loaded amplifier.
It's like comparing an op-amp circuit with a gain of ten versus an op-amp circuit with a gain of 100. both run out of steam at the same high frequency point but the higher-gain circuit has a lower frequency 3 dB point: -

As you can see, when configured as an amplifier with a DC gain of 100, it will have a 3 dB point around 100 kHz whereas when configured as a gain of ten amplifier, the 3 dB point is around 1 MHz - same amplifier but different resistor values.

A: Q4 will have Miller Effect multiplication of the Cob of Q4.
You might also consider the Source resistance, that drives the bases of the two differential transistors.


text:
Q: 100% height divs in bootstrap I have this piece of code with bootstrap...

CHAT

text

ONLINE

text

I need to have the columns be 100% height and panels in that columns be 100% also.
Thanks for ur help.

A: If you have set the height of the class to 100% and it does not seem to make a difference, make sure it's parent object (ex. body or HTML) are also set to be 100%

A: Here is something that might help you.
Live sample HERE
HTML

    // Contents

CSS
.your-div {
    background-color: #ccc;
}

JS
//Gets the current height of the screen.
var screenHeight = $(window).height();
var yourDiv = $('.your-div');

// Assign that height to the .row
yourDiv.css({
    'height': screenHeight + 'px',
});

// This makes the div's height responsive when you resize the screen or the window of the browser.
$(window).resize(function () {
    screenHeight = $(window).height();
    yourDiv.css({
        'height': screenHeight + 'px',
    });
});

Live sample HERE

A: Have you tried:
 .row {
   min-height: 100vh; }


text:
Q: Access file names(or mappings) from specific dependency in sbt I would like to access all of the content of one of my dependencies during the build. To be more precise, I want to include the scaladoc of one of my dependencies into a site generated with sbt-site. I think I could do that with mappings or addMappingsToSiteDir as described here but for that I need to be able to get mappings of this dependency somehow.

A: I have solved the problem with following code.
(update in Compile).value
    .select(configurationFilter("provided"))
    .filter(x => x.name.contains(s"mypackage") && x.name.contains(s"javadoc"))
    .flatMap(unpackjar(_, target.value / "mypackage"))

def unpackjar(jar: File, to: File): Seq[(File, String)] = {
  println(s"Processing $jar and saving to $to")
  IO.unzip(jar, to)
  Path.allSubpaths(to).toSeq
}


text:
Q: iOS: How to control sound volume (not ringer) when user presses button? I have some speech in my app.
The iPhones buttons only affect the volume while the phone is speaking. As soon as the sentence finishes, the buttons affect the 'ringer' volume.
But I would like for the buttons to always affect 'volume' when my app is open. How can I achieve this?


text:
Q: React Native Expo SDK upgrade to 36 I am working on my React Native app built with expo. Today I was really bothered by the console that all the time was reminding me that there is a new version of expo, so I decided to update it. I followed the steps given on the expo docs. Everything in update seemed working fine but in nearly a half command :
expo upgrade stacked and returned me this error expo NPM ERR
I listed previous solutions that I should check my package.json file and app.json file to match the sdk versions but I got all three set up on the same :
{
  "expo": {
    "name": "bakalarka",
    "slug": "bakalarka",
    "privacy": "public",
    "sdkVersion": "36.0.0", ...

and my package.json file:
"dependencies": {
    "core-js": "^3.6.4",
    "expo": "^36.0.0",
    "expo-font": "~8.0.0",
    "expo-image-picker": "~8.0.1",
    "expo-linear-gradient": "~8.0.0",
    "linear-gradient": "^1.0.6",
    "moment": "^2.24.0",
    "react": "16.9.0",
    "react-dom": "16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz", ...

When I just want to start the app my Android emulator shows me error as: React native version mismatch.
 Does anyone know where might be the problem?
 Thank you in advance! :)

A: Execute expo update from your project.

A: Try replacing your last line with:
"react-native": "https://github.com/expo/react-native/archive/sdk-36.0.1.tar.gz",

A: Have you tried following?

*

*deleting your node_modules

*npm install

A: use it
ncu -u
to your cmd, it will update your expo SDK


text:
Q: Boxes with equal height I am looking for a simple way to make the following boxes the same height.
\documentclass{article}

\setlength{\parindent}{0pt}

\begin{document}

\fbox{\hbox to 0.3\linewidth{\vbox{test}}}%
\hfill
\fbox{\hbox to 0.3\linewidth{\vbox{test\par{}test\par{}test}}}%
\hfill
\fbox{\hbox to 0.3\linewidth{\vbox{test\par{}test}}}

\end{document}

I have experimented with calculating the maximum of the heights of the boxes and setting them with the settobox package but I am wondering whether there might be a simpler way. Please note that I do not know the height of any of the boxes beforehand and that I am looking for a method that also scales when there are more than three boxes.

A: \documentclass{article}
\begin{document}
\fbox{\parbox[b][2.5\baselineskip]{0.3\linewidth}{test}}
\fbox{\parbox[b][2.5\baselineskip]{0.3\linewidth}{test\par{}test\par{}test}}
\fbox{\parbox[b][2.5\baselineskip]{0.3\linewidth}{test\par{}test}}
\end{document}

\parbox[<vpos>][<height>]{<width>}{<contents>}

or for a variable height which needs a test:
\documentclass{article}
\newsavebox\VBox
\begin{document}
\savebox\VBox{\parbox{0.3\linewidth}{test\par test\par test\par}}

\noindent
\fbox{\parbox[b][\dimexpr\ht\VBox+\dp\VBox]{0.3\linewidth}{test}}
\fbox{\parbox[b][\dimexpr\ht\VBox+\dp\VBox]{0.3\linewidth}{test\par test\par test}}
\fbox{\parbox[b][\dimexpr\ht\VBox+\dp\VBox]{0.3\linewidth}{test\par test}}

\end{document}

A: This could be a another job for tcolorbox, if you like. Its option equal height group allows to set a group of boxes to the same height. The example code below produces a new kind of \fbox called \mybox here. It has an optional parameter to specify another equal height group, if you have several ones.
My example is specific, of course, but the option can be used for any number of boxes and does not need xparse which I used for the example. The current version 3.12 (2014/07/29) describes the option on page 42 of the documentation.
Note: The example has to be compiled twice.
\documentclass{article}

\usepackage[xparse]{tcolorbox}
\usepackage{lipsum}
\setlength{\parindent}{0pt}

\begin{document}

\NewTotalTColorBox{\mybox}{ O{once} +m }{size=fbox,sharp corners,
  colframe=blue!50!black,colback=yellow!10!white,
  width=0.3\linewidth,nobeforeafter,equal height group=#1}{#2}

\mybox{test}%
\hfill
\mybox{test\par{}test\par{}test}%
\hfill
\mybox{test\par{}test}\par

\bigskip

{
\footnotesize
\mybox[other]{\lipsum[1]}%
\hfill
\mybox[other]{\lipsum[2]}%
\hfill
\mybox[other]{\lipsum[3]}\par
}

\end{document}


text:
Q: Use Same BindingSource in 2 LookUpEdit Can i use the same BindingSource for two DevExpress LookUpEditand while changing the first to reflect the other one while displaying different properties of the datasource?

A: I'd say yes. Did you actually try it?


text:
Q: How to start an external jar in the same JVM and still be able to terminate current main() I'm particularly new to Java, therefore my question could be total BS, but I am faced with the challange of creating an Updater Wrapper (java app) to an existing Java Application, of which I cannot get my head wrapped around.. The issue I'm facing is, that we don't want to spin up a second and a third JVM each time we have to start a new jar, but Step 5)'s termination is blocked by the Thread of the Updater, which was started from Classloader of the Updater.jar.
Concept:

*

*Current version of App gets triggered to check for updates

*Starts Updater.jar

*OnUpdateAvailable -> closes incoming connections and saves application state and its objects

*Sends ReadyForUpdate Signal to Updater on socket

*Current application terminates.

*Updater replaces Application executable and resources

*Updater launches New Version of Application.jar with argument to resume to its previous state

*Updater waits for Application -> to initialize successfully

*Updater terminates

*New version of Application is up and running

Question: Is there a way to use the same Virtual Machine to start first the updater and then the new version of the application from the updater or should we go ahead with the separate JVMs?
java version: 1.7.0_05-icedtea
OpenJDK 64-Bit Server VM (build 23.0-b21, mixed mode)

A: I think that it would be far simpler to do this with a separate virtual machine and a wrapper script.
Your problem at step 5 is that it requires the application to "shut down" without calling System.exit and without running the shutdown hooks:

*

*This could require major re-engineering of your application code-base.

*Even after you've done that, you still have the problem that old application state is likely to "linger" via objects loaded using the old classloader.  Getting rid of that could be really difficult.  And if you don't then:

*

*you've got a permgen leakage,

*you may have a non-permgen memory leaks (e.g. via statics in classes that have been replaced), and

*you may have leakage of application state that could cause problems for the "relaunched" application.


text:
Q: I get a type error when importing tensorflow So I have this line of code import tensorflow but whenever I run it I get this error
  File "C:\Users\bartl\Documents\PythonProjects\TensorFlowMachineLearningTutorials\LinearRegression.py", line 1, in <module>
    import tensorflow
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 41, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\__init__.py", line 64, in <module>
    from tensorflow.python.framework.framework_lib import *  # pylint: disable=redefined-builtin
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\framework_lib.py", line 52, in <module>
    from tensorflow.python.framework.importer import import_graph_def
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\importer.py", line 28, in <module>
    from tensorflow.python.framework import function
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\function.py", line 36, in <module>
    from tensorflow.python.ops import array_ops
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\ops\array_ops.py", line 429, in <module>
    listdiff.__doc__ = gen_array_ops.list_diff.__doc__ + "\n" + listdiff.__doc__
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

I have only just installed tensorflow using pip install tensorflow and I went to check if it installed properly but I keep getting this error message. Does anyone know how to fix this?
EDIT:
I get this error from reinstalling tensorflow
ERROR: Exception:
Traceback (most recent call last):
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in _main
    status = self.run(options, args)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\cli\req_command.py", line 185, in wrapper
    return func(self, options, args)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\commands\install.py", line 333, in run
    reqs, check_supported_wheels=not options.target_dir
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 179, in resolve
    discovered_reqs.extend(self._resolve_one(requirement_set, req))
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 362, in _resolve_one
    abstract_dist = self._get_abstract_dist_for(req_to_install)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 314, in _get_abstract_dist_for
    abstract_dist = self.preparer.prepare_linked_requirement(req)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\operations\prepare.py", line 469, in prepare_linked_requirement
    hashes=hashes,
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\operations\prepare.py", line 259, in unpack_url
    hashes=hashes,
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\operations\prepare.py", line 130, in get_http_url
    link, downloader, temp_dir.path, hashes
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\operations\prepare.py", line 277, in _download_http_url
    download = downloader(link)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\network\download.py", line 189, in __call__
    resp = _http_get_download(self._session, link)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\network\download.py", line 157, in _http_get_download
    stream=True,
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\requests\sessions.py", line 543, in get
    return self.request('GET', url, **kwargs)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_internal\network\session.py", line 421, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\cachecontrol\adapter.py", line 44, in send
    cached_response = self.controller.cached_request(request)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\cachecontrol\controller.py", line 145, in cached_request
    resp = self.serializer.loads(request, cache_data)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\cachecontrol\serialize.py", line 97, in loads
    return getattr(self, "_loads_v{}".format(ver))(request, data)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\cachecontrol\serialize.py", line 184, in _loads_v4
    cached = msgpack.loads(data, raw=False)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\msgpack\fallback.py", line 129, in unpackb
    ret = unpacker._unpack()
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\msgpack\fallback.py", line 670, in _unpack
    ret[key] = self._unpack(EX_CONSTRUCT)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\msgpack\fallback.py", line 670, in _unpack
    ret[key] = self._unpack(EX_CONSTRUCT)
  File "C:\Users\bartl\AppData\Local\Programs\Python\Python37\lib\site-packages\pip\_vendor\msgpack\fallback.py", line 683, in _unpack
    return bytes(obj)
MemoryError

A: This is probably a broken installation, since the error comes from importing the package.
Try to reinstall tensorflow with
pip install -I tensorflow

Also, the tensorflow web page says that it needs a "newer version" of pip, so you might want to update pip, too. (Before installing tensorflow)
python -m pip install -U pip

Memoryerror when trying to install Tensorflow
As mentioned here and here, try reinstalling without caching:
pip install -I --no-cache-dir tensorflow


text:
Q: Calculated property isn't filled by Hibernate I've made a calculated property with @Formula annotation on one of my entities:
@Entity
@Table(name="PERSON")
public class Person {

    @Searchable(name = "First name")
    private String firstName;

    @Column(name = "FIRST_NAME", nullable=false)
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Searchable(name = "Last name")
    private String lastName;

    @Column(name = "LAST_NAME", nullable=false)
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Formula("FIRST_NAME || ' ' || LAST_NAME")
    private String loFstLstName;

    public String getLoFstLstName() {
        return this.loFstLstName;
    }

    public void setLoFstLstName(String loFstLstName) {
        this.loFstLstName = loFstLstName;
    }
}

The problem is that I have only nulls in persons list in the following code:
Query q = entityManager.createQuery("SELECT loFstLstName FROM Person");
List persons = q.getResultList();

PERSON table contains records having values different from null in FIRST_NAME and LAST_NAME fields. I'm using Hibernate 3.3 with PostgreSQL 8.4.9. What am I doing wrong?

A: You should not mix different access types (i.e. placement of annotations on properties and on fields) inside the same entity (unless you explicitly configure it with @Access). Try the following:
@Formula("FIRST_NAME || ' ' || LAST_NAME")
public String getLoFstLstName() {
    return this.loFstLstName;
}


text:
Q: ADFS understanding possibilities I'm sorry if this is a stupid question. I've read many articles about ADFS setup and what-not, but what I'm failing to understand (since this is not my primary area of work or interest) is if its actually capable of handling what I need handled.
That is: I have a Sharepoint server on domain "domainA". Now, I've been told that using ADFS, I can "delegate" permissions to other external AD's. The way I'm understanding it is, that I can say this other company using "domainB" is allowed to login to my sharepoint server? Is this at all correct? So users of both "domainA" and "domainB" is allowed to login, and I can set sharepoint permissions with users of both AD's?

A: ADFS is an instance of a Security Token System (STS).
SP 2010 has its own STS which can be federated with an instance of ADFS in Domain A which allows users to authenticate via the Domain A AD. These users are configured to receive a set of claims from the Domain A AD which SP 2010 uses as permissions (i.e. authorisation).
If you have another domain - Domain B - the normal practice is to install another instance of ADFS on that domain and then federate the two ADFS. These users will also receive a set of claims.
Now users in Domain A authenticate on the Domain A AD and users in Domain B authenticate on the Domain B AD and both have access to the SP2010 application.
To decide where to authenticate, the user will be presented with a Home Realm Discovery screen which will ask them where they want to authenticate. This is out-of-the-box behaviour.
For anything ADFS related, look here.


text:
Q: Webpack server configuration + external libs I have the following webpack configuration file:
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const LiveReloadPlugin = require('webpack-livereload-plugin');
const path = require('path');

module.exports = {
  entry: [
    'webpack-dev-server/client?http://0.0.0.0:2000', // WebpackDevServer host and port
    'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
    './app/index.tsx'
  ],
  output: {
    path: __dirname + '/dist/',
    filename: 'bundle.js'
  },

  devtool: 'source-map',

  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },

  module: {
    loaders: [
      {
        test: /\.tsx?$/,
        loaders: ['react-hot', 'ts'],
        include: path.join(__dirname, 'app')
      }
    ],

    preLoaders: [
      'source-map-loader'.
      {test: /\.js$/, loader: 'source-map-loader'}
    ]
  },

  plugins: [
    new CopyWebpackPlugin([
      {from: './app/index.html', to: './dist/index.html'}
    ]),
    new webpack.HotModuleReplacementPlugin()
  ],
  builds.
  externals: {
    'react': 'React',
    'react-dom': 'ReactDOM'
  }
};

and here is my server configuration:
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.config');

new WebpackDevServer(webpack(config), {
  contentBase: './dist',
  publicPath: config.output.publicPath,
  hot: true,
  historyApiFallback: true,
  open: 'http://localhost:2000'
}).listen(2000, 'localhost', function (err, result) {
  if (err) {
    return console.log(err);
  }

  console.log('Listening at http://localhost:2000/');
});

I want to be able to access the application from root path: http://localhost:2000 and not http://localhost:2000/dist.
One more thing, is there any way to move all the external dependancies from node_modules to dist with webpack (without the need to include the script tag in the index.html file)?

A: on you server configuration change your public path to
publicPath: '/',

A: First of all for set application start point you need to set publicPath to "/" or publicPath: 'http://localhost:2000'
Your second question
Is there any way to move all the external dependancies from node_modules to dist with webpack?
Yes
You can use different file just for external modules and bundle that file. You don't need to take care of index.html file let webpack plugin HtmlWebpackPlugin take care of it.
First step set entry points for your app
entry: {
        'vendors': './src/vendors.ts',//your external libraries
        'app': './src/main.ts' //your app
}

and out put
output: {
    publicPath: '/',
    filename: '[name].js'//this will generate two different files app.js, vendor.js
}

How to add HtmlWebpackPlugin?
Add this in you plugins
new HtmlWebpackPlugin({
     template: "./src/index.html",
     minify:false
})

Now it will place script tags for you


text:
Q: real time json communication between php server and android java I have a java code that accepts jsonObject from php server to my android application by sending a data to the server:
requestQueue = Volley.newRequestQueue(this);

    request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);

                user_id = jsonObject.getJSONObject("user").getInt("user_id");;
                textView.setText(jsonObject.getString("msg"));

                saveInfo();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //Toast.makeText(context, "Please check your internet connection.", Toast.LENGTH_LONG).show();
            AlertDialog.Builder a_builder = new AlertDialog.Builder(getApplicationContext());
            a_builder.setMessage("Please check your internet connection.").setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            AlertDialog alertDialog = a_builder.create();
            alertDialog.setTitle("Network failure!");
            alertDialog.show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> hashMap = new HashMap<String, String>();

            hashMap.put("username", "testing");
            hashMap.put("password", "testing");

            return hashMap;
        }
    };
    requestQueue.add(request);

Now, How can I receive jsonObject from the server in real time without any user actions?
automatically update the data from my android app when the data from the server changes.


text:
Q: Devspace tool. How to deploy dependeny in --force-build mode I use DevSpace tool to deploy my services into minikube local cluster.
I have two services to deploy: auth-handler and mysql;
auth-handler has the dependency of my-sql in devspace.xml. So it can't start till mysql hasn't been deployed.
auth-handler
dependencies:
  - source:
      path: ../mysql
    namespace: databases

mysql has the image stage. Where in Dockerfile I perform logic to initiate DB by some data.
images:
  backend:
    image: registry.kube-system.svc.cluster.local/mysql
    tags:
      - local
    dockerfile: ./mysql/Dockerfile

The first time, it works fine. But for example when I redeploy services the second time mysql image stage for mysql is skipped because DevSpace caches the image stage if it's already been successfully built. So my DB isn't initialized at this time because image stage skipped.
I can manually deploy mysql with -b / --force-buildto deploy mysql with the forcing launching of image stage but I don't need to manually deploy mysql. I need to initiate deployment of auth-handler and it will initiate deploying mysql in -b / --force-build``-b / --force-build mode.

A: Instead of populating your database within the Dockerfile, I would recommend adding a hook in the hooks section of devspace.yaml which could run devspace enter -c [mysql] -- command-to-populate-db or alternatively, adding an init container to populate the database. This will be a lot more flexible.
For more details on hooks, have a look at the DevSpace docs: https://devspace.sh/cli/docs/configuration/hooks/basics


text:
Q: String lines sorting by Shell Sort I have a text file of 50 string lines of varying length and content. I need to read the file and sort in ascending order. Sorting condition: the number of words in a sentence that start from the letter "a".
public static void main(String[] args) throws FileNotFoundException {
    String token1 = "";
    Scanner inFile1 = new Scanner(new File("E:\\text.txt"));

    List<String> temps = new LinkedList<String>();
    inFile1.useDelimiter(". ");

    while (inFile1.hasNext()) {
       token1 = inFile1.nextLine();
       temps.add(token1);
    }
    inFile1.close();

    String[] tempsArray = temps.toArray(new String[0]);
    for (int i = 0; i < tempsArray.length; i++) {
       System.out.println(tempsArray[i]);
    }

    int cnt = 0; //number of words in the string line
    for (int i=0; i<tempsArray.length; i++) {
        int k=0; //number of words that start from the letter "а"
        System.out.println("Line № = " + i);
        StringTokenizer st = new StringTokenizer(tempsArray[i]);
        while (st.hasMoreTokens()) {
            cnt++;
            String s= st.nextToken();
            if (s.charAt(0)=='a') {
                k++;
            }
        }
        System.out.println("Number of words = " + cnt);
        cnt=0;
        System.out.println("Number of words 'а' = " + k);
    }
}

I use Map as Kau advise me. But Map use unique keys. But my K can have same values and Map can't find an appropriate string element. What other Сollection сan I use?

A: I am assuming you already have the algorithm for shell short to sort an array of integers. Let the method be shellSort(int[] a).
What you can do is create a map with key as k and value as the string representing the line. At the same time we'll create an array of integers that holds all k . Then call the method shellSort on the array of k values. Then read back from the sorted array, look in the map using the array elements as keys. Fetch the corresponding map values (which are the lines) and put them back one by one in tempsArray which should finally have all the lines sorted in the desired way.
Below is the code (untested) just to give an idea.
public static void main(String[] args) throws FileNotFoundException {
   String token1 = "";
   Scanner inFile1 = new Scanner(new File("E:\\text.txt"));

   List<String> temps = new LinkedList<String>();
   inFile1.useDelimiter(". ");

   while (inFile1.hasNext()) {
     token1 = inFile1.nextLine();
     temps.add(token1);
   }
   inFile1.close();

   String[] tempsArray = temps.toArray(new String[0]);
   for (int i = 0; i < tempsArray.length; i++) {
     System.out.println(tempsArray[i]);
   }

   int cnt = 0; //number of words in the string line
   Map<Integer, List<String>> myMap = new HashMap<Integer, List<String>>();
   int[] countArr = new int[tempsArray.length];
   for (int i=0; i<tempsArray.length; i++) {
       int k=0; //number of words that start from the letter "а"
       System.out.println("Line № = " + i);
       StringTokenizer st = new StringTokenizer(tempsArray[i]);
       while (st.hasMoreTokens()) {
          cnt++;
          String s= st.nextToken();
          if (s.charAt(0)=='a') {
             k++;
          }
       }
       countArr[i] = k;
       List<String> listOfLines = myMap.get(k);
       if(listOfLines  == null){
          listOfLines = new ArrayList<String>();
          listOfLines.add(tempsArray[i]);
          myMap.put(k, listOfLines);
       } else{
          listOfLines.add(tempsArray[i]);
       }
       System.out.println("Number of words = " + cnt);
       cnt=0;
       System.out.println("Number of words 'а' = " + k);
    }
    //Call shellsort here on the array of k values
    shellSort(countArr);
    List<String> sortedListOfLines = new ArrayList<String>();
    for(int i=0; i<countArr.length; i++){
       List<String> lineList = myMap.get(countArr[i]);
       if(lineList != null){
          sortedListOfLines.addAll(lineList);
          lineList = null;
          myMap.put(countArr[i], lineList);
       }
    }
 }


text:
Q: What is dilution percentage called? So I am trying to find out what the following method is called, that is used to calculate a dilution.
Soap makers would mix their main ingredient with a base product which dilutes the main ingredient. They would say something like "dilution 25%". This means that they would take 100ml of the base product and add 25ml of the main ingredient.
However, I would say the whole 125ml so the dilution is 31.25% or 68.75% percent depending on which way you are looking at it.
I think maybe dilution is the wrong word to be using, however does this have a name or logic?

A: Assuming, as per my comment above, that you really meant $20\%$, not $31.25\%$, then I understand your confusion. However, there is a good reason you would do it the way they do it: It's practical when you're actually making it.
Consider this: Say you make soap batches of many different sizes, but they all have the same proportions of ingredients: $20\%$ of the finished product is main ingredient, $80\%$ is base ingredient.
When you're writing a recipe, and especially if you're teaching assistants to help you, which would you find less confusing and prone to error? Which one is easiest to do quickly, in the head, on the fly, as you go about your daily routine in the soap factory?

*

*First take the base ingredient, then add main ingredient until $20\%$ of the mix is main ingredient

*First take the base ingredient, then add main ingredient corresponding to $25\%$ of the amount of base ingredient


text:
Q: Como fazer o file_exists procurar na pasta correta? Estou testando se um arquivo existe assim:
if (file_exists('assets/img/items/'. $currentLocation['id'] .'c.jpg')){
    $galleryItem .= '<img src="assets/img/items/'. $currentLocation['id'] .'c.jpg" alt="">';
}

A questão é que o arquivo PHP que está fazendo essa consulta está em assets/external/ então ele não acha o arquivo.
Como fazer pra ele procurar na pasta correta?
Abraços.

A: O comentario do @Denis Rudnei de Souza está correto. Entretanto você pode adicionar um pouco mais de precisão (evitar que em inclusões multiplas de arquivos, o diretorio corrente mude acidentalmente) usando a constante __DIR__ e a função realpath().
A constante DIR vai retornar o diretorio do script atualmente em execução e a função realpath() vai transformar caminhos relativos (../pasta1/../a.php) em caminho absoluto.
Então aplicando à sua situação fica:
$caminho = 'assets/img/items/'. $currentLocation['id'] .'c.jpg';
if (file_exists(realpath(__DIR__ . '/../' . $caminho))){

}


text:
Q: How to change IBM-Cloud cloudfoundry golang app version? When I run command ibmcloud target --cf && ibmcloud cf restart appname, it showed an error, it seems like golang version is invalid, but I can't change it to specify version without root permission, or can it be an old version by creating container for instance?
   Downloading app package...
   Downloaded app package (20.8K)
   -----> Go Buildpack version 1.9.16
          **WARNING** [DEPRECATION WARNING]:
          **WARNING** Please use AppDynamics extension buildpack for Golang Application instrumentation
          **WARNING** for more details: https://docs.pivotal.io/partners/appdynamics/multibuildpack.html
   -----> Checking Godeps/Godeps.json file
   -----> Installing godep 80
          Download [https://buildpacks.cloudfoundry.org/dependencies/godep/godep-v80-linux-x64-cflinuxfs3-b60ac947.tgz]
   -----> Installing glide 0.13.3
          Download [https://buildpacks.cloudfoundry.org/dependencies/glide/glide-v0.13.3-linux-x64-cflinuxfs3-ef07acb5.tgz]
   -----> Installing dep 0.5.4
          Download [https://buildpacks.cloudfoundry.org/dependencies/dep/dep-v0.5.4-linux-x64-cflinuxfs3-79b3ab9e.tgz]
          **ERROR** Unable to determine Go version to install: no match found for 1.11.x in [1.13.14 1.13.15 1.14.6 1.14.7]
   Failed to compile droplet: Failed to run all supply scripts: exit status 16
   Exit status 223
   Cell e0f8b881-1ded-45a7-a004-101d32dc7f6d stopping instance 3d1adec5-7f49-47a1-8005-e25e83521422
   Cell e0f8b881-1ded-45a7-a004-101d32dc7f6d destroying container for instance 3d1adec5-7f49-47a1-8005-e25e83521422
Error staging application: App staging failed in the buildpack compile phase

A: It seems your environment is configured for an older Golang version. And the version was not found in the installed, available buildpacks. You could either look into your manifest and other config files what version is set. Or you could switch to a different buildpack by using the manifest attribute or  a command option (see ibmcloud cf push --help to list the buildpack option).

A: You can specify Go version in the manifest.yml file like this
---
applications:
  - name: my-app-name
    env:
      GOVERSION: go1.8

Supported Go versions can be found in the release notes.
Also, refer getting started with GO guide to understand how to work with GO app on Cloud Foundry


text:
Q: How to update android app without user interaction? I am developing an application in android, i just want to add feature of auto update when the internet is available. I want to update app while app is running as well as when the app not in active mode.
Please reply me with any idea.

A: If you are going to put app to android market, autoupdate will be there automagically.


text:
Q: Выдается последний элемент списка Всем привет! у меня парсер прокси, и тут такая проблема что выдается последний элемент из списка
у меня 400 строчек и выдается только самая последняя, подскажите как решить
Код:
with open('https.txt', 'r') as proxy:
    linesstrok = proxy.readlines()
    for proxy in linesstrok:
        ip= proxy.split(':')[0]
        port = proxy.split(':')[1]

proxy= 'http://'+ ip + ":" + port
print(proxy)

A: with open('https.txt', 'r') as proxy:
    linesstrok = proxy.readlines()
    for proxy in linesstrok:
        ip= proxy.split(':')[0]
        port = proxy.split(':')[1]
        proxy= 'http://'+ ip + ":" + port
        print(proxy)


text:
Q: MVC5 Typeahead Feature I have created a basic typeahead and it works ok but looks pretty rubbish.
I want to create something more like this: http://twitter.github.io/typeahead.js/
Anyone know of where I can find an example of this nature?


text:
Q: Get the item from a collection that contains another collection using linq Say I have a collection of Layerobjects and each Layer may or may not contain a Polygon collection. There's only one Layer that contains the Polygon collection from the Layer collection. How do I obtain this Layer from the collection using LINQ?
Something like
foreach (var layer in Layers)
{
    var item = layer.FirstOrDefault( x =>x.Content is Polygon)
    if (item != null) return layer
}

A: You should be able to get the first layer having a Polygon content like this: (using  Enumerable.Any):
return Layers.FirstOrDefault(l => l.Any(x => x.Content is Polygon));


text:
Q: Proper way of allocating array together with its owner I am trying to dynamically allocate an array of generic type along with kind of primitive control block. Take this as an examplary code of this "control block":
template<class T>
struct my_array{
    T* arr;
    unsigned size;
};

To avoid multiple allocations I try to call allocating new only once. This is code I came up with:
template<class T>
my_array<T> *alloc_new_array(unsigned size){
    unsigned align_mismatch = sizeof(my_array<T>) % alignof(my_array<T>);
    unsigned array_size = size * sizeof(T);
    unsigned struct_size = sizeof(my_array<T>) + align_mismatch ?
        alignof(my_array<T>) - align_mismatch : 0;

    char *memory = new char[array_size + struct_size];

    my_array<T> *arr = new (memory) my_array<T>;
    arr->arr = new (memory + struct_size) T[size];
    arr->size = size;
    return arr;
}

What I am concerned with is:

*

*correctness - I think I took care of struct padding, but there may be something I am missing. Did I count it correctly and will it work properly regardless of platform?

*standard compliance - don't I break any C++ rule and cause UB? I am aware I am doing some pointer magic here and I am unsure if everything is fully legal

A: One example for you:
#include <iostream>
#include <new>
#include <memory>
#include <numeric>

template<class T>
struct alignas(T) WithArray {
    unsigned const size_;

    static void* operator new(size_t size, unsigned elements) {
        return ::operator new(size + elements * sizeof(T));
    }

    static void operator delete(void* p, size_t /*size*/, unsigned /*elements*/) {
        return ::operator delete(p);
    }

    static void operator delete(void* p) {
        return ::operator delete(p);
    }

    T* get_elements() { return reinterpret_cast<T*>(this + 1); }

    T* begin() { return get_elements(); }
    T* end() { return get_elements() + size_; }

    WithArray(unsigned elements)
        : size_(elements)
    {
        std::uninitialized_default_construct_n(get_elements(), size_);
    }

    ~WithArray() {
        std::destroy_n(get_elements(), size_);
    }

    WithArray(WithArray const&) = delete;
    WithArray& operator=(WithArray const&) = delete;
};

int main() {
    unsigned elements = 10;
    std::unique_ptr<WithArray<int>> a(new (elements) WithArray<int>(elements));

    for(int& elem : *a)
        std::cout << elem << ' ';
    std::cout << '\n';

    std::iota(a->begin(), a->end(), 0);

    for(int& elem : *a)
        std::cout << elem << ' ';
    std::cout << '\n';
}

Output:
0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9

alignas(T) + reinterpret_cast<T*>(this + 1) is the C++ version of C99 flexible array member.


text:
Q: MongoMapper Disable Embedded ID Is it possible to disable _id for embedded documents?
For example if have a parent with an embedded child document. it seems kind of pointless for the child to have an id if i don't intend to reference the child from anywhere else.
class Parent
  include MongoMapper::Document
  one :child
  key :name
end

class Child
  include MongoMapper::EmbeddedDocument
  key :name
end

parent = Parent.new(:name => 'parent',
  :child => Child.new(:name => 'child'))

puts parent.to_json

{"id":"4ebeddde51d9e56dcb000006","name":"parent",
"child":{
    "id":"4ebeddde51d9e56dcb000005",
    "name":"child"}}

A: I remember there being talk at one point of removing the _id field for embedded one.  Best bet would be to patch it yourself and then send a pull request.
Otherwise, there isn't a config option to remove the id.  You might be able to over-write to_mongo, if you were adventurous.